-3

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());
    }

}
  • 2
    *"non-primitive data types are passed by reference"* This is not exactly correct - in Java, non-primitive data types are reference types, but references are values and are passed by value. – kaya3 May 03 '21 at 04:27
  • 3
    The method changeValue is NOT changing the value. It is creating a new object. (test = new Test();) – Luixv May 03 '21 at 04:28
  • It doesn't make any sense for `changeValue()` to be static, or to be implemented the way it is. `setValue()` is correct: imitate. 'In Java, non-primitive data types are passed by reference': no they aren't. And even if they were, your `changeValue()` method would not work as desired. – user207421 May 03 '21 at 04:49
  • 1
    Poor title. Rewrite to summarize your specific technical issue. – Basil Bourque May 03 '21 at 05:14

1 Answers1

2
public static void changeValue(Test test, String value) { //Function to change the value of an object
    test = new Test(); 
    test.setValue(value);
}

In here you are creating a new Test object which you don't need to do because the value that you will change will be the value of new object just simply delete this line: test = new Test() by doing this now you will be changing the value of object whose reference you have send in arguments.

Parwinder Bhangu
  • 39
  • 1
  • 1
  • 5