Chapter 3. Know Your Variables: Primitives and References

image

Variables can store two types of things: primitives and references. 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 (like the difference between primited and references) 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

image

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 ...

Get Head First Java, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.