58

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

7
  • There are multiple posts here that say outright "no, not really". I wonder - does Java have any mechanisms (in modules/extensions?) to write to memory directly, like old outb(0x08,0x378); or the old peek/poke on "small CPUs" like mobile.
    – SF.
    Apr 13, 2010 at 13:21
  • 1
    SF, sun.misc.Unsafe class (docjar.com/docs/api/sun/misc/Unsafe.html), you're looking for putByte method.
    – Vlad Gudim
    Apr 13, 2010 at 14:17
  • @Totophil: strictly speaking that's not "Java", because it's not standardized. It's an implementation detail of the Sun JVM (and thus the OpenJDK as well). Apr 13, 2010 at 20:13
  • @SF: Java has the ability to call into native (i.e. non-Java) code. That way you can do anything that native code can't, but there's no direct hardware-access in Java. Apr 13, 2010 at 20:14
  • 4
    java.lang.NullPointerException This alone should answer everything. I think the high number of upvotes for answers here claiming that java does not have pointers, is the best argument against stackoverflow.
    – user4590120
    Nov 2, 2015 at 23:00

12 Answers 12

48

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.

14
  • 6
    Actually, at the implementation level, references usually are pointers to the memory containing the object. HOWEVER, there is no way that a regular Java program can "look behind the curtain" and use references as C-like pointers.
    – Stephen C
    Apr 13, 2010 at 12:23
  • 7
    Can you post a reference to the above ? Given that the JVM can move objects at will, and maintain its references, I would suspect that at the least, a reference would be a pointer to a pointer. Apr 13, 2010 at 12:25
  • 14
    There actually is one famous pointer, the NullPointer, which in my applications seems to be married to Exception :)
    – extraneon
    Apr 13, 2010 at 13:25
  • 2
    @jalf This is mere handwaving. Either you actually have a reference that actually says this, in which case you should post it as requested, or you don't, which leaves room for the conclusion that you are making it up. I just looked up both my compiler implementation 101 books, one of which is Aho, Sethi, & Ullman, and neither of them says any such thing. The existence of language like 'managed pointer' and 'compressed oops' in the JVM documents clearly indicates that object references are anything but straight pointers.
    – user207421
    Aug 16, 2013 at 1:21
  • 2
    @jalf - I'm not doubting you particularly, but would just like to find some reference that actually describes what's going on Aug 16, 2013 at 9:00
46

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.

14
  • Micro-nitpick: "C++ must maintain compatibilty with C" is not exactly true, there are several (small-ish) incompatibilities. "C++ strives to maintain compatibility with C" is more correct. Apr 14, 2010 at 10:00
  • Not-so-micro nitpick: The "reference to pointer" table that you mention is one possible implementation, but in no way required by the Java specification. Apr 14, 2010 at 10:01
  • 1
    No problem with the nitpicking, yet somehow the reference will eventually have to be turned into an address. A pointer table is the most logical means of doing so, but you're right, other means could exist. The pointer table is not a requirement, but without some sort of a lookup, you're dealing with something generated algorithmically, which hardly will help out with memory compaction.
    – Edwin Buck
    Apr 14, 2010 at 19:58
  • 1
    @EdwinBuck: isn't the most logical thing to do just creating a pointer to the pointed-to data? Just update your pointers when you move a pointed-to object during a garbage collection
    – jalf
    Jan 8, 2013 at 9:45
  • 1
    @jalf It is a logical thing to do, but it is prone to issues. Basically pointer values can be copied into multiple locations, so unless you have some sort of exotic "track each time this pointer's value was copied, and keep a reference of all of those value locations, including tracking if some of those locations are destroyed over time" then you'll update only some of the pointer values (which would be very bad). Actually, you can't really even create such a system; because, some of those values might be passed between programs. With a reference to pointer table, it's in one place only.
    – Edwin Buck
    Jan 8, 2013 at 14:50
14

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.

