Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String consant pool

 
K Anshul
Ranch Hand
Posts: 71
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


It gives the output
arit
amit
false
true

Why doesn't it give the output
arit
amit
true
true


Because it's giving false does it mean s2 is not refering to the string already in the String constant pool called "arit".
Why does it create a new object when String "arit" already exists.
 
arnel nicolas
Ranch Hand
Posts: 149
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The line String s2=s1.replace('m','r'), this actually creates a new object in the heap.It means that s2 now is pointing on a different object.When you are going to use the == for comparison it will compare both operands via their reference type. It is another story if you are going to use the equal operator(s2.equals(s3) which will turn out true.Both operands
are compared by their value.

arnel
 
arnel nicolas
Ranch Hand
Posts: 149
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Another thing, String are immutable. So if you you use any
of its methods it actually creates another String object.

arnel
 
Corey McGlone
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And none of this is on the exam.
 
K Anshul
Ranch Hand
Posts: 71
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Corey McGlone:
And none of this is on the exam.


Nice to know that
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic