0

could someone explain this piece of code. The output is where I am confused. It seems only one thing (i.e. p) was modified by the modifyObject function, but the other (i.e. s) is left unchanged. But I am confused. Could someone explains what's going on.

class Person{

int a = 8;

public int getA() {
    return a;
}

public void setA(int a) {
    this.a = a;
}

@Override
public String toString() {
    return "Person [a=" + a + "]";
}

  }

public class TestMutable {
public static void main(String[] args)
{
    Person p = new Person();
    p.setA(34);


    String s = "bar";

             modifyObject(s, p);   //Call to modify objects

    System.out.println(s);
    System.out.println(p);

}



private static void modifyObject(String str, Person p)
{

        str = "foo";
        p.setA(45);

}

  }

why is it that the following is output? i.e. str is still bar , but person.A is now 45?

       bar
          Person [a=45]
john_w
  • 693
  • 1
  • 6
  • 25
  • `person.a` is different because you changed the instance's `a` property. `s` is unmodified because that's not how Java works; you pass in the string reference and update the reference locally, which has no effect on code external to `modifyObject`. – Dave Newton Jul 08 '21 at 17:06
  • `str =` replaces the reference in the variable `str`. `p.setA` modifies the object that is still in `p`. – chrylis -cautiouslyoptimistic- Jul 08 '21 at 17:07
  • @DaveNewton could you explain which instance get changed? and how do I know if I am passing in a string reference? is it possible to get some example. thank you – john_w Jul 08 '21 at 17:12
  • The only `Person` instance there is--`p`. You know if you're passing in a string reference if you're passing a string. See https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value e.g. The trick is to understand that Java is always pass-by-value, but the value passed for objects is an object handle (confusingly a reference to an object). – Dave Newton Jul 08 '21 at 17:15
  • @DaveNewton Does it have to do with the data being "primitive" type or "reference" type? – john_w Jul 08 '21 at 17:21
  • @john_w All parmaters are passed by value. An `int`, for example, has an integer value. An object's parameter value is the handle (reference) to that object. – Dave Newton Jul 08 '21 at 17:27

1 Answers1

0

You can see this thread to understand why String value doesn't change and how to make it to change it: Passing a String by Reference in Java?