What's the difference between a Java reference and C++ reference - java

So I've been thinking (while reading this Java pdf)...
I know this may seem silly but why can't I do this in c++.
float &f = new float;
Isn't this saying the reference of f is the address of new float?
In Java, I see something like this
String s = new String("something")
String s is called a string reference.
Does the word 'reference' in Java have the same meaning as in C++?

Java references are much closer to C++ pointers rather than C++ references. In Java, you can do the following with a reference:
Change which object it refers to
Check whether two references are equal or unequal
Send messages to the referenced object.
In C++, pointers have these same properties. As a result, the code you're looking for in C++ is something like
float* f = new float;
Which is perfectly legal. For a better comparison, this Java code:
String myString = new String("This is a string!"); // Normally I wouldn't allocate a string here, but just for the parallel structure we will.
System.out.println(myString.length());
/* Reassign myString to point to a different string object. */
myString = new String("Here's another string!");
System.out.println(myString.length());
would map to this C++ code:
std::string* myString = new std::string("This is a string");
std::cout << myString->length() << std::endl;
delete myString; // No GC in C++!
/* Reassign myString to point to a different string object. */
myString = new std::string("Here's another string!");
std::cout << myString->length() << std::endl;
delete myString; // No GC in C++!
Hope this helps!

No in Java when you declare String s, s doesnt contain the address of the new String, but its value which in this case is something.
You can take a look at this post for more information about variable address locations in Java which is kind of meaningless.

In C++ you use pointers so if you have:
int foo = 0;
you can then have a pointer refer to the address of foo with:
int* bar = &foo;
This line of code says that the value of bar is foo's memory address.
Java manipulates objects by reference and every object is a reference but it also collects garbage automatically. If you use the new keyword in C++ you need to clean up the memory yourself:
float* f = new float(0); // Allocate memory
...
delete f; // Free memory

Yes, I agree with Joni, a c++ pointer is syntactically closer to a reference in Java.
The other important difference between a pointer and a reference in C++, a pointer can either point to a real object or it can be equal to null. A reference in C++, by definition, always points to a real object or variable. You must assign it to something real when you declare it.

To answer your question, for best practices only use the new or malloc operator to allocate space. Assuming that you are new to pointers, The big difference between pointers and references is that you must use an explicit operator-the * operator-to dereference a pointer, but you don't use an operator to dereference a reference.

Java parameters are close to C++ references. For instance;
When you are passing an object, actually you are passing a reference value. Therefore all objects are references in Java.
On the other hand, Java pass methods by value.
You can also check this link out.

In java reference, you can refer values or methods more than one times. But in c++,you can refer only one value in a single reference variable. So in java reference variables are more likely pointers of c++.Moreover java runs garbage collector automatically, so there is no use of delete key which is used in c++ to release memory.

Related

changing address of object in Java (pass-by-value again??)

