my dog learned polymorphism*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes + Operator in String Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "+ Operator in String" Watch "+ Operator in String" New topic
Author

+ Operator in String

Poornima Sharma
Ranch Hand

Joined: Sep 09, 2008
Posts: 114
Why does + operator in string does not create a new String?


Poornima Sharma
SCJP 6.0
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18917
    
  40

Where have you heard that it does not? Or are you asking why *does* it create a new string?

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
victor kamat
Ranch Hand

Joined: Jan 10, 2007
Posts: 247
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

Joined: Oct 09, 2007
Posts: 206

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.


Enjoy, Chander
SCJP 5, Oracle Certified PL/SQL Developer
Thomas Thevis
Ranch Hand

Joined: Sep 02, 2008
Posts: 87
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


SCJP 5.0, SCJD in progress
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: + Operator in String