Print Name in Java
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.
Java Program
public class PrintName {
public static void main(String[] args) {
String name = "John"; // store the name in a variable
System.out.println(name);
}
}Output
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().
- 1
String name = "John";declares a variable and stores the text"John"in it. - 2
System.out.println(name)prints the variable's current value, not the literal wordname.
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
Approach 2: Formatted Output with printf
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
Core Logic
Besides plain concatenation, printf and String.format insert values into a template, with control over width and alignment.
- 1Concatenation builds "Hello, John!" from three pieces.
- 2
printf("%s is %d years old.%n", name, age)fills%swith text and%dwith a number. - 3
%-8sleft-aligns the name in 8 characters and%3dright-aligns the age in 3. - 4
name.length()reports how many characters the name has.
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
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).