Is there anything similar to C++ pointers in Java? If there is, I would like to know what it is. Could you give me some examples?
-
5http://stackoverflow.com/questions/2629357/does-java-have-pointers – Bart Aug 17 '12 at 11:39
-
No, what exactly do you want to achieve! – Ozair Kafray Aug 17 '12 at 11:39
-
Java does not have pointers. Use polymorphism – ddoor Aug 17 '12 at 11:40
-
5@close-voters: you're wrong. asking whether Java has "pointers" (*yes*, the Java language specification says so) is very different from asking whether has "same thing like C++ pointer (*no*, it doesn't). Get a grip. The answers are directly **opposite**, it's no duplicate. – Cheers and hth. - Alf Aug 17 '12 at 11:46
2 Answers
Java's pointers (so called by the language specification, while I believe Java programmers mostly know them as "references") do not support pointer arithmetic.
And Java has no way to do pointer arithmetic.
If you want to do such low-level stuff in Java, one way is to use JNI (the Java Native Interface) to access code written in C or C++.

- 142,714
- 15
- 209
- 331
The Java object model is different from that of C++:
In C++, for every type you can have a variable of that type. Additionally, for every non-reference type
T
there is a typeT&
and you can have variables of that type (but references are never objects).In Java, types which are class types can never be the type of a variable. Objects of class type can only exist dynamically, and a variable that is declared as being of type
T
(whereT
is of class type) is always implicitly a tracked reference to an object. (Let us ignore primitive types for this discussion.)
In both languages, variables are scoped. However, in C++ you can take advantage of scoped lifetime because objects whose lifetime ends automatically call a destructor. In Java, the only variables are references, and their going out of scope does something very different: It informs the memory manager that the object which they were tracking now has one fewer reference; and if there are no based references left, the object becomes eligible for (non-deterministic) collection.
If you will, you can equate class-type variables in Java to pointers in C++:
// Java:
{
Foo x = new Foo();
x = new Foo(); // no assignment in Java!
}
// C++:
{
Foo * px = new Foo;
px = new Foo; // ... leaks the previous object
}

- 464,522
- 92
- 875
- 1,084