Java ยท Chapter 5 of 42

Java Output

System.out.println() and System.out.print() are used to print output to the console. println adds a new line after the text, while print does not.

You can concatenate strings and values using the + operator, or use String.format() / printf for more control over formatting.

Syntax
System.out.println(value);
System.out.printf("format", values);

println vs print

println() moves to a new line after printing; print() keeps the cursor on the same line, useful for building output piece by piece.

Formatted output

System.out.printf() works like C's printf, using format specifiers like %d, %s, and %.2f for controlled formatting.

Example 1 (java)
public class Main {
  public static void main(String[] args) {
    System.out.println("Hello");
    System.out.print("No newline ");
    System.out.printf("Pi is %.2f%n", 3.14159);
  }
}
Output
Hello
No newline Pi is 3.14

println adds a newline, print does not, and printf formats the float to 2 decimal places.

Key points

  • println() adds a newline after printing.
  • print() does not add a newline.
  • printf() supports format specifiers like %d and %.2f.
  • The + operator concatenates strings with values.
๐Ÿ’ก Note: Use %n instead of \n in printf for a platform-independent newline.

๐Ÿ“ Quick Quiz

1. Which method adds a newline after printing?

2. Which specifier formats a float to 2 decimals?

3. What operator concatenates a string with a number in Java?