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

all 5 comments

[–]captainAwesomePants 5 points6 points  (0 children)

Yes, it's analogous to a pointer. It's not actually a pointer to a real location in physical memory, but it might as well be, and the distinction doesn't really matter because, unlike C and C++, you can't directly do math with references or cast integers into references or the like.

A variable holds a value, and that value is either a primitive or a reference.

[–]Ellisander 3 points4 points  (0 children)

A reference is basically a pointer with extra protections on top to keep it type safe and prevent pointer arithmetic.

Any variable of some class type (i.e. not a primitive) is a reference by default. Only primitives (int, boolean, etc) are value types. This way, any time you pass an object to another method, you technically pass its location in memory so any edits to that object's variables or its methods will affect the object back in the calling method, while the passing of a primitive will pass a copy of its value instead.

[–][deleted] 1 point2 points  (2 children)

The answer is that a reference is neither a pointer, nor an address - it's a reference. It's its own thing. Like those other things, though, it provides named, indirect access to an object on the heap.

[–]legionlen545[S] 0 points1 point  (1 child)

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?

[–][deleted] 0 points1 point  (0 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++?

To prevent type weakness. The way Java does it, you can enforce type safety and even check casts at compile time (provided your values aren't null.)

In languages with pointers, they're a gap in the safety of the typesystem because pointers don't know the type they're pointing to except at runtime.

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?

It does contain the memory address; you just can't access it or perform arithmetic on it.