Escape Sequences and Formatted Output

Escape Sequences

SequenceMeaning
\nnew line
\ttab
\"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.

SpecifierUsed forExample output
%dintegers42
%f / %.2fdecimals (2 places)99.50
%sstrings (any object)Asha
%ca characterA
%bbooleantrue
%nnew line (platform safe)
%5d / %-10swidth (right / left aligned) 42
%,dthousands separator1,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);