Java Primitive Types

Java provides eight primitive data types for basic values. These are the building blocks of Java programming.

The Eight Primitive Types

Integer Types

byte

  • Size: 8 bits (1 byte)
  • Range: -128 to 127
  • Default: 0
  • Use Case: Saving memory in large arrays
1byte smallNumber = 100; 2byte temperature = -20;

short

  • Size: 16 bits (2 bytes)
  • Range: -32,768 to 32,767
  • Default: 0
  • Use Case: Memory-efficient integer storage
1short year = 2023; 2short port = 8080;

int

  • Size: 32 bits (4 bytes)
  • Range: -2³¹ to 2³¹-1
  • Default: 0
  • Use Case: General-purpose integer
1int count = 42; 2int population = 1_000_000;

long

  • Size: 64 bits (8 bytes)
  • Range: -2⁶³ to 2⁶³-1
  • Default: 0L
  • Use Case: Large numbers, timestamps
1long bigNumber = 9_000_000_000L; 2long timestamp = System.currentTimeMillis();

Floating-Point Types

float

  • Size: 32 bits (4 bytes)
  • Precision: 6-7 decimal digits
  • Default: 0.0f
  • Use Case: Memory-efficient decimal numbers
1float pi = 3.14159f; 2float price = 19.99f;

double

  • Size: 64 bits (8 bytes)
  • Precision: 15-16 decimal digits
  • Default: 0.0
  • Use Case: Precise decimal calculations
1double precisePi = 3.141592653589793; 2double balance = 1234.56;

Other Types

boolean

  • Size: 1 bit (implementation dependent)
  • Values: true or false
  • Default: false
  • Use Case: Conditional logic
1isActive = true; 2hasPermission = false;

char

  • Size: 16 bits (2 bytes)
  • Range: '\u0000' to '\uffff' (Unicode)
  • Default: '\u0000'
  • Use Case: Single characters
1char grade = 'A'; 2char newline = '\n'; 3char unicode = '\u03A9'; // Greek omega

Type Conversion

Implicit Conversion (Widening)

1int intValue = 100; 2long longValue = intValue; // int to long (automatic) 3double doubleValue = intValue; // int to double (automatic)

Explicit Conversion (Narrowing)

1double doubleValue = 123.456; 2int intValue = (int) doubleValue; // 123 (truncates decimal) 3long longValue = (long) doubleValue; // 123L

Default Values

When primitive variables are declared as class members without initialization:

1public class Defaults { 2 byte b; // 0 3 short s; // 0 4 int i; // 0 5 long l; // 0L 6 float f; // 0.0f 7 double d; // 0.0 8 boolean bool; // false 9 char c; // '\u0000' 10}

Best Practices

  1. Choose the smallest type that fits your needs to save memory
  2. Use long for timestamps and large numbers
  3. Prefer double over float for precision
  4. Use underscores for readability in large numbers
  5. Be explicit with literals (f for float, L for long)

Common Pitfalls

  • Integer overflow: int max = Integer.MAX_VALUE + 1; // becomes negative
  • Floating-point precision: 0.1 + 0.2 != 0.3 due to binary representation
  • Division by zero: Throws ArithmeticException for integers
  • Type casting loss: (int) 3.99 results in 3, not 4

Understanding primitive types is fundamental to writing efficient and correct Java code.