Menus

Nov 23, 2018

Is java pass by value or pass by reference?


Java is Strictly Pass by Value.
Lets take an example for PRIMITIVE TYPE: Here an int is passed to the function “change()” as parameter and as a result the change in the value of that integer is not reflected in the main method.Because, Java creates a copy of the variable being passed in the method and then do the manipulations like in c/c++. Hence the change is not reflected in the main method.

And for the object type: In Java, all primitives like int, char, etc are similar to C/C++, but all non-primitives (or objects of any class) are always references. So it gets tricky when we pass object references to methods. Java creates a copy of references and pass it to method, but they still point to same memory reference. Mean if set some other object to reference passed inside method, the object from calling method as well its reference will remain unaffected. Actually java passes object reference as a value too.

No comments:

Post a Comment

Contact Form

Name

Email *

Message *