Does Java have pointers?

JavaPointers

Java Problem Overview


If Java does not have pointers, then what does the the new keyword do in Java?

Java Solutions


Solution 1 - Java

As pointed out, Java has references. How are these different ?

  1. you can't perform arithmetic or other such operations on these
  2. they do not point to the memory containing the object (i.e. they are not pointers by another name). The JVM is at liberty to move objects around within the VM memory, and most likely will do during garbage collection. The references however still point to that object, despite its movement within memory.

So they're not like C++ references (pointing directly to an object). Perhaps a better name would be handle.

Solution 2 - Java

Java doesn't have pointers; Java has references.

It's a fine point, but a pointer has extra operations that you may (or may not) typically use; a reference lacks these operations because the operations may be unsafe.

For example, if you use a pointer to index the first element of an array like so:

int squares[] = {1, 4, 9, 16, 25, 36, 49};
int* intPointer = squares;

you may want to dereference the pointer and get the value "1", but you may also:

intPointer++

and after you do that, when you dereference the pointer you will get the value "4". A second

intPointer++;

will, when dereferenced, give you the value "9". This is because the ++ operation moves the pointer one "unit" ahead in memory.

The issue comes from the weaknesses in the C / C++ typechecking system (C++ must maintain compatibilty with C, so it allows the same issues). The pointer stores an address in memory and the ++ operation adds the appropriate number of bytes to the address. On many systems ++ing an int adds four bytes, but if the pointer was a char pointer ++ing it should only add one byte. Note that since the underlying data type of a pointer is an address in memory, the following is legal (but not recommended):

char* charPointer = squares;
charPointer++;

void* voidPointer = squares;
voidPointer++;

Since pointers are addresses in memory, they might represent (correctly) any bit of memory in the computer, but they are only properly dereferenced when the underlying data maches the type and alignment of the pointer. For pointers that aren't managed by lots of code to make them safe, this means you might stray off the data type (or alignment) of the desired information and a dereference might end in disaster. Attempting to fix this issue with custom code tends to slow down one pointers badly enough that you notice performance issues, and it opens the doors for adding errors in the custom "pointer management" code.

Java side steps all of these issues by returning a reference. A reference does not refer to any location in memory; Java maintains an internal "reference to pointer" table. This table takes the reference and returns the data associated with it, wherever that data may reside in memory. This slows down code execution, because two lookups are done for each "dereferencing", one lookup in the reference table, one in the machine's memory.

A big advantage of Java using references is that the memory can be moved around without breaking the would-be pointer addresses. In a C program, if you move data into a new memory location, it is very difficult to know whether some other part of the program has a pointer to the data. Should a stale pointer be dereferenced after the memory is moved, the program will be accessing corrupt data, and typically a crash will be shortcoming.

Ability to move the memory around in a running program allows programs to easily recycle memory. Any program which doesn't need chunks of memory can release the unused memory, but this creates memory holes of unused memory in between chunks of used memory. Internally computers use pages of memory, which are quite large. If a sparsely used page of memory could have the few used bits moved into another page, then a page of memory can be freed. This increases the density of data to memory, improving cache performance. Sometimes this translates into performance improvements that can be quite dramatic.

Java's Garbage Collector takes advantage of the use of references by temporarily blocking access to the data for a set of references. During that blockage of access, it moves the data around (to compact it). After the blockage, the reference to address table has the new memory addresses. Since the "functional" layer of the code never knew the addresses in the first place, this operation will not break a running Java program.

Solution 3 - Java

Java has pointers in the sense of variables that store references to data in memory. All variables of Object types in Java are pointers in this sense.

However, the Java language does not allow arithmetic operations on the values of pointers, like you'd be able to do in a language like C.

Solution 4 - Java

new does (roughly) the following:

  1. Find a contiguous free block of heap memory equal to the instance size of the class you're creating, plus some space for bookkeeping
  2. Zero said space & remove it from the free list
  3. Run the constructor
  4. Return a reference (NOT a pointer, as other posts have explained) to the created instance.

Solution 5 - Java

Java does have pointers, which are known under the name "reference".

When people say "Java does not have pointers", they typically confuse the concept of a pointer with the specific implementation and abilities of pointers found in C and C-derived languages.

In particular:

  • Java references can't be set to an arbitrary address. Nor can (standard) Pascal nor Fortran pointers.
  • Java references can't be set to point to a variable. Nor can (standard) Pascal pointers.
  • Java references don't support pointer arithmetic. Nor do Pascal nor Fortran pointers
  • Java references can't point to parts of an object (like the third element of an array). Nor can Pascal pointers.

Also, contrary to widespread belief, a pointer is not necessarily an address. A pointer is typically implemented as an address, but there's no requirement to do so, not even in C or C++.

Solution 6 - Java

[java.lang.NullPointerException][1]

People told me "that java does not have pointers" in interviews. I usually gave them some java code and let them explain, what is happening in this code:

public class TestPointers {

    public static void main(String args[]) {
        Object p1, p2;
        p1 = new Object();
        p2 = p1;
        p1 = null;
        System.out.println(p2);
    }
}

[1]: https://docs.oracle.com/javase/7/docs/api/java/lang/NullPointerException.html "java.lang.NullPointerException"

Solution 7 - Java

Java has references. All objects are accessed through having references to their instances. You create a new instance using new, which returns a reference to the object.

Java references are not like pointers in C, you cannot "look under the hood" at the raw memory that makes up the object.

Solution 8 - Java

new in Java returns a reference to the newly created object.

Solution 9 - Java

new returns reference. it has some similarities with pointers (if you pass to function, reference is passed, same as with pointer), but there is no pointer arithmetics.

Solution 10 - Java

Java Does not have Pointers. The operator "new" is used to the reference variable in java.

Solution 11 - Java

Java does not support or allow pointers. (Or more properly , Java does not support pointers that can be accessed and/or modified by the programmer.) Java cannot allow pointers, because doing so would allow Java applets to breach the firewall between the Java execution environment and the host computer. (Remember , a pointer can be given any address in memory - even addresses that might be outside the Java run-time system.)

Solution 12 - Java

In java we come across certain keywords used as reference for example this keyword is used to refer the variables of same class. The operator new is used as reference to an object.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionarunaView Question on Stackoverflow
Solution 1 - JavaBrian AgnewView Answer on Stackoverflow
Solution 2 - JavaEdwin BuckView Answer on Stackoverflow
Solution 3 - JavaSyntacticView Answer on Stackoverflow
Solution 4 - JavathecoopView Answer on Stackoverflow
Solution 5 - JavaceltschkView Answer on Stackoverflow
Solution 6 - Javauser678269View Answer on Stackoverflow
Solution 7 - JavaunwindView Answer on Stackoverflow
Solution 8 - JavacodaddictView Answer on Stackoverflow
Solution 9 - JavaAndreyView Answer on Stackoverflow
Solution 10 - JavaVenkatView Answer on Stackoverflow
Solution 11 - JavaShubham SharmaView Answer on Stackoverflow
Solution 12 - Javauser315459View Answer on Stackoverflow