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.
Related
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
I have recently started to learn c++ on my own and I have some prior knowledge of Java.I was wondering is there an option to typecast in c++.
Like in java
char ch=(char)(65); would store 'A' in ch
or int n='a'; would store 97 in n
Does c++ have same or similar options?
For a first transition to C++, you'll be fine most of the time with static_cast for explicit conversions:
int i = static_cast<int>('c');
Of course there are also implicit conversions:
int i = 'c';
char c = 32;
And special promotion rules
char a = 'a', b = 'b';
auto result = a + b; // result is int now
Then there are the other cast operators:
dynamic_cast to cast from base to derived types.
reinterpret_cast to make your code fail - sometimes - and you don't know why.
const_cast to remove constness from expressions (but only if they are not const, that is).
C++ has casts. C-style casts () (avoid them), static_cast, dynamic_cast, reinterpret_cast (be very careful), const_cast (only very rarely the right choice), std::dynamic_pointer_cast, std::forward (yes, that's a cast), std::move (yes, that's also a cast).
C++ is not Java. Don't expect much of your Java knowledge to carry over. In many cases the two languages have constructs that look the same at the source code level but do very or subtly different things. They also use a lot of common terminology, but what is meant by a term in one language can be different in the other.
There are also implicit conversions, converting constructors and conversion operators.
C++ has several different cast operators that are used to access memory objects and each of these has differences in how they operate. In order to understand casting in C++ you need to understand the differences between these different casting methods and why you would use one or the other.
However first you must understand two fundamental differences between Java and C++ when it comes to how variables and objects are allocated and stored in memory.
The most fundamental difference between the two languages is the compile target for the two languages. Java is compiled into byte code and runs on a virtual machine. C++, most often, is compiled into native machine code and runs on the actual hardware using the hardware facilities such as CPU registers.
I used the caveat of "most often" for C++ because there are compilers, the Microsoft Visual Studio has such an option, that will generate byte code that runs on a virtual machine. However in most instances C++ is compiled to native, hardware machine code.
The second major difference between the two is how objects and variables and classes are stored and managed, how assignment works, and what kinds of information is available at runtime about the objects and variables and classes.
Java has a central memory store where objects are allocated with the new operator. This means that a Java variable is not a physical storage area containing the object but rather a physical storage area that contains a reference which points to the actual storage area in the central memory store.
This central storage area contains not only the memory area for the actual objects but also information about the classes from which the objects are instantiated. In other words much of the type information available in the source code at compile time is also available to the virtual machine in which the program is running allowing the virtual machine to determine if a cast is valid at runtime when the conversion is being done.
C++ variables are memory areas where the value of the variable or object is actually stored. C++ has pointer variables which contain the address of the memory area where an object is stored and it has reference variables which contain a reference to the address of the memory area where an object is stored. However when you are accessing a C++ object or variable with the name of the object or variable, you are accessing the memory area of the object directly and not through a reference the way it is done in Java.
So an assignment statement in Java which assigns one object to another is really just making a copy of the reference rather than the actual object. This is why after doing an assignment you now have two variables pointing to the same thing. An assignment statement in C++ which assigns one object to another is making a copy of the actual object itself into another memory area which results in two copies of the same object.
The C++ language and compilers are designed to do validity checking when the source code is compiled and to remove much of the overhead involved in the checking that the Java virtual machine does. So the C++ compiler strips away most of the class information when it compiles the source code. There is the Runtime Type Identification option that can be used however there is additional overhead involved with using that (see How expensive is RTTI? ) and since C++ is running native on the hardware, there is no virtual machine that is using that information to decide as to the validity of operations.
Over the years C++ has improved the ability of the programmer to write source code which allows the compiler to catch typical types of mistakes. The changes in the cast operators and the addition of several types of cast operators was one of those improvements to address an area where it is easy to make a mistake that can cause problems yet be difficult to debug.
For further details concerning the different types of C++ casts see the following:
When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used?
Regular cast vs. static_cast vs. dynamic_cast
dynamic_cast and static_cast in C++
Why use static_cast<int>(x) instead of (int)x?
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.
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
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.