Win a copy of Practical SVG this week in the HTML/CSS/JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

+ Operator in String

 
Poornima Sharma
Ranch Hand
Posts: 114
  • 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
Sheriff
Posts: 22542
109
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • 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
  • 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
  • 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
  • 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
 
WHAT is your favorite color? Blue, no yellow, ahhhhhhh! Tiny ad:
the new thread boost feature brings a LOT of attention to your favorite threads
https://coderanch.com/t/674455/Thread-Boost-feature
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!