Print Name in Java

beginner·  Basics & I/O  ·  Fundamentals

Problem

A string literal is fixed text written directly in the source code, surrounded by double quotes.

Store a name in a variable and print it to the console.

Input
John
Output
John

Java Program

Java
public class PrintName { public static void main(String[] args) { String name = "John"; // store the name in a variable System.out.println(name); } }

Output

John

Core Logic

Storing text in a String variable and printing that variable separates the data from the print statement, a small step up from hard-coding text directly into println().

How It Works
  1. 1String name = "John"; declares a variable and stores the text "John" in it.
  2. 2System.out.println(name) prints the variable's current value, not the literal word name.
Changing the value assigned to name changes what gets printed, without touching the println() call itself.
💡

Key Point: Once a String is created in Java, its content can't change — reassigning name points it at a brand-new String object instead of modifying the original.

Key Concepts

String variableSystem.out.println()

Approach 2: Formatted Output with printf

Java
public class PrintNameFormatted { public static void main(String[] args) { String name = "John"; int age = 28; System.out.println("Hello, " + name + "!"); // concatenation System.out.printf("%s is %d years old.%n", name, age); // printf placeholders String card = String.format("Name: %-8s| Age: %3d", name, age); // padded columns System.out.println(card); System.out.println("Name length: " + name.length() + " letters"); } }

Output

Hello, John! John is 28 years old. Name: John | Age: 28 Name length: 4 letters

Core Logic

Besides plain concatenation, printf and String.format insert values into a template, with control over width and alignment.

How It Works
  1. 1Concatenation builds "Hello, John!" from three pieces.
  2. 2printf("%s is %d years old.%n", name, age) fills %s with text and %d with a number.
  3. 3%-8s left-aligns the name in 8 characters and %3d right-aligns the age in 3.
  4. 4name.length() reports how many characters the name has.
The padded line reads Name: John | Age: 28.
💡

Key Point: %n prints the platform's line separator, which is the recommended way to end a line in printf.

Key Concepts

printf()String.format()format specifierslength()

Interview Questions

Can a String variable hold an empty name?

Yes. "" is a valid empty string, which is different from null (no string at all). Check with isEmpty() or isBlank().

How do you print a name and age in one line?

Concatenate, System.out.println(name + " is " + age), or format, System.out.printf("%s is %d%n", name, age).

Learn the Concept

Related Programs