• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How does String str = "str" work?

 
Madhusudhan Rao
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Rick O'Shay
Ranch Hand
Posts: 531
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
>> 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
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Ronnie Ho
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
[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.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 531
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 531
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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/
 
Rick O'Shay
Ranch Hand
Posts: 531
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic