Embarrassing !!!!
public class TestingPassByValue {
public static void main(String[] args) {
String object1 = "Hello";
display(object1);
changeAndDisplay(object1);
display(object1);
}
private static void changeAndDisplay(String object1) {
object1 = "Changed Hello";
display(object1);
}
private static void display(String object1) {
System.out.println(object1);
}
}
Ans:
Hello
Changed Hello
Hello
Had to think why this was the case. I mean In Java Objects are passed around by Reference right !!!! and primitives are passed by Value.
Well the Culprit lies in that sentence. In Java Objects are passed by Reference, but the problem is that the Objects themselves are not passed around, rather its the reference thats passed around. And the reference variables (primitives themselves) are passed by value.
So basically everything in Java is passed by Value, and objects being passed by reference is just a side effect ;-) ... Basics .. tch tch
1 Comments:
Yes, references are passed by value in Java. But this does NOT mean that objects are passed by reference. Pass-by-value and pass-by-reference refer to how an lvalue is affected by being used as a function argument.
By Anonymous, at 7:24 AM
Post a Comment
<< Home