3

Possible Duplicate:
difference between string object and string literal

Hello,

Foremost, let’s come up with Java facts with String

Strings are immutable My Question - If Strings are immutable then below statement should have compilation error!

             String str = "xyz";
                     or
             String str = new String("xyz");

             str = "abc";        //COMPILATION ERROR
                 or
             str = new String("abc");  //COMPILATION ERROR

What is the difference between below instantiation ?

 String str = "xyz";
      and
 String str = new String("xyz");

Amit.

Community
  • 1
  • 1
Amit Yadav
  • 32,664
  • 6
  • 42
  • 57

5 Answers5

5

Strings are immutable means you can't do something like str[1] = 'x' i.e you cannot change the content of the string.

This will answer your second question.

Community
  • 1
  • 1
Prasoon Saurav
  • 91,295
  • 49
  • 239
  • 345
3

Strings are immutable, so you cannot change the contents of a string.

In the following code:

String str = "xyz";
str = "abc";

you're not changing the contents of a String instance, but rather assigning a new String instance to the variable str. That is, if you do:

String str = "xyz";
String otherStr = str;
String str = "abc";

Then otherStr will remain the same. So you're not actually changing the object that str points to.

As for your second question

String str = "xyz";

takes the a String-object with value "xyz" from the String pool, while

String str = new String("xyz");

instantiates a new object.

That is, if you do

String a = "xyz", b = "xyz";

you will have a == b, while if you do

String a = new String("xyz"), b = new String("xyz");

this will not be the case.example

For more information, see:

Community
  • 1
  • 1
Sebastian Paaske Tørholm
  • 49,493
  • 11
  • 100
  • 118
2

Strings are immutable. String references are not. That's the distinction.

So:

String str = "abc";

str is a variable, referring to an immutable string "abc". Now if I do:

str = "def";

str is still a variable, referring to a different immutable string ("def"). I can change what str points to all I want, str is a variable. I can't change the actual content of any string (because Java's strings are immutable, by design). Whenever you do something that would seem to modify the string (say, toUpperCase), what it's actually doing is creating a new string with a copy of the old string's contents, modified in the way described.

The point of having strings be immutable is that I know that if I have a reference to a string, that string can never change. This is a very useful guarantee when passing strings around. If we didn't have this guarantee, we'd be copying strings all the time just to protect ourselves from someone modifying them. For instance, consider a standard setter function for a name property:

void setName(String n) {
    this.name = n;
}

If strings weren't immutable, we'd have to do this:

void setName(String n) {
    this.name = new String(n); // Blech, duplication
}

...so that we know our copy of the string won't change in ways we don't expect it to. This would result in a lot of duplication of string data in memory, most of it unnecessary, and so the designers of Java quite intelligently decided that strings would be immutable, and any changes you might want would create a new string rather than modifying the old one in-place. (You can get modify-in-place behavior for those situations that really warrant it by using char[] instead.)


Regarding your separate question about the difference between str = "abc"; and str = new String("abc"), the difference is that the latter (using the constructor) is guaranteed to return a new reference, whereas the former is not. E.g.:

String a = "abc";
String b = "abc";
String c = new String("abc");

a == b (checking whether the references match, not the strings) will be true, because literal strings are interned. a == c is guaranteed to be false, because we used the constructor for c. a.equals(b) and a.equals(c) will both be true, because a, b, and c all refer to equivalent strings.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • @Crowder; this is regarding 'Blech, duplication' suppose i have 2 classes A and B and in B constructor i am passing reference of A; typically what we write a code A a; //declare a global variable and in constructor simply write this.a=${passed reference} i mean to say we don't use new operator for that....could you plz elaborate it and (2) how can i make my own class immutable ? – Amit Yadav Jun 03 '11 at 14:18
  • @Amit: This is going to sound like a joke, but it isn't: To make your own class immutable, don't provide any mutator functions. So for instance, if `A` accepts `foo` and `bar` as constructor arguments and makes them available via `getFoo` and `getBar` methods, *don't* provide `setFoo` and `setBar` mutator methods. Then ensure that either 1) The things you accept in the constructor are immutable (in which case you can just use the reference you were given, as you're doing now), or 2) If you accept anything that is mutable, make a *copy* of it for your own use, so nothing can change your copy. – T.J. Crowder Jun 03 '11 at 17:00
1

If Strings are immutable then below statement should have compilation error!

You are misunderstanding the immutability concept. Look at Prasoon's answer.
String immutability means you cannot alter the contents inside the string.

String a = "hello";
String b = "hello";    
System.out.println(a==b);   // returns true.

Here both a and b both string literals refer the same object.


What is the difference between two instantiations ?

String a = "hello";
String b = "hello";   
System.out.println(a==b); // returns true.

Both refer to same String literal.

String a = new String("hello");
String b = new String("hello"); 
System.out.println(a==b);  // returns false.

Two different String Objects are created.

Saurabh Gokhale
  • 53,625
  • 36
  • 139
  • 164
0
 String str = "xyz"; 

is an internal cached string instance.

 String str = new String("xyz");

is a new object not instanciated from the cache

As side fact notice the following behaviour ...

"xyz" == "xyz" evals true

new String("xyz") == new String("xyz") evals false

new String("xyz").equals(new String("xyz")) evals true

notice also that == in Java compares object references.

Manuel Salvadores
  • 16,287
  • 5
  • 37
  • 56
  • can you please explain me why it is returning true with equals() ? – Amit Yadav Jun 03 '11 at 09:41
  • `equals` implement string content comparison which in that case is true. `==` will test equality of object memory reference that will be true when reusing instances from the cache. – Manuel Salvadores Jun 03 '11 at 09:49