Java Program to compare strings for equality

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 12-Dec-2018 07:50:22
Advertisements