Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

String comparison  RSS feed

 
Vinayak patil
Ranch Hand
Posts: 67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I have a doubt about String comparison. I know that we have to use "equals" to check if two strings are same. But I tried the following code :


And I am getting the output as "Both are equal".
I was under the impression that When str= "<some content> is given, a new String object is created and I was expecting the comparison to fail.
Please let me know why I am getting the result.
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Whenever you create a String literal, it is placed in the literal pool.

If you create another reference to the same String literal, then that reference points to the object in the literal pool.

A new String isn't created.
 
Vinayak patil
Ranch Hand
Posts: 67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Keith for your response. Has helped me understand String comparison

-Vinayak
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try

str1 = "Java";
str2 = "Ja" + "va";

and let us know what you get.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Stan James:
Try

str1 = "Java";
str2 = "Ja" + "va";

and let us know what you get.


Probably the same, as "Ja" + "va" is a compile time constant, and therefore the compiler should be able to see that it's the same String as "Java".
 
Nils Alexander
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The way you wrote the code calls the compiler optimisation. Because you create the string implicit only one object is created with two identical references. To create two objects use:

 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Probably the same, as "Ja" + "va" is a compile time constant, and therefore the compiler should be able to see that it's the same String as "Java".


Yeah, I thought about that being compile time shortly after posting. Guess I wanted variables? Maybe I should just try it.

String ja = "Ja"
String va = "va"
String j2 = ja + va

??
[ June 25, 2006: Message edited by: Stan James ]
 
wise owen
Ranch Hand
Posts: 2023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
String Literal Pool.
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!