← Back to Core Java Course | Chapter 2: Input & Output | Lesson 2 of 6

Java Print Numbers

System.out.println can print numeric values and the results of arithmetic expressions directly, and printf or String.format offer extra control over decimal places and thousands separators.

Printing Numeric Literals

System.out.println can print numeric literals directly, without any conversion, and will display the number exactly as written, whether it's a whole integer or a decimal value.

Example: Printing Numeric Literals

java
public class Main {
	public static void main(String[] args) {
		System.out.println(42);
		System.out.println(3.14);
	}
}

Printing Arithmetic Results

When println is given a mathematical expression, Java evaluates that expression completely first and only then prints the single resulting number, not the original expression text.

Example: Printing Arithmetic Results

java
public class Main {
	public static void main(String[] args) {
		System.out.println(5 + 3); // evaluated first - prints 8, not "5 + 3"
	}
}

Printing Different Number Types

println works with every numeric type in Java -- byte, short, int, long, float, and double -- and prints each one formatted according to that type's own conventions, such as no L suffix ever appearing in the printed output.

Example: Printing Different Number Types

java
public class Main {
	public static void main(String[] args) {
		byte b = 10;
		long l = 100L;
		double d = 2.5;
		System.out.println(b);
		System.out.println(l); // no 'L' suffix in the printed output
		System.out.println(d);
	}
}

Concatenating Numbers with Text

When a number is combined with a String using the + operator, Java automatically converts the number to its String representation before concatenating, which is why numbers can be mixed directly into printed text.

Example: Concatenating Numbers with Text

java
public class Main {
	public static void main(String[] args) {
		int age = 25;
		System.out.println("Age: " + age); // age auto-converted to a String
	}
}

Formatting Numbers in Output

For more control over how a number appears, printf and String.format accept format specifiers like %.2f for a fixed number of decimal places or %,d to insert thousands separators into large integers.

Example: Formatting Numbers in Output

java
public class Main {
	public static void main(String[] args) {
		System.out.printf("%.2f%n", 3.14159);   // 2 decimal places
		System.out.printf("%,d%n", 1000000);    // thousands separators
	}
}
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.