What are the differences between references and pointers in C++ and in Java?

Question:

Both Java and C++ have references.

Are they practically the same or are they significantly different?
Java has no pointers. So are references in Java like pointers in C++?
Are there code structures around references and pointers that are the same in the two languages ​​but do different things?

Answer:

For a senior C++ programmer, the best way to explain java, or part of java, is to say:

  • All declarations of variables, parameters, attributes, etc. that are of type Object or that inherit from Object are always "pointers".
  • Objects never reside in the "stack" or in "global memory" they always reside in the java object heap.
  • The reason that the C++ pointer (the "*") in such declarations does not exist in java is that it is always 100% implicit and it is impossible to declare object variables that are not pointers (C++ style without "*") . I mean objects that do not reside in the "heap".
  • As all the declarations (variables etc) that inherit from Object are always pointers, and there is no possibility of anything else, they eliminated the "*", it is always implicit.
  • "new" is always used to create new instances. New object instances cannot be created without "new". (or use of JNI).
  • Objects cannot be "delete", it is the JVM that knows which objects are "alive" and which are not. The garbage collector looks at the "soup" of existing objects and from some "roots" it knows how to decide which one is alive (is accessible) and which one is no longer accessible from the "roots".
  • Java objects can change their memory address over time. But the programmer never sees what those addresses are (unlike C++), and the JVM always maintains the integrity of the "soup" of java objects on the heap. When you move an address object, all references from clients change properly. This is 100% transparent to the programmer/user.
  • Any variable, of type Object or inheriting from Object, can always be assigned null (ALL such declarations are pointers).
Scroll to Top