Java SE 8 Programmer I (OCAJP 8) study materials
Java SE 8 Programmer I (OCAJP 8) study resources

Java SE 8 Programmer I (OCAJP 8): Working With Java Data Types

Java SE 8 Programmer I (OCAJP 8) · Work through your exam, one topic at a time.

All guide sections

Working With Java Data Types

Working With Java Data Types

This domain tests the eight primitives, literal syntax, casting, wrappers, and the difference between primitive values and object references. Questions often turn on compile-time type checking rather than runtime behavior.

Primitives and literals

  • byte 8 bits, short 16, int 32, long 64, float 32, double 64, char 16-bit unsigned Unicode, boolean true/false.
  • Integer literals are int unless suffixed L; floating-point literals are double unless suffixed F.
  • Underscores may separate digits but cannot sit at the start/end or next to a decimal point. Prefixes: 0b binary, 0 octal, 0x hex.
  • Widening conversion is automatic; narrowing needs a cast. A constant expression that fits a narrower type may be assigned without a cast.

Wrappers and references

Each primitive has a wrapper (Integer, Double, etc.). Autoboxing converts automatically, but == compares references for wrappers, while equals compares values. The wrapper cache (typically -128 to 127 for Integer) can make == true for small values and false for larger ones. null can be assigned to a reference but unboxing it throws NullPointerException. String is immutable and string literals are pooled.

Worked example

byte b = 10;
b = b + 1;       // compile error: int result
b += 1;          // legal: implicit cast
Integer i1 = 1000, i2 = 1000;
System.out.println(i1 == i2);      // false
System.out.println(i1.equals(i2)); // true

b + 1 promotes b to int; assigning back needs a cast. Compound assignment performs the cast implicitly. The two Integer objects are outside the usual cache.

Traps

  • float f = 1.0; fails; use 1.0F.
  • char c = 65; is legal, but char c = -1; is not.
  • boolean does not convert to or from numeric types.
  • Comparing a wrapper with == to a primitive can unbox; comparing two wrappers compares references.