Java Tutorial · Java Basics · Lesson 4 of 37

Java Output

Print text and numbers with println, print and printf.

println and print

System.out.println() prints its argument followed by a new line. System.out.print() doesn't add the new line:

Example 1
public class Main {
    public static void main(String[] args) {
        System.out.println("Hello");
        System.out.print("Same ");
        System.out.print("line");
        System.out.println();
        System.out.println(3 + 4);
        System.out.println("3 + 4 = " + 3 + 4);
        System.out.println("3 + 4 = " + (3 + 4));
    }
}

Output

Hello
Same line
7
3 + 4 = 34
3 + 4 = 7

Run this on your computer — see “Get Started” for setup.

Formatted output

printf() and String.format() use format specifiers: %s string, %d integer, %.2f decimal with 2 places, %n new line, %,d with thousands separators, %5d padded to width 5:

Example 2
public class Main {
    public static void main(String[] args) {
        String item = "Coffee";
        double price = 3.5;
        int qty = 2;
        System.out.printf("%s x %d = $%.2f%n", item, qty, price * qty);
        System.out.printf("%,d visitors%n", 1234567);
        System.out.printf("[%5d] [%-5d]%n", 42, 42);
        String code = String.format("ORD-%05d", 42);
        System.out.println(code);
    }
}

Output

Coffee x 2 = $7.00
1,234,567 visitors
[   42] [42   ]
ORD-00042

Run this on your computer — see “Get Started” for setup.

Inside strings, \n is a new line, \t a tab and \" a double quote.

Test yourself

What does System.out.println("1" + 2 + 3); print?

  1. 6
  2. 123
  3. 15
  4. 33
Show answer

Answer: 123

Evaluation goes left to right: "1" + 2 is the string "12", then + 3 gives "123".