DEV Community

Adetayo Akinsanya
Adetayo Akinsanya

Posted on Originally published at unkletayo.dev on

How Java stores values

How Java stores values

When you write int x = 42, your computer stores something in memory. Not the character 4 followed by 2. Not some abstract notion of "forty-two". A specific pattern of bits that the CPU knows how to add, compare, and shift. When you write String name = "Adetayo", something different happens. Understanding that difference is the foundation for reasoning about Java programs.

Bits, bytes, and two's complement

A bit is a single binary digit: 0 or 1. A byte is 8 bits. With 8 bits you can represent 2^8 = 256 distinct values. The question is which 256.

Java uses two's complement for all integer types. In two's complement, the most significant bit (the leftmost one) is the sign bit. When it's 0, the remaining 7 bits give values from 0 to 127. When it's 1, you're in negative territory. The range for byte is -128 to 127, not -127 to 127. Here's why: 256 combinations split as 128 non-negative (0 through 127) and 128 negative (-128 through -1). Zero takes one combination from the non-negative side.

Bits Decimal
01111111 127
00000001 1
00000000 0
11111111 -1
10000000 -128

The useful property of two's complement is that addition works identically regardless of sign. The CPU uses the same adder circuit for 3 + 4 and 3 + (-4). That's the practical reason it was chosen.

Integer arithmetic in Java wraps around at the boundary. Integer.MAX_VALUE + 1 does not throw an exception. It produces Integer.MIN_VALUE. The 32-bit pattern for Integer.MAX_VALUE is 01111111 11111111 11111111 11111111. Adding 1 flips it to 10000000 00000000 00000000 00000000, which in two's complement is -2147483648. The JLS specifies this in section 15.18.2: integer addition is performed modulo 2^32 for int. Silently, defined, and your responsibility to guard against when it matters.

int max = Integer.MAX_VALUE;
System.out.println(max); // 2147483647
System.out.println(max + 1); // -2147483648

Enter fullscreen mode Exit fullscreen mode

The eight primitive types

Java has exactly eight primitive types. Their sizes and ranges are fixed by the JLS. They don't vary between platforms, which was a deliberate design choice for portability.

Type Size Range / notes
boolean 1 bit (conceptually; JVM may use 1 byte in arrays) true or false
byte 8 bits -128 to 127
short 16 bits -32,768 to 32,767
char 16 bits 0 to 65,535; unsigned UTF-16 code unit
int 32 bits -2,147,483,648 to 2,147,483,647
long 64 bits -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
float 32 bits IEEE 754 single precision
double 64 bits IEEE 754 double precision

char deserves a note. It's a 16-bit unsigned integer representing a single UTF-16 code unit. This covers code points U+0000 through U+FFFF, which includes most characters in common use. Code points beyond U+FFFF, including many emoji and rare scripts, require two char values, called a surrogate pair. So char is not a "character" in the Unicode sense; it's a 16-bit storage unit that sometimes needs a partner.

float and double follow IEEE 754. A 64-bit double splits its bits as 1 sign, 11 exponent, 52 significand. Most decimal fractions cannot be represented exactly in binary. 0.1 in binary is a repeating fraction. When you write double x = 0.1, x holds the nearest representable value, which differs from 0.1 by about 5.5 × 10^-18. That's why:

System.out.println(0.1 + 0.2); // 0.30000000000000004
System.out.println(0.1 + 0.2 == 0.3); // false

Enter fullscreen mode Exit fullscreen mode

This is not a Java bug. It's IEEE 754 arithmetic, used by every major language and processor. When exact decimal arithmetic matters, as in financial calculations, use BigDecimal.

What a primitive variable is

A primitive variable is a named storage location that holds the bits directly. When you write int x = 42, the variable x is a 32-bit slot containing the two's complement pattern for 42. When you write int y = x, the slot for y gets its own copy of those same 32 bits. x and y are independent. Changing one has no effect on the other.

This directness is why primitives exist as a category. No allocation, no indirection, no garbage collection. The bits are right there in the variable slot, whatever storage that variable is using.

What a reference variable is

A reference variable is different. It doesn't hold the data itself. It holds an address, a way to find an object elsewhere in memory.

String name = "Adetayo";

Enter fullscreen mode Exit fullscreen mode

The variable name holds an address. At that address in memory, there's a String object containing the characters, the hash code, and the other fields that String maintains internally. If you assign name to another variable, that second variable gets a copy of the address, not a copy of the string.

String a = "Adetayo";
String b = a;

Enter fullscreen mode Exit fullscreen mode

Both a and b now hold the same address. They point to the same String object. Setting b = "Tayo" doesn't modify the string that a points to. It replaces the address stored in b with the address of a different string object. a still points to "Adetayo".

You can't inspect a reference's numeric value from Java code in any stable or useful way. System.out.println(a) calls toString() on the object, not on the reference. The address is internal to the JVM.

A reference variable can also hold a special value: null. null means the variable holds no address, so it doesn't point to any object. Calling a method on a null reference throws a NullPointerException, because there's no object at the end of a null to call the method on.

The stack and the heap

This is where the two categories connect to memory layout.

Each thread in a JVM process has its own call stack. The stack is divided into frames, one per active method call. A frame holds the method's local variables and its operand stack. When a method returns, its frame is gone.

Local variables, both primitives and references, live in the stack frame. int x = 42 inside a method: the slot for x is part of the current frame. String name = "Adetayo" inside a method: the slot for name (which holds an address) is part of the current frame.

Objects live in the heap. The heap is shared across all threads. When you write new String("Adetayo"), the JVM allocates space on the heap for the new object and returns its address. That address is what goes into name.

void greet() {
    int count = 1; // 'count' slot in this frame, holds 1
    String msg = "Hello"; // 'msg' slot in this frame, holds an address
    // The String object is on the heap, at the address stored in 'msg'
}

Enter fullscreen mode Exit fullscreen mode

When greet returns, its frame disappears. count and msg vanish with it, since they were part of the frame. The String object on the heap is still there, but nothing references it anymore. Eventually the garbage collector will reclaim it.

Why two categories instead of one?

This design is a deliberate tradeoff. Primitives avoid the overhead of heap allocation and pointer indirection. If int were an object, every arithmetic expression would allocate a new object on the heap, increment the GC counter, and require an extra pointer dereference to get the actual value. For a loop running a million iterations, that matters.

The cost of this tradeoff appears in Java's generic type system: you can't use primitives as type parameters. List<int> is not valid; you have to use List<Integer>. Autoboxing , the automatic conversion between int and Integer, papers over this at the syntax level, but the heap allocation still happens. Integer.valueOf(42) allocates an object (or returns a cached one for small values). Wrapping a tight numeric loop in a List<Integer> incurs allocation costs that a primitive array avoids.

Project Valhalla, a long-running OpenJDK effort, is working toward value types that behave like objects in generics but are stored like primitives. That work is ongoing; it doesn't change how Java behaves today.

Prediction exercise

Given this code:

void example() {
    int a = 5;
    String b = "hello";
    int[] c = {1, 2, 3};
}

Enter fullscreen mode Exit fullscreen mode

Draw what's in the stack frame when example is running, and what's in the heap. Which variables hold values directly, and which hold addresses? What happens to each when example returns?

Work through it before moving on. The answer to the last question, what survives the return, is the foundation for understanding how Java programs manage memory, and it comes up constantly when reasoning about object lifetimes, method parameters, and garbage collection.

Top comments (0)