• 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
  • Ron McLeod
  • Tim Cooke
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • Junilu Lacar
  • Rob Spoor
  • Jeanne Boyarsky
Saloon Keepers:
  • Stephan van Hulst
  • Carey Brown
  • Tim Holloway
  • Piet Souris
Bartenders:

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
 
this llama doesn't want your drama, he just wants this tiny ad for his mama
The Low Tech Laboratory Movie Kickstarter is LIVE NOW!
https://www.kickstarter.com/projects/paulwheaton/low-tech
reply
    Bookmark Topic Watch Topic
  • New Topic