This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Java in General and the fly likes How does String str = Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "How does String str = "str" work?" Watch "How does String str = "str" work?" New topic
Author

How does String str = "str" work?

Madhusudhan Rao
Greenhorn

Joined: Aug 10, 2005
Posts: 1
How does Java create a new String object when it sees the followin?


The String class in itself does not seem to answer this question.

Does the Java compiler pre-process this into something like this?


Tried to Google but could not find any link that answers this.

Cheers
-Madhu
Joanne Neal
Rancher

Joined: Aug 05, 2005
Posts: 3429
    
  12
Not quite that simple. Literal strings are cached, so the actual byte code will first check if an object matching the required string is in the cache and if it is then str will reference that object. If it isn't then a new String object will be created and added to the cache and str will then reference the new object.
So if you had the lines

both str1 and str2 would be pointing to the same object.


Joanne
Peter Chase
Ranch Hand

Joined: Oct 30, 2001
Posts: 1970
Originally posted by Madhusudhan Rao:
The String class in itself does not seem to answer this question.


The Java Language Specification does explain (albeit in not very simple language) this stuff.


Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
Rick O'Shay
Ranch Hand

Joined: Sep 19, 2004
Posts: 531
>> String str = new String("some string");

The reason this is not done is for efficiency. The compiler will fix up the reference to a constant in the string pool, not an object on the heap. Which of these is faster? The answer is 2 is way faster because it takes zero nanoseconds to assemble at runtime. Lotta folks mistakenly think that + is slower in general but that's only true when concatenating variables.

1. Use StringBuilder

StringBuilder builder = new StringBuilder();
builder.append("one ");
builder.append("two ");
builder.append("three ");
String message = builder.toString();

2. Use concatenation operator

String message = "one " + "two " + "three ";
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

Hi,

Welcome to JavaRanch!

Most of what's been posted here is correct, although the statement that the JVM decides at the time this line is executed whether to create a String is wrong: that decision is made when the class is loaded. The bytecode, as Rick correctly points out, just directly fetches a constant from the class's data -- which will be a reference to the internal String pool.

In any case, the whole notion of String interning and String literal handling is part and parcel of the SCJP exam; if this interests you, you might want to pick up an SCJP study guide. Further questions on this topic probably belong in the Beginner's forum rather than here.


[Jess in Action][AskingGoodQuestions]
Ronnie Ho
Ranch Hand

Joined: Aug 10, 2005
Posts: 47

Lotta folks mistakenly think that + is slower in general but that's only true when concatenating variables.


I thought the + is slower only if it's used within a loop because the java compiler automatically transform the + operator. For example,
String xyz = x + y + z;
transforms to:
String xyz = new StringBuffer().append(x).append(y).append(z).toString();
If the statement is within a loop, I understand extra memory allocated for the temp "StringBuffer" object hurts performance, but if it's just one single statement, does the use of + hurt performance as well ?
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
[EFH]: In any case, the whole notion of String interning and String literal handling is part and parcel of the SCJP exam

Not really. The real exam is carefully worded to avoid this issue. The problem is that many mock exams inadvertently raise the issue by using Strings in questions about garbage collection. It's very easy to accidentally create a question which depends on understanding String pooling, even though the real exam doesn't do this (as far as I'm aware).

[Rick]: The compiler will fix up the reference to a constant in the string pool, not an object on the heap

Mmmmh, a String literal will (at runtime) have a regular String object which iss located on the heap same as any other object - it's just that there's also an additional reference to that object which is kept in the intern pool. And each class that used the literal will also keep a reference to the associated String.


"I'm not back." - Bill Harding, Twister
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
Ronmate, welcome to JavaRanch. Please take another look at our display name policy and then edit your display name to include both a first and last name. Thanks.
Rick O'Shay
Ranch Hand

Joined: Sep 19, 2004
Posts: 531
Originally posted by Ronmate:

The java compiler automatically transform the + operator...
String xyz = new StringBuffer().append(x).append(y).append(z).toString();


Good point Ron! I believe that is the case for any Java compiler introduced since the turn of the century. Any compiler worth its minerals should be able to unroll a loop with a constant iteration expression, too, although I would not bank on that one. A cool IDE plug-in would be to show the byte code which was generated by your compiler.
Rick O'Shay
Ranch Hand

Joined: Sep 19, 2004
Posts: 531
Speaking of performance, it's a good idea to use StringBuilderrather than the old StringBufferif you can use Java 5.0: StringBuffer methods are synchronized. I heard a rumor it might help on the 5.0 exam, too
[ August 10, 2005: Message edited by: Rick O'Shay ]
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

Originally posted by Jim Yingst:
[b]
Not really.


Interesting! I've not taken the exam, so I didn't know this. So whenever one of these interminable "How many strings are created?" threads starts up, is it valid to say "THAT'S NOT ON THE EXAM!!!" as a way to quickly end it?
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by Rick O'Shay:

A cool IDE plug-in would be to show the byte code which was generated by your compiler.


That's probably why it exists for Eclipse: http://andrei.gmxhome.de/bytecode/


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Rick O'Shay
Ranch Hand

Joined: Sep 19, 2004
Posts: 531
Nice. Installed using the Eclipse update manager and it worked out of the box (Eclipse 3.1 with Java 5.0). Works great. Not sure what Byte Code Reference View is, however, seems to do nothing. Byte Code View shows the disassembled code.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: How does String str = "str" work?
 
Similar Threads
retrieving value from a text box
strings immutable
regarding Strings
Immutable String
Help with int Conversion to String