Java Program to compare strings for equality



To compare string for equality in Java, use the equals() method. Let us see some examples wherein we have checked for same as well as different string values.

Example

 Live Demo

public class Demo {
    public static void main(String[] args) {
       String one = "x";
       String two = "x";
       if(one.equals(two)) {
          System.out.println("String one is equal to two i.e. one==two");
       }else{
          System.out.println("String one is not equal to String two i.e. one!=two");
       }
    }
}

Output

String one is equal to two i.e. one==two

Let us see another example.

Example

 Live Demo

public class Demo {
    public static void main(String[] args) {
       String one = "x";
       String two = "y";
       if(one.equals(two)) {
          System.out.println("String one is equal to two i.e. one==two");
       }else{
          System.out.println("String one is not equal to String two i.e. one!=two");
       }
    }
}

Output

String one is not equal to String two i.e. one!=two
karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know


Advertisements