I read quite a few resources on the internet and now I am quite confused about the existence of pointers in Java.
Some claim that there are pointers and some claim that there is no such concept. So what is the truth?
Software Engineering Stack Exchange is a question and answer site for professionals, academics, and students working within the systems development life cycle. It only takes a minute to sign up.Sign up to join this community
At face value, since the official Java language specification specifically mentions pointers, then the answer is YES, pointers exist in Java.
So how do we explain the apparent contradictory opinions here? Well, like many issues, the disagreement comes down to semantics.
The term "pointer" is strongly associated with the C/C++ concept of pointers, which are variables which explicitly store memory addresses, and which can be modified arithmetically to point to any arbitrary address. In Java, pointers exist, but not as a first-class language concept. Rather, pointers only exist as an implementation detail for References. The spec says:
An object is a class instance or an array.
The reference values (often just references) are pointers to these objects, and a special null reference, which refers to no object.
It's also telling that accessing a null reference throws a
NullPointerException, not a
NullReferenceException. So, clearly the Java designers were at least thinking in terms of pointers when they wrote the Java language spec. (Although really it should be called a
NullReferenceException; in my opinion the name of that exception leaks through the abstraction)
So, the answer is that Java References are "pointer-ish", in the sense that they are implemented in terms of pointers (just like most implementations of C++ references), but Java References provide a higher-level abstraction which restricts the programmer from manipulating the actual memory address. Syntactically, a Java reference only gives you access to the members or methods of the pointed-to Object - not the memory location of the Object.
So yes, pointers exist in Java, for a certain value of "exist". But it's probably not helpful to speak in terms of "pointers" when discussing Java language concepts.
Java does have pointers. Any time you create an object in Java, you're actually creating a pointer to the object; this pointer could then be set to a different object or to null, and the original object will still exist (pending garbage collection).
What you can't do in Java is pointer arithmetic. You can't dereference a specific memory address or increment a pointer.
If you really want to get low-level, the only way to do it is with the Java Native Interface; and even then, the low-level part has to be done in C or C++.