Java - Data Types

Data Types

Primitive Types

Primitives are stored by value and have fixed sizes. They avoid allocation overhead and are not nullable.

byte, short, int, long   // integral
float, double            // floating point
char                     // UTF-16 code unit
boolean                  // true/false

Wrapper Types

Each primitive has a wrapper: Integer, Long, Boolean, etc. Wrappers are objects and can be null.

Integer xi = Integer.valueOf(10);
int x = xi; // unboxing

Autoboxing / Unboxing

Automatic conversion between primitives and wrappers. Beware of unintended allocations and NullPointerException during unboxing.

Integer n = null;
// int y = n; // NPE at runtime!

Strings

String is immutable. Use StringBuilder for repeated concatenation in loops.

String s = "Hello";
String t = s + " World";          // creates new String
StringBuilder sb = new StringBuilder().append(s).append(" World");

Arrays

Fixed-size containers of elements of a single type. Arrays are objects; length is accessed by .length (field, not method).

int[] a = new int[]{1,2,3};
int n = a.length;

Casting and Numeric Promotion

Widening conversions are safe; narrowing conversions require explicit casts and may lose information.

long L = 100;       // widening from int to long
int i = (int) 1_000_000_0000L; // narrowing; potential overflow

null and Optional

Only reference types can be null. Prefer Optional<T> for return values that may be absent, not for fields.

java.util.Optional maybe = java.util.Optional.of("value");
Architect note: avoid excessive boxing in hot code paths; prefer primitives or specialized collections (e.g., fastutil) when profiling indicates need.

Try it

  1. Create examples of each primitive and print their sizes/ranges (document in comments).
  2. Trigger a NullPointerException via unboxing, then fix it safely.
  3. Use StringBuilder to build a large string efficiently and compare with + in a loop.