aspose file tools
The moose likes Beginning Java and the fly likes variable or reference? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Head First Android this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "variable or reference?" Watch "variable or reference?" New topic

variable or reference?

Wesley Tai

Joined: Sep 30, 2003
Posts: 6
Do "x" is a variable?
Can we say "x" is a reference and it refer to "3" ?
Kathy Sierra
Cowgirl and Author

Joined: Oct 10, 2002
Posts: 1589
Howdy -- x is a *variable*, with a *value* of 3.
It's not a reference, because in the Java world, a reference is a variable that gets you to an object on the heap.
Variables can be primitives... where the bits in the variable ARE the value. So the bits representing the integer 3 are the value of the variable x.
Variables can be references... where the bits in the variable are a WAY TO ACCESS AN OBJECT. The object is somewhere on the heap, and the *reference* variable holds bits that the JVM uses to access that object (like a pointer to a pointer to... we don't know and we don't care, unless we are a developer writing a Java virtual machine).
So we could say:
Dog d = new Dog();
"The variable "d" is a reference to a Dog object"
or just, "d is a reference to a Dog."
or, "d refers to a Dog"
and if you're being sloppy or taking shortcuts and everyone knows what you're talking about, you can say, "d is a Dog". But we don't like to say it that way, because it implies that the whole Dog is somehow stuffed into what is perhaps a 64 bit-sized container. Ouch. Have to be a small dog...
But there are other issues surrounding reference variables, and the MAIN one is that reference variables have a TYPE, and that type does not necessarily exactly match the type of the object to which the variable refers.
If we have:
Dog d;
We can say, "d is a Dog reference variable with a value of null"
The important part is that "d" is declared as type "Dog".
But because of polymorphism, we COULD say:
Dog d = new Beagle();
And now we have TWO types that matter. So now we can say:
"d is a Dog reference variable referring to a Beagle object." Although it is also acceptable to say: "d is a reference to a Dog." Even though we NOW know that the object is *actually* a Beagle. But because Beagle IS-A Dog, it's OK to refer to a Beagle as a Dog. Unless you want it to Beagle-specific stuff that exists as methods only in class Beagle and NOT in class Dog. But I'm probably going way off the track here.
There's a lot more info on this in the Campfire stories!!
Wesley Tai

Joined: Sep 30, 2003
Posts: 6
Thanks for your help.
jQuery in Action, 3rd edition
subject: variable or reference?
It's not a secret anymore!