• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Liutauras Vilda
  • Jeanne Boyarsky
  • paul wheaton
Sheriffs:
  • Ron McLeod
  • Devaka Cooray
  • Henry Wong
Saloon Keepers:
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Tim Moores
  • Mikalai Zaikin
Bartenders:
  • Frits Walraven

String.equals

 
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Refer to the following code:
\\many codes here
StringBuffer s1 = new StringBuffer( "String" );
StringBuffer s2 = new StringBuffer( "String" );
if ( s1.equals( s2 ) )
{
System.out.println( "TRUE" );
}
else
{
System.out.println( "FALSE" );
}
//many codes here.
This code compiled no error with output is "FALSE".
I know equals() is the method which declared in class String, why can we called by class StingBuffer directly here?
Besides, why can we get the result "TRUE" if we change variable type of s1 from StringBuffer to String instead of "FALSE" with the type is StringBuffer? Thanks.
 
Ranch Hand
Posts: 142
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
String class has equlas method overridden so it returns true where as in case StringBuffer equals method is not overridden it uses object's equals(as all classes extend object by default) method which performs reference comparision so it returns false.

Hth
sunil.s
------------------
"Winners don't do different things
They do things differently"
 
Ranch Hand
Posts: 133
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi, Bin:
You can refer to the following thread for a roundup. Hope it helps.
http://www.javaranch.com/ubb/Forum24/HTML/006994.html
 
Bin Wu
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Sunikumar,Tom, thanks a lot for your great help. I see.
 
There is no beard big enough to make me comfortable enough with my masculinity to wear pink. Tiny ad:
Gift giving made easy with the permaculture playing cards
https://coderanch.com/t/777758/Gift-giving-easy-permaculture-playing
reply
    Bookmark Topic Watch Topic
  • New Topic