Java as a second language?

Started by
13 comments, last by Drathis 13 years, 8 months ago
Quote:Original post by BCullis
What tripped me up was the transition to "reference by default". Where C++ passes by value, Java will always pass by reference because all objects are treated like references. (and if I just horribly mis-described that, someone more knowledgeable feel free to smite me, this is just how it was explained to me).


This was stated a bit wrong. Java passes every reference by value. So, passing a reference of an Object to a method, inside the method you will have a new reference variable that contains the same value as what was passed to it. If you assign a different object, or a new object to that local variable, the original reference passed to the method will not lose it's reference to the original object, and will not point to the new one created.

public void foo(Object obj2){   //The local variable obj2 now contains a reference to a new Object   obj2 = new Object();}Object obj1 = new Object();foo(obj1);//obj1 still points to the original object
Advertisement
That reference stuff in java confused me as well, because I was coming from C++.

But basically, there is a notion of passing reference by reference and passing reference by value. Whereas in C++, its usually by reference or by value and not a mix.

But to point out an example, as shown already, In C++, passing reference by value is similar to this:
void foo(Object* obj){  obj->var = 0; //can change its values  obj = new Object; //can change where it points to, but is only valid inside this scope}Object *obj =  new Object(1);foo(obj); //inside foo, obj eventually points to a different memory location//outside, it points to the original location


Of course in C++ reference operator is the '&' sign, and not the '*' sign.
Edge cases will show your design flaws in your code!
Visit my site
Visit my FaceBook
Visit my github
So plain objects in Java behave similarly to pointers in C++?
I trust exceptions about as far as I can throw them.
Eesh... kind of. It would be better to say that plain object variables behave similarly to C++ pointers. The objects are still there, and still act the same; but whereas C++ has stack-allocated and heap-allocated objects, and only the latter really require pointers, Java has only heap-allocated objects, and thus needs all of its variables to be pointers.
Pro tip: don't try making a swap function as your first exercise :P

This topic is closed to new replies.

Advertisement