This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String, == and String constant pool

 
Rafa Barcel� Bauz�
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 643
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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
Posts: 2023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Strings, Literally
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic