Variables are a way to store information in our computer. Variables that we define in a program can be accessed by a name we give them, and the computer does the hard work of figuring out where they get stored in the computer’s random access memory(RAM).
Variables can store two types of things: primitives and references.
The most significant difference between primitive and reference variables is that primitives (usually numbers) are immutable.
Types in Java are divided into two categories—primitive types and reference types. The primitive types are
double. All other types are reference types, so classes, which specify the types of objects, are reference types.
- There is actually no such thing as an object variable.
- There’s only an object reference variable.
- An object reference variable holds bits that represent a way to access an object.
- It doesn’t hold the object itself, but it holds something like a pointer. Or an address.
Although a primitive variable is full of bits representing the actual value of the variable, an object reference variable is full of bits representing a way to get to the object. You use the dot operator (.) on a reference variable to say, “use the thing before the dot to get me the thing after the dot.
Dog myDog = new Dog();
The bits representing a way to get to the Dog object go into the variable.
Tells the JVM to allocate space for a new Dog object on the heap.
The Dog object itself does not go into the variable!
- Instance variables are declared inside a class but not within a method.
- Local variables are declared within a method.
- Local variables Must be initialized before use!