File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

+ Operator in String

 
Poornima Sharma
Ranch Hand
Posts: 114
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why does + operator in string does not create a new String?
 
Henry Wong
author
Marshal
Pie
Posts: 20836
75
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Where have you heard that it does not? Or are you asking why *does* it create a new string?

Henry
 
victor kamat
Ranch Hand
Posts: 247
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you do

String str = "abc";
str = str + "be";

then the JVM creates string "abc" and then when you do the second operation, it creates a second string "abcbe" and assigns to the reference str.

If now you do String x = "abcbe"
then x refers to the same object that str refers above ( after the 2nd assignment).

But if you do String x = new String("abcbe");
then x refers to another object altogether.
 
chander shivdasani
Ranch Hand
Posts: 206
Eclipse IDE Ubuntu
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well it does create a new String. Strings in Java are immutable. When you perform a Concatenation Operation, the resultant object is thus a new object.
 
Thomas Thevis
Ranch Hand
Posts: 87
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well it does create a new String.

There is a small exception from this rule, as far as I know. The String class holds a pool of String references and it could be that you get a reference to an already created String. You can manipulate the defaut behaviour by using the String.intern() method. Therefore it is possible that Strings which pass the equals() test do also pass the '==' test. However, this is nothing to rely on and in general you can say that you'll get a new String object in most cases.

Regards,
Thomas
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic