In Java, non-primitive data types are passed by reference. So, this means whatever change is made to that object will be global.
In the code below, a Test
object is passed to a static function changeValue()
to change the value of its attribute.
So, from my knowledge the object is passed by reference, so the output should be:
test1 : Fuzzy
test2 : Billboard
But, the output is:
test1 : Fuzzy
test2 : Wuzzy
What am I missing here?
class Test {
private String value; // instance variable
public void setValue(String value) { // setter function
this.value = value;
}
public String getValue() { // getter function
return value;
}
public static void changeValue(Test test, String value) { //Function to change the value of an object
test = new Test();
test.setValue(value);
}
public static void main(String args[]) {
// Object creation
Test test1 = new Test();
Test test2 = new Test();
// Setting value
test1.setValue("Fuzzy");
test2.setValue("Wuzzy");
// Changing value of test2
Test.changeValue(test2, "Billboard");
// Printing values of the objects
System.out.println("test1 : " + test1.getValue());
System.out.println("test2 : " + test2.getValue());
}
}