• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String and StringBuffer

 
swarna kumar
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i came across this ques in RHE book,
code:
String s="abcde";
StringBuffer s1=new StringBuffer("abcde");
if(s.equals(s1))
s1=null;
if(s1.equals(s))
s=null;
the compilation succeds,
actually, we can't compare String to a StringBuffer. If we do, it would return false,
then how the compilation succeds without giving any exception.
let me know this
swarna
 
Corey McGlone
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Compilation succeeds because the equals method has the following signature:

It has this signature because it is inherited from the Object class. Therefore, you can pass any object to the equals method.
However, the first check that is done is to make sure that the object passed in is of the same type as the object, like this:

If this check fails, false is returned. Therefore, it is legal to compare a String to a StringBuffer, but the equals method will always return false because they are of differing types.
Corey
 
John Wolf
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But you should keep in mind that it will return true if you use toString() with StringBuffer. Eg.

Just an fyi...
Cheers!~
Sumit
 
srinivas bolloju
Ranch Hand
Posts: 112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,

where can i find instanceof in API
pls help
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The APIs are for methods, classes and packages descriptions.
instanceof is a keyword and can thus be found in JLS 15.20.2 Type Comparison Operator instanceof
[ July 24, 2002: Message edited by: Valentin Crettaz ]
 
srinivas bolloju
Ranch Hand
Posts: 112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thank you Val
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic