1

in below code although I am updating StringBuilder roar3 inside roar(String roar1, StringBuilder roar3) method but how it affects roar2 in main() method? Same thing does not affect int x or y in intUpdate(int x, int y) also not for String roar1.

public class TestReference {

    public void roar(String roar1, StringBuilder roar3) {
        roar1.concat("!!!");
        roar3.append("!!!");
    }

    public void intUpdate(int  x, int y) {
        x=1;
        y=2;
    }

    public static void main(String[] args) {
        String roar1 = "roar";
        StringBuilder roar2 = new StringBuilder("roar");
        new TestReference().roar(roar1, roar2);

        System.out.println(roar1 + " " + roar2);


        int x=-1,y=-2;
        new TestReference().intUpdate(x, y);

        System.out.println(x + " " + y);
    }
}
Harshit kyal
  • 365
  • 1
  • 5
  • 24
Aminul
  • 1,427
  • 2
  • 8
  • 16
  • Must be new classes.. – user2864740 Dec 26 '17 at 05:22
  • tldr: 1) modifying an *object* in one place modifies *that same object* everywhere (see the the API for what methods *mutate* an object); 2) [re-]assigning to local variables does not modify any object or argument.. – user2864740 Dec 26 '17 at 05:23
  • I love how upvotes come so freely for certain kinds of questions :} – user2864740 Dec 26 '17 at 05:25
  • @user2864740 I don't think it is a dupe of that. Because, the confusion is really about the immutability. – Suresh Atta Dec 26 '17 at 05:28
  • @ꜱᴜʀᴇꜱʜᴀᴛᴛᴀ I'd say "half duplicate" (due to bringing in the ints), there are definitely questions that are duplicates wrt *String being immutable*. Feel free to link them in. – user2864740 Dec 26 '17 at 05:30
  • https://stackoverflow.com/questions/1552301/immutability-of-strings-in-java?noredirect=1&lq=1 (re-assignment of a variable is not related to mutability of the object being assigned) , https://stackoverflow.com/questions/20945049/is-a-java-string-really-immutable (the mutable is defined at the contract level) – user2864740 Dec 26 '17 at 05:32

0 Answers0