Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between a pointer and a reference variable in Java?

Tags:

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 :)

like image 397
i love stackoverflow Avatar asked Sep 15 '11 19:09

i love stackoverflow


People also ask

What is the difference between pointer and reference variable?

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.

What is the difference between reference and variable?

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.

What is reference variable in Java?

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.

What is the difference between pointers in C C++ and reference variable 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.


2 Answers

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

like image 118
Jon Skeet Avatar answered Sep 27 '22 18:09

Jon Skeet


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

like image 31
wberry Avatar answered Sep 27 '22 17:09

wberry