Careeroza
Integer and Floating Point Types
Limits and Overflow
Example
Each integer type has a fixed size. Going past the maximum overflows silently and wraps around to the minimum.
public class Main {
public static void main(String[] args) {
System.out.println("byte max: " + Byte.MAX_VALUE);
System.out.println("int max: " + Integer.MAX_VALUE);
System.out.println("long max: " + Long.MAX_VALUE);
int big = Integer.MAX_VALUE;
big = big + 1; // overflow!
System.out.println("int max + 1 = " + big);
long safe = Integer.MAX_VALUE + 1L; // do the math in long
System.out.println("as long = " + safe);
}
}Output
byte max: 127 int max: 2147483647 long max: 9223372036854775807 int max + 1 = -2147483648 as long = 2147483648
Note: Overflow is a classic bug in money and counter code. When values can exceed about 2 billion (for example amounts in paise, file sizes, user IDs), use long.
float vs double Precision
Example
Floating point numbers are stored in binary, so some decimals cannot be stored exactly.
public class Main {
public static void main(String[] args) {
float f = 1.1234567890f;
double d = 1.1234567890;
System.out.println(f);
System.out.println(d);
System.out.println(0.1 + 0.2);
System.out.println(10.0 / 3);
}
}Output
1.1234568 1.123456789 0.30000000000000004 3.3333333333333335
Tip: For money in real applications, use long paise or java.math.BigDecimal, never double. Banking apps follow this rule strictly.
Number Literals
Example
Java supports decimal, hex, binary and scientific notation.
public class Main {
public static void main(String[] args) {
int decimal = 255;
int hex = 0xFF;
int binary = 0b1111_1111;
double scientific = 1.5e3; // 1.5 x 10^3
System.out.println(decimal + " " + hex + " " + binary + " " + scientific);
}
}Output
255 255 255 1500.0