Pointers in java



Is pointers are there in java implicitly?


java has references to object. it is not same as pointer. they don’t point to memory location of object. but you can use reference to modify the object, pass the object around methods etc.


It would be great if you explain me briefly, I heard somewhere we have pointers explicitly in java.


Let’s start with few tests to find out differences…

See this easy example - http://ideone.com/K7rM60

Without trying try to find out what is printed when s[1] “is modified”…

S ns = s[1];
ns.val = 100;

nothing, because it is not modified!

Let’s check what happens in Java - http://ideone.com/oBaBYq

In Java s[1] was modified. Why? Because there are pointers used in Java. In C++ S ns = s[1] copies s[1] to ns, that’s why it is not modified. If we want to achieve the same behavior as in Java, we have to use pointers - http://ideone.com/OIfhKr


Java doesn’t have pointers. All it has are references. They do a lot of work similar to pointers. But no reference arithmetic like pointer arithmetic. Java doesn’t allow pointers to stop illegal access of memory and to have efficient garbage collection.


Can you describe more, how are are those two different? Ok, there is no pointer arithmetic in Java, something else?