Careeroza
Escape Sequences and Formatted Output
Escape Sequences
| Sequence | Meaning |
|---|---|
\n | new line |
\t | tab |
\" | double quote inside a string |
\' | single quote (needed in char literals) |
\\ | backslash |
Example
public class Main {
public static void main(String[] args) {
System.out.println("Name:\tAsha\nCity:\tPune");
System.out.println("She said \"Hello\"");
System.out.println("Path: C:\\Users\\asha");
}
}Output
Name: Asha City: Pune She said "Hello" Path: C:\Users\asha
printf and String.format
System.out.printf() prints formatted text using format specifiers. String.format() builds the same text as a String.
| Specifier | Used for | Example output |
|---|---|---|
%d | integers | 42 |
%f / %.2f | decimals (2 places) | 99.50 |
%s | strings (any object) | Asha |
%c | a character | A |
%b | boolean | true |
%n | new line (platform safe) | |
%5d / %-10s | width (right / left aligned) | 42 |
%,d | thousands separator | 1,50,000-style grouping |
Example
public class Main {
public static void main(String[] args) {
String name = "Asha";
int age = 22;
double cgpa = 8.4567;
System.out.printf("Name: %s, Age: %d%n", name, age);
System.out.printf("CGPA: %.2f%n", cgpa);
System.out.printf("[%5d] [%-6s] [%06.1f]%n", 42, "Hi", 3.14159);
System.out.printf("Salary: %,d%n", 1250000);
String line = String.format("%s scored %d marks", "Vikram", 91);
System.out.println(line);
}
}Output
Name: Asha, Age: 22 CGPA: 8.46 [ 42] [Hi ] [0003.1] Salary: 1,250,000 Vikram scored 91 marks
Practice
Exercise: Print a price of 1299.5 as Price: Rs. 1299.50 using printf.
Show answer
System.out.printf("Price: Rs. %.2f%n", 1299.5);