What exactly is a reference in Java? Is it a memory address? Is a Java reference the equivalent of a dereferenced C++ pointer?
In other words, given the following:
Object o1 = new Object();
Object o2 = new Object();
o1 == o2
Is the above comparison the equivalent of comparing two pointers in C++?
Reference Class is an abstract base class for reference object. This class contains methods used to get information about the reference objects. This class is not a direct subclass because the operations on the reference objects are in close co-operation with the garbage collector.
Examples of reference data types are class, Arrays, String, Interface, etc. Examples of primitive data types are int, float, double, Boolean, long, etc. JVM allocates 8 bytes for each reference variable, by default. Its size depends on the data type.
For reference types, Java passes the reference by value. That is, it creates a copy of the pointer to the object in memory.
An object reference is information on how to find a particular object. The object is a chunk of main memory; a reference to the object is a way to get to that chunk of memory. The variable str does not actually contain the object, but contains information about where the object is.
o1 == o2
is pretty much equivalent to comparing two pointers in C/C++, yes.
But there are a two main differences between references in Java and pointers in C/C++ that are quite important:
Also a short note about the word "reference": C++ has references that act quite differently from both pointers in C and references in Java (but I don't know enough about C++ to tell you the specifics).
For a thorough discussion of this, see this related question on programmers.SE.
What exactly is a reference in Java?
It is an index of an object. It can be thought of as like a pointer but it differs in the fact that it
Is the above comparison the equivalent of comparing two pointers in C++?
Yes.
On Compresses Oops which allows a 64-bit JVM to sue 32-bit references.
Java HotSpot™ Virtual Machine Performance Enhancements - Compressed Oops
Compressed oops in the Hotspot JVM
IBM V6 - More effective heap usage using compressed references
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With