Chapter 3. Know Your Variables: Primitives and References
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
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.