1

I am new to java and confused.

Does Java have pointers? if yes, how to manipulate them? how to perform operations like ptr++ etc?

Chandranshu
  • 3,669
  • 3
  • 20
  • 37
  • you can't directly interact – subash Nov 17 '13 at 18:51
  • 1
    Everything but primatives (integer, float etc) are references, they behave in a similar way to C++ pointers but not identical; the most important difference being that most of the time you don't have to worry about them being references – Richard Tingle Nov 17 '13 at 18:51
  • You can do them with Unsafe but you shouldn't unless you have considered using natural Java first. Can you explain what you are trying to do as more than likely you don't need pointers. – Peter Lawrey Nov 17 '13 at 23:31

4 Answers4

3

Yes, java has pointers and they call them references. But reference manipulation is not possible in java. That is, you can not do ref++ and things like that. You can just allocate memory to an object and assign it to a reference, de-allocation too is done by garbage collector in JVM. So you are free of free.

codingenious
  • 8,385
  • 12
  • 60
  • 90
3

Java doesn't have pointers, but you can make pointer manipulations with sun.misc.Unsafe: Java Magic. Part 4: sun.misc.Unsafe:

static Object shallowCopy(Object obj) {
    long size = sizeOf(obj);
    long start = toAddress(obj);
    long address = getUnsafe().allocateMemory(size);
    getUnsafe().copyMemory(start, address, size);
    return fromAddress(address);
}

Though in my practice I have never wanted to do such things and they are considered a bad practice by community unless you're developing a super-fast library like Kryo.

Andrey Chaschev
  • 16,160
  • 5
  • 51
  • 68
1

You dont have pointers, or at least not how you are used to thed from C/C++/whatever. You have object references instead, but you cant ++ those.

kajacx
  • 12,361
  • 5
  • 43
  • 70
0

The following examples are pointers set to reserved memory:

Object o = new Object();
int[] myInts = new int[32];

You can manipulate pointers like this:

Object myObject = otherObject;

...if both types match.

You cannot do pointer manipulation as you could in C, because these are usually dangerous operations. Java in general tries to reduce coding errors by disallowing dangerous operations as much as possible. In the beginning this feels restraining, but once you get to know Java and suddenly can write a whole page of code without a single bug, you understand why this is a core design of the language.

TwoThe
  • 13,879
  • 6
  • 30
  • 54