-4

I tried this code.

public class CopyOfMain {
    public static void main(String[] args) {

        CopyOfMain c = new  CopyOfMain();

        Emp e = new Emp();
        e.setName("Mick");
        c.edit(e);

        System.out.println(e.getName());

        String s = new String("hello");
        c.edit(s);

        System.out.println(s);

    }

    public void edit(Emp s) {
        s.setName("mickey");
    }


    public void edit(String s) {
        s.concat("world");
    }
}

Output:

mickey hello

WHy name in emp has changed ? But not with the string parameter? Is it because it is immutable class?

And If yes, then name in String is also immutable?

So how does first name get updated but not second?

THanks.

Raj
  • 692
  • 2
  • 9
  • 23

2 Answers2

2
    Emp e = new Emp();
    e.setName("Mick");
    c.edit(e);

Updated because - in Java "References to objects are passed by value" and your object is "Mutable" which means its value can be changed. You are replacing one string with another and returning the object. So, it is reflected. You are putting the String in an object and the reference changes the original object.

String s = new String("hello");
        c.edit(s);

Strings are immutable. Unless you "encapsulate them in another object or return them (which will return a new String, not the original one)" you cannot change its value

TheLostMind
  • 35,966
  • 12
  • 68
  • 104
  • But in the `emp` case , I have not return the object as you have mentioned in your answer – Raj Mar 18 '14 at 16:18
  • "References to objects are passed by value" , so whatever changes you make on the reference you have, are directly reflected in the original object". – TheLostMind Mar 18 '14 at 16:20
  • Does it applies to List also as list is also mutable ? – Raj Mar 18 '14 at 16:23
  • yes.. To every "mutable" object. Mutable means the object's attributes can be changed to have different values. here the encapsulating object is List, the list contains strings, so, you might create a new String in your "edit" function, but you will be using/editing the same list/ emp object. – TheLostMind Mar 18 '14 at 16:24
1

Yes, Strings are immutable in Java.

In the first edit method, you call a method call setName on your Emp object, which presumably changed its own internal reference to the employee's name to "mickey". That is the proper way to change a String -- have it refer to another String.

However, the concat method doesn't change s's contents; it returns another String that represents the concatenation, which you are ignoring. But even if you said

s = s.concat("world");

That would just change the local reference s to the new String; it wouldn't change the original String s in main. To that, you would need to change the original reference, and you can only do that in the main method itself, because that's where it's declared.

String s = new String("hello");
s = s.concat("world");
rgettman
  • 176,041
  • 30
  • 275
  • 357