Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String & String Buffer

 
Ram Reddy
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
  • 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.
 
Srinivasan thoyyeti
Ranch Hand
Posts: 557
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please refer to String and StringBuffer API for equals ans hashCode.
 
Bodie Le
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • 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().
 
Srinivas Kumar
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • 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?
 
Thuwaragan Sundaramoorthy
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • 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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic