I am new to java and confused.
Does Java have pointers? if yes, how to manipulate them? how to perform operations like ptr++ etc?
I am new to java and confused.
Does Java have pointers? if yes, how to manipulate them? how to perform operations like ptr++ etc?
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.
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.
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.
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.