Wednesday, May 24, 2006

String comparison

One should not compare the String as follows -
string1 == string2

I will explain you with the example -
example 1 :

String a = "java";
String b = "java";
if (a == b)
System.out.println("campared using ==");
if(a.equals(b))
System.out.println("campared using equals()");

In this cases both the println statements will execute. Now consider the following example -

String a = "java";
String b = new String("java");
if (a == b)
System.out.println("campared using ==");
if(a.equals(b))
System.out.println("campared using equals()");

In this case the output will be "campared using equals()". This is bacause String objects are immutable. That means String objects cannot be modified. When we try to modify it the JVM internally creates the new String object which is hidden from us. In example 2, (a == b) compares the string object and (a.equals()) compares the object contents.
Whenever you require the String object to be modified later intead use StringBuffer. StringBuffer object is muttable. we can modify the content using append() method.

0 Comments:

Post a Comment

<< Home