• Post Reply Bookmark Topic Watch Topic
  • New Topic

Please explain the below reason.  RSS feed

 
Saxena Sajal
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
String s1 = "abcd5"

String s2 = "abcd"+"5"

String s3 = "abcd"+s1.length()

system.out.println(s1 == s2)

system.out.println(s2 == s3)

system.out.println(s1 == s3)

answer is true , false , false.

I am not getting why "abcd"+s1.length() is not pointing to same ref as s1 in string constant pool. Please explain this.
 
Knute Snortum
Sheriff
Posts: 4281
127
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Someone more knowledgeable than me may correct me, but I believe that the JVM knows how to create a single string with "abcd" + "5", because they are both constants. "abcd" + s1.length() is evaluated at runtime, too late to combine the string.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Knute is right
 
Knute Snortum
Sheriff
Posts: 4281
127
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I love being right.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!