• Post Reply Bookmark Topic Watch Topic
  • New Topic

String == vs equals  RSS feed

 
VenkataPrasad Regula
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am getting a strange output. the code is as follow



The above code is displaying both the statements. Same if I declare the variable as


In this case it is displaying only a.equals(b). Could someone explain why in the first case it is displaying both the statements.
 
Abhay Agarwal
Ranch Hand
Posts: 1376
Eclipse IDE Java
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When we assign String as

then String literal ("qwerty") is first searched in String pool. If there is already a String literal "qwerty" present in String pool then no new object is created. a_str will reference same "qwerty" literal.

When we assign String as

then there is no search of "qwerty" performed and a new object is created straight away.

Read this good article present on Javaranch about "String literal"
http://www.javaranch.com/journal/200409/Journal200409.jsp#a1
This will clear your doubts.

~ abhay



 
John Jai
Rancher
Posts: 1776
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Abhay - nice answer
 
VenkataPrasad Regula
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Abhay Thanks.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!