0

I khow that java is pass-by-value, and when i pass a object into method and change it,it will change when i out method. But i can't do it with String object. This is example:

public class text 
{
    public void change(String a)
    {
        a = "ha";
    }

    public static void main(String[] args)
    {
        text a = new text();
        String b = "hi";
        a.change(b);
        System.out.println(b);
    }
}
john
  • 95
  • 6
  • 1
    http://stackoverflow.com/questions/1552301/immutability-of-strings-in-java <-- The answer you want and a lot more. – helderdarocha Jun 08 '14 at 00:46
  • Research on these "Java String literals", "String intern". I am sure after these you won't be having same questions. – Nu2Overflow Jun 08 '14 at 00:48
  • Assignment is an operation on variables, not objects. Assigning a new value to a variable doesn't change other variables. – user2357112 Jun 08 '14 at 00:49

2 Answers2

1
a = "ha";

That statement is analogous to this:

a = new String("ha");

So even if String were not immutable, you'd have the issue that you are now pointing a to a new String object.

What is happening here is just "compiler magic" or "syntactic sugar" to make it easier to declare a String.

Mike Thomsen
  • 36,828
  • 10
  • 60
  • 83
0

Not in this case, String is an immutable object. All you are saying in your change method is for "a" to point to a new object, but that "a" is a different pointer than your main "a" pointer.

rvijay007
  • 1,357
  • 12
  • 20