Before I post my question, I have read the following excellent articles on java-pass-by-value.
I am convinced I have understood it well.
Is Java "pass-by-reference" or "pass-by-value"?
http://www.javaworld.com/article/2077424/learn-java/does-java-pass-by-reference-or-pass-by-value.html
My question has to do with a side-by comparison of Java with other language that supports pass-by-reference(C++ may be).
In case of Java, you have a handle (reference) pointing to the object in location A. so object itself could be modified. But It is not possible to change the object location itself.
I.e An object stored in memory address 0X945 cannot be changed to 0X948.
In languages such as C++, you can choose to pass-by-value or pass-by-reference. (It is in the hands of the programmer correct?). Hence it is possible to change the location of object in memory space correct?
P.S: I have good background on Java but on C++. so my views above may be wrong.
It is claimed in the article 1, I cited above that there is no notion of pointers in Java. I dont know how far that is true? (why do NullPointerException exists then)
EDIT:
consider this example:
void swap(Object A,Object B) {
Object temp=B;
Object B=A;
Oject A=temp;
}
when I call the method in Java such as swap(A,B), nothing happens
but in C++ (I presume), swap happens. which probably means I am changing the location of objects in memory correct?
In java even - references to objects are passed by value. i.e, everything is pass-by-value. Next,
you can choose to pass-by-value or pass-by-reference. (It is in the hands of the programmer correct?).
Correct. But you can't do it in Java.
An object stored in memory address 0X945 cannot be changed to 0X948.
You can't do this in both java and C++.
NullPointerException is thrown when you try to access a property / method of something which doesn't exist (is null). i.e, the reference points to null when an instance of the object is required.
Object o = null;
o.toString() --> NPE. o points to null.
so in C++, do pass-by-reference means you pass the object itself, so that it could be reassigned in swap method
In C++, pass by reference, swap(Object &A, Object &B) appears to be close to java's pass by value.
In Java Object A is a reference to an Object and is null by default. As Object is already a reference and so when this reference is copied, it is passed by value.
In C++, Object A is an instance of an Object and is always a unique object. As Object is an instance, you are passing by reference using Object& because the Object is not passed, but a reference to it.
Java is always pass by value, it's just when you are passing objects, the value passed is the location in memory so it can act like pass by reference.
when I call the method in Java such as swap(A,B), nothing happens but
in C++ (I presume), swap happens.
No it doesn't. "Nothing" also happens in C++.
A correct translation of the code to C++ would be:
void swap(Object *A,Object *B) {
Object *temp=B;
B=A;
A=temp;
}
(Yes, the syntax for types is different between the languages. Namely, the pointer-to-Foo type is written as Foo * in C++ and Foo in Java; that's just a syntactical difference between the languages.)

C++/Java reference variable

In Java, when I do
Foo bar = new Foo();
bar will be a variable containing the address of the newly constructed object. My professor call it a reference variable
The previous line is equivalent to this in C++:
Foo *bar = new Foo();
here, bar is a pointer to the object
So, is it true that a reference variable in Java is basically a pointer?
Also, when I do this in C++:
Foo bar;
is bar also a pointer? If not, then does that mean there is a difference in memory structure between
Foo bar;
and
Foo *bar = new Foo();
?
Pointers in C++ behave similarly to references in Java.
However, Foo bar; is very different from Foo *bar = new Foo();. The first creates an instance of Foo with automatic duration. It will be destroyed at the end of the block in which it is created. The second creates a dynamically allocated instance of Foo. It will stick around until it is explicitly deleted.
The first can't be used if you want the object to exist after the function returns. If you use a pointer or a reference to it after the function returns, bad things will happen. In that situation, you have to use the second form.
The advantage of the first form is that you don't have to worry about memory management. It will be automatically destroyed at the end of its scope. With the second form, you have to manually delete it, or manage it with a smart pointer of some kind.
If you wonder whether the term "pointer" is appropriate for each language, given each language's specification, then yes.
In the Java language specification, Java references are called "pointers":
An object is a class instance or an array.
The reference values (often just references) are pointers to these objects, and a special null reference, which refers to no object.
In the C++ language specification (which is an international ISO standard, the C++ standard), C++ pointers are called "pointers".
So, is it true that a reference variable in Java is basically a pointer?
--> In short YES! But as c++ allow you to manipulate pointers, java does not. (Similar would be good word to differentiate)
Foo bar; // bar is allocated on stack in c++
--> In java this is just declaration of bar of type Foo.
In c++ objects can be saved on stack as well as on heap while in Java objects are stored only on heap while object references pointing to objects are on stack.
Foo *bar = new Foo(); // C++ : *bar is on stack while memory allocated is on heap
Foo bar = new Foo(); // Java : bar on stack and object created using new is on heap
Also, when I do this in C++:
Foo bar; is bar also a pointer? If not, then does that mean there is a
difference in memory structure between
Foo bar;
It isn't a pointer. It is just an object created on the stack.
In Java all objects are references or pointers, or returns an address using new
The difference between C++ pointers and Java "pointers" is that you can't have pointer arithmetic in Java.
And last time I read The Java Programming Language, it says references are pointers.
Well, if you want to be picky they are actually not exactly like pointers:
Pointer arithmetic is not allowed with Java pointers. You cannot increment, decrement, multiply, etc pointers to move what they point to in memory.
Not Strongly typed. In C, you can cast a pointer from one type to pretty much any type wth no consequence (as long as you are careful). In Java, you will get an exception if you try to cast between incompatible types.
Otherwise they behave pretty much the same way as pointers, and as long as you do not need any of the above features of C-style pointers, you will probably not notice a difference.
A pointer is a value that represents a memory address.
A reference is a value that refers to an object.
Pointers are one way to realize references. In fact, there are several ways to use pointers to realize references, because most objects take up more than one address, so you have to define to which address the reference points.
A few differences:
You can do math with pointers, because adresses are integer values. A reference value has no inherent meaning, it just represents an object.
A pointer can point to any value, eg., a field in an object; a reference always represents the entire object.
It would be more accurate to compare them to Pascal pointers. They have many of the same characteristics: strongly typed, no arithmetic, can be null.

What exactly is null in Java memory [duplicate]

This question already has answers here:
What is null in Java?
(14 answers)
Closed 9 years ago.
If I declare some string variable like
String str = null;
Is there memory allocated for variable str?
If allocated, how many bytes will be allocated?
If not allocated, how does the JVM know that there is some variable called str been declared?
If allocated and if there is null value inside the memory, then what exactly is the representation of null in binary?
When you do something like:
String str = null;
The only thing allocated is a reference to a string (this is analogous to a string-pointer in languages which contain pointer-types). This reference is a 32 or 64 bit variable (depending upon your hardware architecture and Java version) which resides on the stack (probably, depending upon the exact context in which your declaration is placed).
No memory should be allocated for the null itself, because null is not actually a valid object instance. It is simply a placeholder that indicates that the object reference is not currently referring to an object. Probably it is simply the literal value 0, such that assigning an object reference to null is equivalent to setting a pointer type to NULL in C/C++. But that last bit is conjecture on my part.
Null is the value of a reference that is not bound to an object.
Space is allocated for the reference variable itself, regardless of its value. Null is merely a value that fits within this space.
To answer each question for the specific example.
Yes, there is space allocated for the variable str.
The size of the memory allocated for the reference variable is probably four bytes.
It is allocated, and the JVM follows the instructions of the compiled code to access it.
It doesn't matter.
Take a look at this Java IAQ (infrequently asked question) "Is null an object?".
To answer your questions:
Only memory to store the reference is allocated
The java standard doesn't specify how much memory a reference takes up (although, in practice it is usually 32 or 64 bits depending on your JVM - although some JVMs try to beat this)
The memory representation of null doesn't matter, since you can't do bit level operations on it (or assign it to anything that isn't a reference)
Java works on references. Think of String str=null as you have pointer in C, but not exactly pointer.
Now internal representation dependes upon the JVM. It is not easy to calculate the size of reference. The implementation differs per JVM so there is no point extracting that low level info.
After doing this line:
String str = null; // or String str;
Only a reference of type String is allocated into the stack. null means that you don't assign any value (object) to the reference str into the heap.

C++ create Object accesible by . operator on heap?

this might be stupid question, but:
When I moved from ASM to C (no, I am not actually that old, I just started to love programing on MCU), I LOVED the way heap memory is used. Malloc was my friend, and I quickly became familiar with pointers. BUT...
Than I moved to OOP and Java. And actully, despite I donĀ“t like Java as a runtime, I love its language. Now, I would like to combine both, speed and memory management capabilities of C and the beauty of OOP. So I started to learn C++.
My problem is, in Java I was used to access class members and functions with . operator. In C++, I have to use somehow not so nice and easy to type -> operator.
So, my question is, is there some way you can use . operator instead of -> to access class members of object allocated on heap? Becouse, stack is limited, and the true power of OOP is in dynamic creation of objects. Remaining "differences" are OK :) . Well, maybe C++ yould allow you to define class methods inside class, but no one can have everything, right? :D Thanks.
Class &c = *c_ptr; // dereference pointer
https://isocpp.org/wiki/faq/references
Sure. Just get a reference to some object allocated on the heap (or the stack, but that's beyond scope):
Object* my_obj_ptr = SomehowGetHeapObject();
Object& my_obj = *my_obj_ptr;
...then you can use the dot operator on the reference:
my_obj.Foo();
Perhaps a pertinent question would be, why is this throwing you off?
No, that is not posssible, at least without some syntax changes. You can use (*Pointer).Function, which Pointer->Function is just a synonym for, but I think the latter is more comfirtable (that's why it exists).
EDIT: Or as the other posts say, just store the dereferenced pointer in a reference. Haven't thought about that, as the whole question is a bit strange.
In C++ there are two ways to access members of an object, depending upon how you are holding the object. If you have the object directly (or have a reference to it), you use the dot operator, .. If you have a pointer to the object, you use the pointer operator ->.
Consider:
class C;
...
// creates a new copy of "c" on stack
int f(C c) {
c.something = c.else;
}
// creates a reference to caller's "c"
int f(C& c) {
c.something = c.else;
}
// creates a pointer to caller's "c"
int f(C* p) {
c->something = c->else;
}
So, your problem is this: you have a pointer, but you don't like the pointer operator. Frankly, I don't really see this as a problem, you should just use the pointer operator until you like it. But, this is SO, so here is a solution.
Initialize a reference from your pointer, and use the reference instead:
int f(C* p) {
C& c = *p;
c.something = c.else; // update the object pointed to by 'p'
}
Or, to make it feel even more natural:
int f2(C& c) {
c.something = c.else; // updates f1's object
}
int f1() {
C* p = new C;
f2(*p);
delete p; // don't forget this step!
}

What's your deep comprehension of pointer,reference and Handle in C,C++ and Java?

What's your deep comprehension of pointer,reference and Handle in C,C++ and Java?
We usually think about the pointer,reference and Handle on the specify language level, it's easy to make confusion by the newbie like me.
Actually all those concept in java, just a encapsulation of pointer.
All pointer just a encapsulation of main memory addresses .
So all of those ,just a encapsulation wiles.
all above, it's my personal glimpse. And what's your comprehension ?
welcome to share with me.
Each language has differences to this respect. In C there are only pointers that are variables holding a memory address. In C you can use pointer arithmetic to move through memory, if you have an array, you can get a pointer to the first element and navigate the memory by incrementing the pointer.
Java references are similar to pointers in that they refer to a location in memory, but you cannot use pointer arithmetic on them. Only assignments are allowed. Note that the reference is not the object, but a way of accessing an object. This can be seen in argument passing semantics: objects are not passed by reference, references are passed by value:
public static void swap( Object o1, Object o2 )
{
Object tmp = o1;
o1 = o2;
o2 = tmp;
}
The previous piece of code is a complex no-op. References to two objects are passed by value, they are played with inside the method and nothing happens from the caller perspective: the real objects do not suffer any change, nor do the references the caller has into those objects. That is, if the call is swap( ref1, ref2 ), the system will make copies of the references into o1 and o2, the copies are changed within the method, but the caller variables ref1 and ref2 will remain unchanged after the method call.
In C++ you have two concepts: pointers are the same as C pointers and close to Java references, while C++ references are aliases into the objects they refer. C++ references can only be initialized with one object/data element in construction and from there on, using the original object and the reference is exactly the same. Besides the fact that references don't hold the resource and thus the destructor will not be called when the reference goes out of scope, nor will the reference notice if the referred object is destroyed, for all other uses the two names are the same element.
template <typename T>
void swap( T & a, T & b )
{
T tmp( a );
a = b;
b = tmp;
}
The code above in C++ differs from the Java version in that it does change the caller objects. If a caller uses swap( var1, var2 ), then the references are bound to those variables, and it is var1 and var2 the ones that suffer the change. After the call, the value of var1 and var2 is actually swapped.
Handles are in a different level, they are not language construct but tokens provided by a library so that you can later on refer to some resource that the library manages internally. The most general case are integer handles that are ids (or offsets) into a resource table, but I have seen strings used as handles. It is the library internally who decides what is exactly a handler (a pointer, an integer, a string or a more complex data structure). Handles are meant to be opaque in that the only sensible use is to store them and later give it back to the same library as part of other function signatures.
In C++ a pointer is a variable that points to a location in memory. You can access the object or data stored there by dereferencing the pointer. A reference is simply a pointer that has two distinctions from a pointer. First, you cannot change what a reference points to once the reference is initialized. Second the dereferencing semantics are removed so you can access a reference as if it were an object allocated on the stack instead of on the heap with new.
In Java, there are no pointers, only references. Every object you use is a reference to an object allocated on the heap. The downside is you can't do pointer math tricks. That's also the upside.
EDIT:
As pointed out in the comments, a Java reference differs from a C++ reference in that it can be reassigned once initialized. They are still called 'reference types' by the language specification, but behaviorally they act like pointers in terms of being able to be reassigned and passed to functions, but the semantics of dereferencing them look like non-pointer access looks in C++.

Categories

Resources