What's inside a reference variable in Java? - java

We know that the object reference variable holds bits that represent a way to access an object.
It doesn't hold the object itself, but it holds something like a pointer or an address.
I was going through the Head-First Java (2nd edition) book and in the book it is written (in Chapter 3, page 54) that
In Java we don't really know what is
inside a reference variable. We do
know that whatever it is, it
represents one and only one object.
And the JVM knows how to use the
reference to get to the object. -
I want to ask:
Do an object reference variable holds pointer, address or what?
How does JVM interpret that?

It's entirely up to the JVM to determine what goes inside a reference.
In the simplest case it would just be a pointer (i.e. an address). In more sophisticated cases, the VM may use different representations depending on the situation - for example, you may want to read the paper on "Compressed oops in HotSpot" to see how the HotSpot VM can avoid doubling the size of references in some (but not all) places when running as a 64-bit VM.
The important thing is that you should neither know nor care. As far as you're concerned as a programmer, it's just an opaque set of bits - its only purpose is to let you get to the object in question (or identify a null reference).

That's up to the JVM. A Java reference isn't guaranteed to have any semantics besides that you can access an object through it. Sunacle might do that differently to IBM as well.
In practice it may often be a pointer of some sort, though maybe not directly to the object since that can be moved by the GC.

It's entirely JVM specific. It may be an address, a pointer, or something more complicated. You don't have, or need, any harder guarantees than the fact that you can get an Object using the reference.

It's up to the JVM to decide exactly how the reference is implemented.
Having said that, any "sane" implementation would probably use either a direct pointer or some form of compressed pointer for performance reasons. I believe this applies to all current production JVMs.

Related

Doesn't java have pointer? [duplicate]

My Java book explains that to use objects, we can assign them to reference variables. How is that different from a pointer to an object? Does Java have pointers?
Thanks :)
A reference is sort of like a pointer that you can't do arithmetic on... although it's more opaque. While the underlying bits may be an address in virtual memory, they don't have to be. They're just a way of getting to an object (or representing the null value). So while they're not exactly the same, if you're used to thinking of a pointer as "a way of identifying an object or navigating to it" (in some sense) then yes, those thoughts apply to references too.
Java doesn't have pointers as such (unlike, say, C# which has references and pointers - the latter being used in "unsafe" code).
The terms "reference" and "pointer" are basically equivalent. Much of the literature I've seen about the basics of Java claims that Java has no pointers. But if you try to use a null reference you get a NullPointerException. So it's all semantics.
(The real difference is, in C or C++ the term "pointer" strictly means an integer that happens to be the memory address of some data. Whereas in Java the term "reference" more closely matches the C++ "reference" concept. You can't work with the memory address directly even if you want to, but you use it the same way.)
Cat x = new Cat();
This line creates a Cat object in memory and stores a reference to it in x.
x now contains a reference to the Cat object, but if you were to do:
x = x + 1;
This would not give the next memory address like in C, but would give a compiler error. Java doesn't allow control to the reference or memory location.
If we think of references or pointers as a kind of means to access or handle the object in memory, they are much the same. However, they are different in terms of implementation. Following are the differences:
Pointers support pointer arithmetic and this makes them a kind of unsafe. Because they provide the programmer with an access level that is much more than needed. However, references provide an handle to the object through a much more abstract hided implementation.
Pointers are less strongly typed and references are more strongly typed. By this I mean the code is much simple in case of references and slightly less formal in case of pointers. You need to make use of reinterpret_cast kind of things to use pointers casts and on the other hand, references support easy casts of the kind of primitive kind of casts in "C".
Pointers are unsafe and references are safe. If you have an option between the two select references. In languages like C#, you have this freedom.
Pointers exists in C/C++ and references exist in Java. Do not confuse references in C/C++ with references in Java. References in C/C++ is a kind of synonym used for the rvalue of a pointer in C/C++.
No, Java does not have pointers. The fundamental concepts in Java are "values" vs "references".
A reference is a pointer that you can't normally see the value of (i.e., the memory address). The only operations allowed are to set it (from another reference) and to reference through it to the referred-to object. It can be set from a reference-valued expression, such as the new operator, or from another reference (which is syntactically a simple reference-valued expression).
In terms of Java syntax - it's true, that Java doesn't have pointers, but to clarify situation - Java Runtime has pointers.
Every time GC occurs, there is a big chance, that your object stored in the heap will physically change it's memory address. This is achievable only by using what is really called Pointer. As you come from C++ world - you know reference restrictions. But it doesn't mean that JVM doesn't use references =).
For further information take a look at Ordinary Object Pointer
So, as you have brief understanding of core JVM memory management, you can consider Java Reference term as Pointer at runtime.
No, there is no pass by reference at all. Only pass by value, since the real Java method argument is a copy of Java Reference, therefore - another Pointer.
So, in syntax usage way - Java Reference is closer to C++ Reference, but in real Runtime world it's close to Pointer.
P.s. for more clarification it's better to read more articles about Ordinary Object Pointer or take a loot at oop.hpp.
As Java does not support pointers. It may appear that references are special kind of pointers. But we must note the key difference: with a pointer, we can point any address (which is actually a number slot in a memory). So, it is quite possible that with a pointer, we can point an invalid address also and then we may face surprises issues during runtime. But reference types will always
point to valid addresses or they will point to null.
pointer only contain the address but Reference does not contains address if we say frankly then
address of the object is assigned to the index or we say can hash code and case code is given to the reference variable if we will see the content of the reference variable it starts with class Name # and after it some Hexadecimal Code. These nos are not address it is a index value or hash code.
second point
we can not perform any Arithmetic operations on values the Content of reference value

Pointer Model that Java has over C++

The single biggest difference between Java and C/C++ is that Java has
a pointer model that eliminates the possibility of overwriting memory
and corrupting data.
This is a quote from a textbook. I always assumed that it was C++ that used pointers and not Java. Can someone please elaborate on this?
I would argue against ever using the word "pointer" in describing a Java program. I always say "object reference" (or just "reference") instead.
A pointer, in C or C++, identifies a location in the process's virtual address space, and the virtual address space basically is a giant, typeless array. Given a pointer, you can add an offset to it, and get a pointer to a different location in the array. Given two pointers, you can compute the offset between them.
You can't do any of that with Java object references. A Java object reference identifies an object on the heap. The address of that object can (and probably does) change from time to time, but it's identity always is unique.
You can't "add an offset" to an object reference and get a different object reference. It doesn't make any sense.
They both use pointers.
In C++, pointers are actual memory addresses, meaning you can use one (via pointer arithmetic) to identify arbitrary memory locations.
In Java, pointers are opaque: knowing the value of one doesn't give you any information about anything other than the object it is pointing to.
Javas "reference system" is its pointer system. They're basically pointers without the possibility of casting to an incompatible type. It also does not allow you to use pointer arithmetic and like C and C++ do. In C++ you can corrupt your data by:
class SomeClass {
private:
int a;
public:
SomeClass(int a): a(a) {}
};
Later you can corrupt an object of the class by basically doing this:
SomeClass victim(2);
unsigned char *hazardousPointer = (unsigned char *) &victim;
for (int i = 0; i < sizeof(SomeClass); i++)
hazardousPointer[i] = 0;
This piece of code just allowed us to violate the private access rights and allowed to change its state (it could be also const, that does not matter). This happened due to the fact that C/C++ pointers are just memory addresses which pretty much behave like integers with some restrictions. Furthermore hazardousPointer[i] is just C/C++ syntactic suggar for *(hazardousPointer + i) which is not the case with Java, where arrays are objects which can even be returned from methods and have their own methods.
Furthermore Java has a garbage collector which cares about memory leaks, where C++ relies on its system stack and wrappers or smart pointers.
C++ uses pointers/references and it's the programmers responsibility to acquire and release dynamic memory allocations.
Java also does internally but in order to keep track of memory java uses a reference count which is in most simplest terms the evil Garbage Collector!
Java hides the pointers from the programmer and C++ doesn't thus making C++ far more powerful, but also dangerous. With Java you cannot allocate user defined objects on the stack (only primitives like int...) but in C++ you can use new keyword to allocate a user defined object on the heap or on the stack.
In java everything is references. so you can create as many aliases of a variable and if you update any one of it, it will be reflected in all the alias variable.
On the other hand, C++ has pointers and references both.

What is the difference between a pointer and a reference variable in Java?

My Java book explains that to use objects, we can assign them to reference variables. How is that different from a pointer to an object? Does Java have pointers?
Thanks :)
A reference is sort of like a pointer that you can't do arithmetic on... although it's more opaque. While the underlying bits may be an address in virtual memory, they don't have to be. They're just a way of getting to an object (or representing the null value). So while they're not exactly the same, if you're used to thinking of a pointer as "a way of identifying an object or navigating to it" (in some sense) then yes, those thoughts apply to references too.
Java doesn't have pointers as such (unlike, say, C# which has references and pointers - the latter being used in "unsafe" code).
The terms "reference" and "pointer" are basically equivalent. Much of the literature I've seen about the basics of Java claims that Java has no pointers. But if you try to use a null reference you get a NullPointerException. So it's all semantics.
(The real difference is, in C or C++ the term "pointer" strictly means an integer that happens to be the memory address of some data. Whereas in Java the term "reference" more closely matches the C++ "reference" concept. You can't work with the memory address directly even if you want to, but you use it the same way.)
Cat x = new Cat();
This line creates a Cat object in memory and stores a reference to it in x.
x now contains a reference to the Cat object, but if you were to do:
x = x + 1;
This would not give the next memory address like in C, but would give a compiler error. Java doesn't allow control to the reference or memory location.
If we think of references or pointers as a kind of means to access or handle the object in memory, they are much the same. However, they are different in terms of implementation. Following are the differences:
Pointers support pointer arithmetic and this makes them a kind of unsafe. Because they provide the programmer with an access level that is much more than needed. However, references provide an handle to the object through a much more abstract hided implementation.
Pointers are less strongly typed and references are more strongly typed. By this I mean the code is much simple in case of references and slightly less formal in case of pointers. You need to make use of reinterpret_cast kind of things to use pointers casts and on the other hand, references support easy casts of the kind of primitive kind of casts in "C".
Pointers are unsafe and references are safe. If you have an option between the two select references. In languages like C#, you have this freedom.
Pointers exists in C/C++ and references exist in Java. Do not confuse references in C/C++ with references in Java. References in C/C++ is a kind of synonym used for the rvalue of a pointer in C/C++.
No, Java does not have pointers. The fundamental concepts in Java are "values" vs "references".
A reference is a pointer that you can't normally see the value of (i.e., the memory address). The only operations allowed are to set it (from another reference) and to reference through it to the referred-to object. It can be set from a reference-valued expression, such as the new operator, or from another reference (which is syntactically a simple reference-valued expression).
In terms of Java syntax - it's true, that Java doesn't have pointers, but to clarify situation - Java Runtime has pointers.
Every time GC occurs, there is a big chance, that your object stored in the heap will physically change it's memory address. This is achievable only by using what is really called Pointer. As you come from C++ world - you know reference restrictions. But it doesn't mean that JVM doesn't use references =).
For further information take a look at Ordinary Object Pointer
So, as you have brief understanding of core JVM memory management, you can consider Java Reference term as Pointer at runtime.
No, there is no pass by reference at all. Only pass by value, since the real Java method argument is a copy of Java Reference, therefore - another Pointer.
So, in syntax usage way - Java Reference is closer to C++ Reference, but in real Runtime world it's close to Pointer.
P.s. for more clarification it's better to read more articles about Ordinary Object Pointer or take a loot at oop.hpp.
As Java does not support pointers. It may appear that references are special kind of pointers. But we must note the key difference: with a pointer, we can point any address (which is actually a number slot in a memory). So, it is quite possible that with a pointer, we can point an invalid address also and then we may face surprises issues during runtime. But reference types will always
point to valid addresses or they will point to null.
pointer only contain the address but Reference does not contains address if we say frankly then
address of the object is assigned to the index or we say can hash code and case code is given to the reference variable if we will see the content of the reference variable it starts with class Name # and after it some Hexadecimal Code. These nos are not address it is a index value or hash code.
second point
we can not perform any Arithmetic operations on values the Content of reference value

Is there a concept of "pointers" or "unsafe code" in Java?

Yesterday I was attending a talk by a CTO of a reputed European Company, and he told until recently he did not know that java has pointers. On confronting him he said he is absolutely sure about existence of pointers/unsafe code in java.
There's a class called sun.misc.Unsafe, that much is true. But it doesn't use pointers in Java code (because Java has no pointers, although I agree that java references are similar in concept), most of it is implemented using native code.
As I mentioned in the comments, this is not part of the public API and shouldn't be used by client code. However, you can see it at work when you look at the sources of the Atomic* classes in the java.util.concurrent.atomic package.
There are no pointers in Java, only safe references. Unfortunately your highly reputed CTO was wrong.
Unsafe code is integrated through JNI.
http://en.wikipedia.org/wiki/Java_Native_Interface
Java has pointers.
The confusion whether Java has pointers or not is strongly related to the discussion whether Java is call by reference or call by value.
Uninformed people think that Java has no pointers, and since a method can change an object that's passed in with the effects of this change vissible to the caller, they reason it must be call by reference.
This is not correct however.
What happens is that in Java pointers are passed by value. There are no other kinds of variables in Java for objects than pointer variables and there is no call by reference.
The "unsafe" story is quite something else. This normally is distinct from the question of whether Java has pointers or not. Java's pointers are safe; they point to objects and using the normal language constructs they can not be manipulated to point to arbitrary memory locations.
There is however JNI, but then native code does potentially unsafe things, not Java code.
There is also Real-time Java (jsr-1), where you absolutely can get access to specific memory locations in your system. This however is a very specific and rather rare version of Java that's mostly used for embedded purposes. If this was meant I guess it would have been explicitly mentioned.
Java has no pointers, only references to objects. A reference is similar to a pointer, because it points to a variable, an object, but you cannot view or edit the address memory of this reference, which you can do in C.
Another thing. In C, you can manage pointers with the referencing/dereferencing operation, putting a * first of the name of pointer. In Java, this operation, referencing/dereferencing, is completely absent, because it's totally automatic, hidden to the user.
Other info on Wikipedia and Oracle.
Pointer is the concept of pointing to the reference. In C and C++ you could access the pointer explicitly but in java we use reference to point the objects. For example If you are passing the an instance to a method, Its reference passing we know but ultimately pointer is passed. when you change state of the instance within the method it reflects when that instance is used after the completing the method call.
We use reference in java which is pointer with respect to JVM.
When we use new operator it create the instance in heap and returns the address to the reference its pointing.
I believe this would answer your question if not you could comment on my answer.
You can call native functions in Java (JNI), so in this sense you can use pointers. But other than that - no, there are no pointers in Java.
He may have a slight confusion with call-by-value and call-by-reference. If he comes from C, he may think that call-by-reference is equal to a pointer. Just a guess.

Does Java have pointers?

If Java does not have pointers, then what does the the new keyword do in Java?
As pointed out, Java has references. How are these different ?
you can't perform arithmetic or other such operations on these
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.
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.
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.
new does (roughly) the following:
Find a contiguous free block of heap memory equal to the instance size of the class you're creating, plus some space for bookkeeping
Zero said space & remove it from the free list
Run the constructor
Return a reference (NOT a pointer, as other posts have explained) to the created instance.
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);
}
}
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++.
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.
new in Java returns a reference to the newly created object.
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.
Java Does not have Pointers. The operator "new" is used to the reference variable in 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.)
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.

Categories