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


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "String, == and String constant pool" Watch "String, == and String constant pool" New topic
Author

String, == and String constant pool

Rafa Barcel� Bauz�
Greenhorn

Joined: Aug 09, 2006
Posts: 22
Can someone help me about this questions?

1)

1- String a = "abc";
Create a new String object "abc" in the String constant pool and the
String reference variable a now refers to that object(in the String constant pool).

2- String b = "ab";
Create a new String object "ab" in the String constant pool and the String
reference variable b now refers to that object (in the String constant pool).

3- b = b + "c";
Create a new String "c" which is lost, and then create the String "abc",
and this "abc" was in the String constant pool when 'String a = "abc"'.

then, can someone tell me why a == b is not true??
*********************************************************
2)
Is this true?
If you write:
String a = new String("hello");

1- you are creating a new String object on the heap,and creating a new String "hello" in the String constant pool (if "abc" was not in), but a refers to the object on the heap, not to the object in the String constant pool.

2- if then you write String b = "abc", ofcourse a != b, but how a reuses the "abc" string in the String constant pool???

Thanks!!!
Gowher Naik
Ranch Hand

Joined: Feb 07, 2005
Posts: 643


Consider above code
case 1:
let us consider reference value of a=123
and reference value of b=456
They are two different string there reference value will be different.
now b=b+"c" concates c to string b and reference value of b is changed
because b=b+"c" creates new object.
now both string a and b are equal according to equals method
but reference is different
when we compare a==b now they have different references hence false.

case 2:
consider reference value of a1=657
consider reference value of b1=657
a1 and b1 will have same reference value because they are same strings.
so when they are compared using == the result will be true.
wise owen
Ranch Hand

Joined: Feb 02, 2006
Posts: 2023
Strings, Literally
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: String, == and String constant pool