• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Bear Bibeault
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Junilu Lacar
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Jj Roberts
  • Tim Holloway
  • Piet Souris
Bartenders:
  • Himai Minh
  • Carey Brown
  • salvin francis

String Comparison

 
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, sorry if this is a lame question that I already ought to know (or has already been answered)
Given Strings s1 and s2, I was wondering what the real difference between s1 == s2 and s1.equals(s2) is


In my understanding, s1 == s2 must fail since they are two separate objects, but when I run the code, both if conditions pass & Hash codes are equal too...
 
Ranch Hand
Posts: 874
Android VI Editor Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

In my understanding, s1 == s2 must fail since they are two separate objects,



NO they are 2 references to *same* String literal in String Constant Pool.

check Javaranch Journal.
 
Vikram Ramaswamy
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I got it now. Thank you.
 
Balu Sadhasivam
Ranch Hand
Posts: 874
Android VI Editor Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

you are Welcome. and Indeed Welcome to Javaranch
 
Ranch Hand
Posts: 1179
Mac OS X Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you want to do the same check with Integer, Byte or Long - you will see that there are a Constant Pool limit of values in the range -128 to 127

Meaning the == will only work in the range -128 to 127
 
Ranch Hand
Posts: 449
Scala IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Rene Larsen wrote:Meaning the == will only work in the range -128 to 127


integers not being equal to one another
 
I am displeased. You are no longer allowed to read this tiny ad:
the value of filler advertising in 2020
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic