myobj as written below is object of MyClass and in changeVal() method, i am changing state of this object and it is getting reflected in Main method.
It looks like objects are still getting passed by reference.
Can anybody please clarify this?
As you are passing the reference of object.....you are not changing the value of reference....
public static void main(String df)
SomeObj o=new SomeObj();
In this the reference o is still pointing to old object(created in main)......
so there is no effect on the value of reference o so it is not pass by reference......
Thanks for the explaination.
But, behavior of java's call by value concept looks same as the behavior of the C++'s call by reference.
I got the concept that in java, copy of reference is passed while in C++, address of object itself gets passed. But , what is the use of supporting pass by value instead of pass by reference in java.
Raj Kumar Bindal wrote:But, behavior of java's call by value concept looks same as the behavior of the C++'s call by reference.
Look at the following line of code, which could be C++ or Java:
If this is C++, it has a different meaning than if this is Java. In C++, variables represent objects directly. So, in C++, the line above would create a SomeClass object, and the variable 'something' directly represents that object. In Java, the variable 'something' would be a reference to a SomeClass object. The line above in Java does not create a new object - it only creates a new variable that's initialized to null (if it's a member variable - local variables aren't initialized to a default value).
Raj Kumar Bindal wrote:But , what is the use of supporting pass by value instead of pass by reference in java.
Pass-by-reference is not necessary in Java, because variables of non-primitive types are references themselves. There's no need to have a separate pass-by-reference mechanism if you can just pass references by value.
As Jesper has explained, the two behaviours are very different. It is hazardous to think that Java is some sort of extension or upgrade of C++. It isn't. It is a completely different language which happens to use similar syntax.
Raj Kumar Bindal wrote: . . . behavior of java's call by value concept looks same as the behavior of the C++'s call by reference. . . .