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
byte8 bits,short16,int32,long64,float32,double64,char16-bit unsigned Unicode,booleantrue/false.- Integer literals are
intunless suffixedL; floating-point literals aredoubleunless suffixedF. - Underscores may separate digits but cannot sit at the start/end or next to a decimal point. Prefixes:
0bbinary,0octal,0xhex. - 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; use1.0F.char c = 65;is legal, butchar c = -1;is not.booleandoes not convert to or from numeric types.- Comparing a wrapper with
==to a primitive can unbox; comparing two wrappers compares references.