Sunday 25 September 2011

Frequent error

I was going through my answers on my Yahoo Answers profile
It was amazing
Atleast 25% were related to a common error
Using == to compare strings
We could not use == to compare two strings because they are the objects of String class present in java.lang package
To compare two strings we should use equals method
String s= "Hello";
if( s.equals("Hello") )
or
if( "Hello".equals(s) )
The second one is said to be more faster
To compare two string ignoring case
if( s.equalsIgnoreCase( "Hello"))

1 comment:

  1. not even faster, more reliable.. You see '==' operator compares the references of the string OBJECTS whereas equals() methods compares the actual CONTENTS..

    ReplyDelete