Chapter 3. Primitives and References: Know Your Variables
Variables come in two flavors: primitive and reference. So far you’ve used variables in two places—as object state (instance variables), and as local variables (variables declared within a method). Later, we’ll use variables as arguments (values sent to a method by the calling code), and as return types (values sent back to the caller of the method). You’ve seen variables declared as simple primitive integer values (type
int). You’ve seen variables declared as something more complex like a String or an array. But there’s gotta be more to life than integers, Strings, and arrays. What if you have a PetOwner object with a Dog instance variable? Or a Car with an Engine? In this chapter we’ll unwrap the mysteries of Java types and look at what you can declare as a variable, what you can put in a variable, and what you can do with a variable. And we’ll finally see what life is truly like on the garbage-collectible heap.
Declaring a variable
Java cares about type. It won’t let you do something bizarre and dangerous like stuff a Giraffe reference into a Rabbit variable—what happens when someone tries to ask the so-called Rabbit to
hop()? And it won’t let you put a floating point number into an integer variable, unless you acknowledge to the compiler that you know you might lose precision (like, everything after the decimal point).