aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes String confusion Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "String confusion" Watch "String confusion" New topic
Author

String confusion

Maduranga Liyanage
Ranch Hand

Joined: May 25, 2005
Posts: 124
Please consider this code:

String str1 = "Hello";
String str2 = "World";
String str3 = "HelloWorld";
String str4 = "HelloWorld";
String str5 = str1 + str2;

int a = 1;
int b = 2;
int c = 3;
int d = a+b;


in main() method ....

str3==str4 //TRUE
str4==str5 // FALSE

(a+b)==c // TRUE
c==d // TRUE

Can somebody please explain me why "str4==str5" is FALSE and "c==d" is TRUE ???
I know "==" compares memory locations. So how come "c==d" ? doesnt the compiler put each integer value into a seperate memory location? Or do the integers also go into a pool like strings?

Please tell me why str3==str4 is TRUE but str4==str5 is FALSE, and why it is not the same concept with integers?

Thanks a lot guys..
[ May 31, 2005: Message edited by: Barry Gaunt ]
Nischal Tanna
Ranch Hand

Joined: Aug 19, 2003
Posts: 182
Try the following code.



Also if u using == with int operands, it compares the values and not references.


Thnx
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 10916
    
  12

i would say it's doing the same thing in both cases. we are comparing the value of what's stored in the variable. for the int variables, it's pretty obvious what's in there, and thus they are equal.

but for any kind of object, it gets a little trickier. what is basically stored in an object reference is the memory address of the object. you don't have access to that value - Java automatically 'de-references' the memory address for you, giving you the actual object when you need it. the '==' operator here will compare the variable here to see if they have the same value - i.e. point to the same spot in memory.

the compiler is smart enough to see that str3 and str4 refer to the same string literal, and thus assigns both to point to the same memory location.

however, when you say

str5 == str1 + str2;

you are creating a new object. the compiler CAN'T tell that this will ulitimatly end up being the same as the literal. it creates a new object, at a new memory location, and str5 refers to there. so, str5 refers to a different spot than str4, so the values stored in the variables are not equal.

did that make sense?


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Nischal Tanna
Ranch Hand

Joined: Aug 19, 2003
Posts: 182
Hi fred,
To question on my as well as ur reply... does that mean there will be duplicate literal values in the String pool?

str = "hello"
str1 = "hel"
str2 = "lo"

str3 = str1+str2

str == str3 // this will return false as we know

Thus from the above there will be two "hello" in the String pool?
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 10916
    
  12

I'm a little shaky on the intricacies of string pool, but here's how i THINK it works...

the string pool only hold string LITERALS. So in your last example, there will be three strings in it, "hello", "hel", and "lo". when you have the line

str3 = str1+str2;

it creates a new OBJECT, that happens to be a String-type object. this is created in a different space than the string pool. the reason being that the three literals are determined by the compiler, but the addition of the two strings has to be done at runtime. Therefore, it's handled differently.

Like i said, i'm not POSITIVE on all this, but someone will correct me shortly if i am wrong.
Steven Bell
Ranch Hand

Joined: Dec 29, 2004
Posts: 1071
I think fred has that about a close as it's going to get (if not right on).

Runtime created String's are not placed into the String pool unless the intern() method is called on them.

In the previous example if you made it:



I didn't actually run and test this.
Maduranga Liyanage
Ranch Hand

Joined: May 25, 2005
Posts: 124
Thanks a lot for the reply fellows.. it helped a lot..
Can somebody explain me this paragraph that appers in Sybex Java certification book"

"String S1 = new String("Hello");
When this line is compiled, the string literal "Hello" is placed into the pool. At runtime, the "new String()" statement is excuted and a fresh instance of String is constructed, duplicating the String in the literal pool. Finally, a reference to the new String is assigned to S1."

Can somebody tell me why there are two copies of "Hello", as it says?

Also can you please tell me what happens in compile time and run time from the above statement?

String str = "Hello";
Doesn't this statement create a new String object?

Thanks guys..
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608

String str = "Hello";
Doesn't this statement create a new String object?

Yes. The object is created at class load time.
http://qa.jtiger.org/GetQAndA.action?qids=68&showAnswers=true for more information and references.


Tony Morris
Java Q&A (FAQ, Trivia)
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 10916
    
  12

i think of it this way...

"String S1 = new String("Hello");

the compiler can see the "Hello" literal, and puts it in the string pool.

when the code is executed, we hit that "new" word. this says "hey, CREATE a BRAND NEW STRING object". the only place this new string object can be created is in the normal heap - we're done creating stuff in the string pool now. so, we make this new object, and 'seed' it with the value of that other string literal.

it sort of boils down to what the compiler can figure out and what it can't. it's pretty dumb. it can detect literals and puts them in the string pool. However, anything with the "new" operator it leaves alone - it's not it's job to figure out what to do with that keyword, so that gets handled at runtime.
Maduranga Liyanage
Ranch Hand

Joined: May 25, 2005
Posts: 124
String Str1 = "Hello";
String Str2 = "World";
String Str3 = "HelloWorld";
String Str4 = "Hello" + "World";
String Str5 = Str1 +Str2;

We know str3==str5 is FALSE because the addition takes place at runtime.
BUT, str3==str4 is TRUE! Doesn't this addition takes place at runtime too?
Steven Bell
Ranch Hand

Joined: Dec 29, 2004
Posts: 1071
No, the compiler is smart enough to see that everything there is a compile time constant and will resolve it at compile time. If you were to change it as such:

You would not get Str4 == Str3 (you really shouldn't capitalize the start of variable names) even though Str4 has the exact same value. The difference is it is theoretically possible for the value of 'blah' to be modified (as in pointing to a different String object) during runtime. In the case of 'blah' being a local method variable I'm not sure if it really is possible, but if it were class level another thread could modify it between the lines, however the compiler doesn't concern itself with things like that and just goes the 'safe' way of letting it be handled at runtime.
amit taneja
Ranch Hand

Joined: Mar 14, 2003
Posts: 806
what if

String str="abc";
str="cde";

now "abc" will be lost from the string pool ?



sometime in this forum why didn't see the page well alinged...
sometime horizontal bar come ..why ?


Thanks and Regards, Amit Taneja
thomas jacob
Ranch Hand

Joined: May 19, 2005
Posts: 91
I think these string basics will help us thru SCJP exam
1) Strings are immutable once initialized
2) Strings initialized at runtime are created as a new objects in memory
3) == operator compares string reference values
4) String Str = "Ja"+"va"; is initialized at compile time cos the compiler can see the value assigned to Str and then matches to similar values in the pool.
5)String Str = Str1+Str2; is initialized at runtime and the JVM doesn't bother to match existing similar string literal in the pool. so a new object is created
6)String Str=Str1; assignment will straightaway assign Str1 object to Str so no problems.

Hope this will help for the exam


Cheers
Jacob
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: String confusion
 
Similar Threads
Can anyone explain what is == and equal( ) ?
IF strings are immutable why is the variable s appending and changing its obect
equals() and ==, doubt
comparing Strings
equals versus ==