Assigning a value to a variable seems straightforward enough; you simply assign
The stuff on the right side of the = to the variable on the left. Well, sure, but don’t
Expect to be tested on something like this:
X = 6;
No, you won’t be tested on the no-brainer (technical term) assignments.
You will, however, be tested on the trickier assignments involving complex expressions and casting. We’ll look at both primitive and reference variable
Assignments. But before we begin, let’s back up and peek inside a variable. What is a
Variable? How are the variable and its value related?
Variables are just bit holders, with a designated type. You can have an int holder,
A double holder, a Button holder, and even a String holder. Within that holder is
A bunch of bits representing the value. For primitives, the bits represent a numeric
Value (although we don’t know what that bit pattern looks like for boolean, luckily,
We don’t care). A byte with a value of 6, for example, means that the bit pattern in
The variable (the byte holder) is 00000110, representing the 8 bits.
So the value of a primitive variable is clear, but what’s inside an object holder?
If you say,
Button b = new Button();
What’s inside the Button holder b? Is it the Button object? No! A variable referring
To an object is just that – a reference variable. A reference variable bit holder
Contains bits representing a way to get to the object. We don’t know what the format
Is. The way in which object references are stored is virtual-machine specific (it’s
A pointer to something, we just don’t know what that something really is). All
We can say for sure is that the variable’s value is not the object, but rather a value
Representing a specific object on the heap. Or null. If the reference variable has not
Been assigned a value, or has been explicitly assigned a value of null, the variable
Holds bits representing – you guessed it – null. You can read
Button b = null;
As “The Button variable b is not referring to any object.”
So now that we know a variable is just a little box o’ bits, we can get on with the
Work of changing those bits. We’ll look first at assigning values to primitives, and
Finish with assignments to reference variables.