References
Table of Contents
1. Memory
Computers store information in memory as a sequence of ones and zeroes. Each type in Java has a different way to store these bits, represented by eight primitive types in Java:
byteshortintlongfloatdoublebooleanchar
When you declare a variable of a certain type, Java sets aside exactly enough bits to hold a thing of that type. For example, declaring an int sets aside a "box" of 32 bits, whereas declaring a double sets aside a box of 64 bits. Java then creates an internal table that maps each variable name to a location in memory where these bits are stored.
When the variable is declared, Java does not write anything into the reserved boxes (until that variable is set to something). For safety, Java does not allow you to read anything from uninitialized variables.
1.1. Golden Rule of Equals
What the equal (=) operator does is that it copies all the bits over. For example, y = x copies all the bits from x to y.
The same thing happens when we pass parameters to a function: the bits are copied over to the new variables.
2. Reference Types
Every other type that is not a primitive type is known as a reference type. When we instantiate an Object, Java first allocates a box of bits for each instance variable of the class and fills them with a default value. Then, the constructor will fill each of these with some other, user-specified value.
The key idea is that for an Object, the new constructor (e.g. new Walrus(1000, 8.3)) returns not the actual value of the object (unlike for primitive types), it returns an address to where the value is stored in memory.
Then, when we use the equal sign, we copy the memory address — not the value itself. This is why in the following code:
// changing b affects a
Walrus a = new Walrus(1000, 8.3);
Walrus b;
b = a;
b.weight = 5;
System.out.println(a);
System.out.println(b);
// changing y does not affect x
int x = 5;
int y;
y = x;
x = 2;
System.out.println("x is: " + x);
System.out.println("y is: " + y);