Meaningless Drivel is fun!*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes String & String Buffer Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "String & String Buffer" Watch "String & String Buffer" New topic
Author

String & String Buffer

Ram Reddy
Ranch Hand

Joined: Feb 20, 2007
Posts: 88
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

Joined: Feb 15, 2007
Posts: 557
Please refer to String and StringBuffer API for equals ans hashCode.


Thanks & Regards, T.Srinivasan
SCWCD 1.4(89%), SCJP 5.0(75%)
Bodie Le
Greenhorn

Joined: Feb 06, 2007
Posts: 1
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

Joined: Jul 14, 2005
Posts: 52
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

Joined: Jan 11, 2007
Posts: 26
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


------------------------------<br />SCJP 1.5
 
Consider Paul's rocket mass heater.
 
subject: String & String Buffer
 
Similar Threads
String equvalence....
String equvalence....
Is this a Java Program?
Equality of String objects
SCJP