• 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
  • Rob Spoor
  • Tim Cooke
  • Junilu Lacar
Sheriffs:
  • Henry Wong
  • Liutauras Vilda
  • Jeanne Boyarsky
Saloon Keepers:
  • Jesse Silverman
  • Tim Holloway
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Mikalai Zaikin
  • Piet Souris

Java Language Problem

 
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
class Test {

public static void main(String[] args) {
StringBuffer str1 = new StringBuffer("Test");
StringBuffer str2 = new StringBuffer("Test");
System.out.println(str1.equals(str2));
Integer i1 = new Integer(9);
Integer i2 = new Integer(9);
System.out.println(i1.equals(i2));
}
}
The output of the above code is:
false
true

Could someone please explain me. I was expecting true for both.
 
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
StringBuffer class does not override the method "equals()". But all the wrapper classes(Integer....) do. That is why for Integer u get a true but for StringBuffer the result is false. If a class does not override the equals() then the results are as if u were using "==". If u go through the API doc for "Object", that would also clear things a bit.
regards,
Ankur
 
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Well, whenever you use .equals() method with objects of numberic type (Integer, Float, etc) or String, the comparison is done with the value in the object. But when you use objects of other types, then the addresses of the object reference are compared. ie., in your example, whether variables str1 and str2 points to the same memory location or not. Here, str1 and str2 points to different locations. So, str1.equals(str2) returned false. But, for Integer variable their values were compared, so i1.equals(i2) returned true.
[This message has been edited by Shriram Shivakumar (edited June 22, 2000).]
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic