Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

strings

 
Parameswaran Thangavel
Ranch Hand
Posts: 485
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi all
the only difference between the string and stringbuffer is former is immutable the latter is muttable.

but i baffled at the output of the following code

1. What is the output of the following
StringBuffer sb1 = new StringBuffer("Amit");
StringBuffer sb2= new StringBuffer("Amit");
String ss1 = "Amit";
System.out.println(sb1==sb2);
System.out.println(sb1.equals(sb2));
System.out.println(sb1.equals(ss1));
System.out.println("Poddar".substring(3));

Ans:
a) false
false
false
dar
b) false
true
false
Poddar
c) Compiler Error
d) true
true
false
dar

ans:a how

to my knowledge it is

false
true
true
dar
 
Sakthi Kani
Ranch Hand
Posts: 98
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi paramesh

Stringbuffer class doesnot overwrite the equals methods. so (==) and (equals) are same in Stringbuffer class
 
sai Venka
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Paramesh,

Actually the StringBuffer class doesn't override the equals() method.so when you call the equals method by sb1.equals(sb2),it will call the parent class equals() method ie,Object class.

The basic rule is when you override the equals() method you should override the hashCode() method also.so, when you call the equals() method of Object class it will call the hashCode()method of Object class.if you check the eqauls() and hashCode() methods explanation in API Reference,they clearly mentioned that

As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.)


so it will return different hashCode values.so you will get false.


StringBuffer sb1 = new StringBuffer("Amit");
StringBuffer sb2 = new StringBuffer("Amit");
String ss1 = "Amit";
System.out.println("hash code sb1-->"+sb1.hashCode());
System.out.println("hash code sb2-->"+sb2.hashCode());
System.out.println("hash code ss1-->"+ss1.hashCode());
System.out.println(sb1==sb2);
System.out.println(sb1.equals(sb2));
System.out.println(sb1.equals(ss1));
System.out.println("Poddar".substring(3));


Output
hash code sb1-->2571580
hash code sb2-->2452092
hash code ss1-->2044535
false
false
false
dar

Check what output you are getting when you run the same program with String class.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic