Java Print Numbers
In this page:
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
public class Main {
public static void main(String[] args) {
System.out.println(42);
System.out.println(3.14);
}
}
Login to try C/C++/Java/PHP code in the editor
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
public class Main {
public static void main(String[] args) {
System.out.println(5 + 3); // evaluated first - prints 8, not "5 + 3"
}
}
Login to try C/C++/Java/PHP code in the editor
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
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);
}
}
Login to try C/C++/Java/PHP code in the editor
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
public class Main {
public static void main(String[] args) {
int age = 25;
System.out.println("Age: " + age); // age auto-converted to a String
}
}
Login to try C/C++/Java/PHP code in the editor
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
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
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: