What exactly is a reference in Java? - java

What exactly is a reference in Java? Is it a memory address? Is a Java reference the equivalent of a dereferenced C++ pointer?
In other words, given the following:
Object o1 = new Object();
Object o2 = new Object();
o1 == o2
Is the above comparison the equivalent of comparing two pointers in C++?

o1 == o2 is pretty much equivalent to comparing two pointers in C/C++, yes.
But there are a two main differences between references in Java and pointers in C/C++ that are quite important:
Java references can't do pointer arithmetic: you can't "add 3" to a reference, you can only let it point to another (known) object
Java references are stongly typed: you can't "reinterpret" what lies on the other end of a reference unless you reinterpret it as a type that that object actually is.
Also a short note about the word "reference": C++ has references that act quite differently from both pointers in C and references in Java (but I don't know enough about C++ to tell you the specifics).
For a thorough discussion of this, see this related question on programmers.SE.

What exactly is a reference in Java?
It is an index of an object. It can be thought of as like a pointer but it differs in the fact that it
can change at any time.
does not always have a direct relationship with memory addresses.
is usually 32-bit in a 64-bit JVM.
you can't re-interpreter what the reference refers to. You can only change the type of the reference itself.
Is the above comparison the equivalent of comparing two pointers in C++?
Yes.
On Compresses Oops which allows a 64-bit JVM to sue 32-bit references.
Java HotSpot™ Virtual Machine Performance Enhancements - Compressed Oops
Compressed oops in the Hotspot JVM
IBM V6 - More effective heap usage using compressed references

Yes, a reference is basically the same thing as a pointer. By the way, if you call a method on a null reference, you get... a NullPointerException.
Note that it doesn't have to be a memory address, though. A given object can be stored elsewhere during a program execution, and still keep the same reference. But you don't need to care, as pointer arithmetic doesn't exist in Java.

A reference is a "pointer" to a memory address in Java, even though Java eleminates direct manipulation of pointers, unlike C++. Objects in Java are never passed to methods or returned by methods, it is always a reference that is being passed.

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.

Pointers in Java

C++ supports pointers whereas Java does not. But when many programmers questioned how you can work without pointers, the promoters began saying "Restricted pointers.” So we can say Java supports Restricted pointers?
The terminology is quite fuzzy here.
Java supports what it calls "references". References act a lot like pointers in C/C++-like languages. They don't act the same way "references" work in those languages.
The major differences between a pointer in C and a reference in Java are:
You can't do pointer arithmetic in Java (i.e. you can't "add" or "subtract" from a Java reference, you can only dereferencere it or compare it with another one).
You can't cast it to an incompatible type: Java is strongly type-safe, you can't "re-interpret" the bytes in memory as some other object.
For some uses of pointers this has no real effect (for example linked lists work pretty much the same in both languages), for others the difference is quite major (arrays in C are just fancy pointer arithmetic, in Java they work quite differently).
So in a way Java references could be called "restricted pointers".
Wikipedia defines a pointer as
... a programming language data type whose value refers directly to (or "points to") another value
Emphasis mine. According to this strict definition, Java doesn't have pointers.
The more general reference is the superclass of pointers, but also contrains more abstract things like file handles or even URLs.
Another important different between Java and C/C++ is that references are an index to an object. Whereas in C/C++ a pointer is an address in memory.
In the 32-bit JVM, they are the same thing, however in the 64-bit JVM they are not. Where you will notice this difference is that for heap sizes less than 32 GB, references are still 32-bit (even in a 64-bit JVM) This is because objects are allocated on an 8 byte boundary, so the index can refer to up to 32 GB of memory (4 G * 8 bytes)
In a 64-bit C/C++ programs, a pointer needs to be able to reference every byte even though memory allocation is on a 16 byte boundary and so it is 64-bit in size (technically it should be possible to make it 32-bit for less than 4 GB of memory.)
A smart pointer needs two underlying pointers (for a total of 16 bytes) but on gcc, the minimum allocation size for the reference count is 32 bytes (And then you have the size of the object you point to) The total size is 32 bytes + 16 bytes per pointer. c.f. 4 bytes per reference in Java. (8 bytes if you have 32+ GB of heap)
In summary, a Java reference doesn't have to be the actual address or even the same size as a pointer. It certainly much smaller than a smart pointer.
First, you need to understand "restricted pointers". Excerpt from Wikipedia:
One major problem with pointers is that as long as they can be
directly manipulated as a number, they can be made to point to unused
addresses or to data which is being used for other purposes. Many
languages, including most functional programming languages and recent
imperative languages like Java, replace pointers with a more opaque
type of reference, typically referred to as simply a reference, which
can only be used to refer to objects and not manipulated as numbers,
preventing this type of error. Array indexing is handled as a special
case.
What it means is that in Java, you can't add or subtract to a pointer since memory management is done by the JVM itself.
Java adopted reference. References have types, just like in C, and they're typesafe as these reference cannot be interpreted as raw address and unsafe conversion is not allowed.
When people say that Java doesn't support pointers, they are practicing
newspeak. What Java calls references correspond exactly to what has
always been known as pointers in the past.
What Java doesn't support is pointer arithmetic. Which is something
else entirely; as far as I know, C and its descendents are the only
typed languages which support pointer arithmetic. Pascal and Modula-2,
for example, have "pointers", described as pointers in their
specifications, but these pointers have a semantic far closer to that of
Java references; they don't allow pointer arithmetic.
Java actually does have pointer math. It comes with sun.misc.Unsafe. However, you have to manage the memory yourself - be careful.
Java has pointers. That's why it has a NullPointerException. It just doesn't have pointer math. Any reference to an object is actually a pointer, which is why it can be null. That said, there are plenty of useful programming languages which don't have pointers, so anyone who thinks that pointers are necessary for programming has a very narrow view of programming languages.
Let me be acid:
Java don't have pointers because it's designers decided to call them differently.
In fact they moved everything on the heap so that everything is managed by a pointer, then, since no direct reference existed anymore, canceled the "." and renamed "->" as "."
The Java language specification has this to say about the matter:
Java Language Spec §4.3.1
The reference values (often just references) are pointers to these objects, and a special null reference, which refers to no object.
For those who fear delving into documentation, the presence of e.g. Java’s NullPointerException should be a strong indication that Java does have pointers.
In short, the question is meaningless because it is based on a totally incorrect assumption that, quoting the OP, “Java does not pointers” – as proven above, that is technically bullshit.
See also James Kanze’s answer.
This answer can best be viewed as just supplying the necessary references to James’ answer.
Cheers & hth.
Pointers are just a way to make mutible return. They not really importend for effektiv work. It is easier to use and you can understand the code better than with pointers. In the most source code in c, I see the more &/*/-> than other things and you have ever look if you need it.

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

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