My Java book explains that to use objects, we can assign them to reference variables. How is that different from a pointer to an object? Does Java have pointers?
Thanks :)
References are used to refer an existing variable in another name whereas pointers are used to store address of variable. References cannot have a null value assigned but pointer can. A reference variable can be referenced by pass by value whereas a pointer can be referenced by pass by reference.
Variables is kinda label for the memory that stores the actual data. Pointers stored the address of the variables. References are alias for the variables.
Reference variable is used to point object/values. 2. Classes, interfaces, arrays, enumerations, and, annotations are reference types in Java. Reference variables hold the objects/values of reference types in Java.
Pointers are memory addresses and a pointer points to a memory address of a variable. In C/C++, a pointer can be incremented/decremented to point to a new address but in Java, arithmetic operations on references are not allowed.
A reference is sort of like a pointer that you can't do arithmetic on... although it's more opaque. While the underlying bits may be an address in virtual memory, they don't have to be. They're just a way of getting to an object (or representing the null value). So while they're not exactly the same, if you're used to thinking of a pointer as "a way of identifying an object or navigating to it" (in some sense) then yes, those thoughts apply to references too.
Java doesn't have pointers as such (unlike, say, C# which has references and pointers - the latter being used in "unsafe" code).
The terms "reference" and "pointer" are basically equivalent. Much of the literature I've seen about the basics of Java claims that Java has no pointers. But if you try to use a null
reference you get a NullPointerException
. So it's all semantics.
(The real difference is, in C or C++ the term "pointer" strictly means an integer that happens to be the memory address of some data. Whereas in Java the term "reference" more closely matches the C++ "reference" concept. You can't work with the memory address directly even if you want to, but you use it the same way.)
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