Java
Beginner
1 min read
Primitive Data Types and Literals
Example
public class PrimitiveTypes {
public static void main(String[] args) {
// Integer family
byte b = 127; // -128 to 127
short s = 32_767; // -32768 to 32767
int i = 2_147_483_647; // ~2.1 billion
long l = 9_223_372_036_854_775_807L; // ~9.2 quintillion
// Binary and hex literals (Java 7+)
int flags = 0b0000_1111; // 15 in binary
int color = 0xFF_AA_00; // orange in hex
// Floating-point family
float f = 3.14F; // ~7 significant digits
double d = 3.141592653589793; // ~15 significant digits
// Character and boolean
char c = 'A'; // UTF-16 code unit
char euro = '€'; // Euro sign
boolean flag = true;
// Widening conversion (automatic)
long fromInt = i; // int -> long, no cast needed
// Narrowing conversion (explicit cast, may lose data)
int truncated = (int) 9.99; // result: 9 (truncates, not rounds)
// Arithmetic and overflow demo
int max = Integer.MAX_VALUE;
int wrap = max + 1; // overflows silently to MIN_VALUE
System.out.printf("byte: %d, short: %d%n", b, s);
System.out.printf("int: %d, long: %d%n", i, l);
System.out.printf("float: %.2f, double: %.15f%n", f, d);
System.out.printf("char: %c (%d), euro: %c%n", c, (int) c, euro);
System.out.printf("overflow demo: %d + 1 = %d%n", max, wrap);
System.out.printf("truncated cast: (int)9.99 = %d%n", truncated);
}
}