Enter your E-mail Address below for Free E-mail Alerts right Into your Inbox: -

Tuesday

How String Comparison works in java or Facts about String in java

How String Comparison works in java or Facts about String in java

String is the one of the mostly used feature in java. All java programmers came across this that what i am going to explain here. But they didn't care about it means they are not interested to know how java works...:).

Let me consider a simple program.

public static void main(String args[])
{
String s1 = "hai how r u";
        String s2 = "hai how r u";
        String s3 = new String(s1);
        
        if(s1==s2){
            System.out.println("s1 == s2 : TRUE");
        } else {
            System.out.println("s1 == s2 : FALSE");
        }
        if(s1.equals(s2)){
            System.out.println("s1.equals(s2) : TRUE");
        } else {
            System.out.println("s1.equals(s2) : FALSE");
        }
        
        if(s1==s3){
            System.out.println("s1 == s3 : TRUE");
        } else {
            System.out.println("s1 == s3 : FALSE");
        }
        if(s1.equals(s3)){
            System.out.println("s1.equals(s3) : TRUE");
        } else {
            System.out.println("s1.equals(s3) : FALSE");
        }


}

Frankly just answer this program without seeing the output. Did you know how the below output comes, what are the things gone innerside.

Output:-

s1 == s2 : TRUE
s1.equals(s2) : TRUE
s1 == s3 : FALSE

s1.equals(s3) : TRUE

In java If you create a String it just looks inside the String pool to verify whether any other literals are there with the same value, then its reference is given to the new one.Otherwise a new reference is given to the new literal.

Thus the "==" operator compares the reference(memory location) and values and return true.The equals also compares the value and returns true.

But the s3 is created by new keyword hence it occupies a new location in java heap. thus the "==" operator fails but the equals operator succeeds.

No comments:

Post a Comment