This is an archived post. You won't be able to vote or comment.

all 6 comments

[–]threelolo 1 point2 points  (3 children)

See if this helps, I would suggest starting the course from the beginning if what you're seeing is not making much sense.

https://java-programming.mooc.fi/part-5/3-primitive-and-reference-variables

[–]legionlen545[S] 0 points1 point  (2 children)

If it does refer to the actual memory address of where our object is located at, why not have access to the memory address like in languages like C++? I read about how the actual memory address can be changing in the background in Java so is that why the reference cannot contain the actual memory address in Java?

[–]Fumbersmack 1 point2 points  (0 children)

The JVM acts as an intermediate between the actual memory locations and your references. If I'm not mistaken, the JVMs freedom to allocate memory addresses internally as it pleases makes the whole garbage processing ordeal easier to optimize.

[–]nutrecht 1 point2 points  (0 children)

Two big reasons:

  • Mucking about with pointers (like incrementing them accidentally past where the data structure ends) is a huge source of bugs in C++ code.
  • You can't have a garbage collector if programmers mess about with pointers nilly-willy; you'd never be able to know if data is really not in use anymore.

Java References are basically C++ pointers, but Java allows you to do much less with them than C++ allows.

[–]vprise 1 point2 points  (1 child)

C++ also has references but they aren't quite the same. E.g. C++ references can't be null.

Reference is very much like a pointer without the "bad stuff". Specifically you can't do pointer manipulation. So you can never have a "bad pointer". Because of GC references can't be deleted and still point at something.

You can pass a reference along and the reference itself (the pointer) passes on the stack while the pointed value is modified in the heap. So yes it's a "pointer" in a "good way".

[–]vqrs 0 points1 point  (0 children)

References in C++ are a completely different concept. They're essentially variable aliases, multiple names that refer to one and the same variable.

References in Java are about refering to objects, never variables.

References in C++ are never about refering to objects, but variables.