• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

String & String Buffer

 
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
1)
public class MyClass
{
public static void main (String args[])
{
String strlit = "SCJP";

String strobj = new String ("SCJP");

System.out.println(strlit.hashCode() == strobj.hashCode());
}
}

2)

public class MyClass
{
public static void main (String args[])
{
StringBuffer strbuf = new StringBuffer("SCJP");

StringBuffer strbuf1 = new StringBuffer ("SCJP");

System.out.println(strbuf.hashCode() == strbuf1.hashCode() )
}


the 1) is giving out put as "true"

and the 2) is giving output as "flase"

can any one help me.
 
Ranch Hand
Posts: 558
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Please refer to String and StringBuffer API for equals ans hashCode.
 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The StringBuffer hashCode and equals method is not overridden, i.e., it uses the same hashCode method as provided by the Object implementation. To avoid this problem, the hash code retrieval should be changed to StringBuffer.toString().hashCode().
 
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If I slightly modify the example 2,
public class MyClass
{
public static void main (String args[])
{
StringBuffer strbuf = new StringBuffer("SCJP");

StringBuffer strbuf1 = new StringBuffer ("SCJP");

System.out.println(strbuf.equals(strbuf1));
}

will the output be false?
If so, why?
 
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
strbuf and strbuf1 are two different object references. And the equals method is not overridden in the StringBuffer class.

Therefore

strbuf.equals(strbuf1) will give false
reply
    Bookmark Topic Watch Topic
  • New Topic