2
  • 2
    "direct manipulation" is kind of in-precise: Assignment of another value (= another reference) is possible, but pointer arithmetics (i.e. adding 1 to the pointer) is not possible. Apr 13, 2010 at 12:29
  • Meaning that if arithmetic operations with the pointers are not allowed, does not mean there are no pointers in Java.
    – hipokito
    Nov 15, 2015 at 15:55
7

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.
1
  • Insightful fact.
    – lft93ryt
    Apr 6, 2017 at 16:15
6

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++.

3
  • 1
    I think confusion comes from the fact that "pointer" is a term almost universally associated with C/C++. As a result most people will gain better understanding from the statement that Java does not have pointers. Still: upvote.
    – B M
    Sep 6, 2017 at 18:24
  • This is the best answer here. I wish I could upvote it more.
    – klutt
    May 21, 2019 at 15:52
  • I wonder where this wrong meme (that java does not have pointers) came from. This created so much confusion. People which claimed this, should not be allowed to write software,
    – user12411795
    Nov 10, 2020 at 19:36
5

java.lang.NullPointerException

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);
    }
}
8
  • 6
    Today I had first Java lecture and I'm exactly perplexed by this example. Why everyone say that Java has references?! What seams to me is that everything is pointer but you can't do pointer arithmetic.
    – tom
    Oct 1, 2013 at 18:55
  • 1
    What's happening is you're declaring two objects on the first line. On the second line you initialize p1, then on the third line you set p2 equal to p1. Finally you make p1 reference null. p2 will(and should), still equal the new object().
    – J Code
    Oct 3, 2014 at 6:06
  • 1
    @ChrisGray: I don't quite understand this answer. The fact that p2 has a value at the end of the exercise and is not null proves that Java indeed does not have pointers otherwise p2 would point to p1 and be null as well.
    – user1191027
    Aug 17, 2015 at 10:58
  • 1
    please, everybody who is still unclear about this, google the class name mentioned at the beginning of this answer.
    – user4590120
    Sep 15, 2015 at 17:26
  • 2
    @ThreaT No, it doesn't, because when you modify p1 you make it reference null, but you don't destroy the object; the object and its reference are distinct things: p2 still points to the created object until you make p2 reference null; then, the object will be destroyed by GC because nothing references it. C pointers are similar in this: consider the code void main() { int n, *p1, *p2; n = 42; p1 = &n; p2 = p1; *p1 = 100; p1 = NULL; printf("%d\n", *p2); } it will print "100" because when you do p1 = null, you modify the pointer value, not the value of what it points to.
    – bd95
    Mar 17, 2017 at 19:58
1

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.

1
  • 3
    "Look under the hood" is not a property of pointers. It's a property of the language; in particular, in C and C++ you can "look under the hood" because (1) any pointer can be converted to a pointer to char (type conversion is not an inherent property of pointers), (2) char is guaranteed to directly map to machine bytes (that's quite obviously not a pointer property) and (3) C and C++ have pointer arithmetics (again, that's not a generic pointer trait, but a specific feature of those languages).
    – celtschk
    Aug 14, 2016 at 12:00
0

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

0

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.

-1

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

1
-1

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.)

2
  • That's not a property of pointers, that's a property of specific languages that support pointers (in particular, C and C++). Pascal supports pointers, but (except as non-standard extension by various compilers) doesn't support giving a pointer an arbitrary address. Indeed, it doesn't even support to point it at a variable; the only way to get pointers in Pascal is either through new or by assigning one pointer to the other.
    – celtschk
    Aug 14, 2016 at 11:48
  • That's not even a property of applets, which can enforce exceptions on bad memory accesses, much like segfaults. Programs in general, with pointers, can't just access any address in memory, because the OS blocks that. Oct 8, 2018 at 2:17
-2

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.

1
  • 3
    'this' is no more a pointer than any other variable. It simply allows an explicit reference to the current object. Apr 13, 2010 at 16:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.