on Leave a Comment

Java Program to Compare Two Strings

In java, we can compare two strings using some predefined methods namely, equals() and equalsIgnoreCase() method. Strings can also be compared using == operator.

Java program to compare strings by equals() method

public class CompareString{
   public static void main(String []args){
      String s1 = "pctechnicalpro";
      String s2 = "pctechnicalpro";
      String s3 = "Pctechnicalpro";
      String s4 = new String ("pctechnicalpro");
   
      //compare s1 with s2
      System.out.println(s1.equals(s2));
   
      //compare s1 with s3
      System.out.println(s1.equals(s3));
   
      //compare s1 with s4
      System.out.println(s1.equals(s4));
   }
}

Output:

true
false
true

equals() method return true if sequence of characters is same in both string objects, otherwise it returns false.

Java program to compare strings by equalsIgnoreCase() method

public class CompareString{
   public static void main(String []args){
      String s1 = "pctechnicalpro";
      String s2 = "pctechnicalpro";
      String s3 = "Pctechnicalpro";
      String s4 = new String ("pctechnicalpro");
   
      //compare s1 with s2
      System.out.println(s1.equalsIgnoreCase(s2));
   
      //compare s1 with s3
      System.out.println(s1.equalsIgnoreCase(s3));
   
      //compare s1 with s4
      System.out.println(s1.equalsIgnoreCase(s4));
   }
}

Output:

true
true
true

equalsIgnoreCase() method ignore the case and returns true if both string objects have same sequence of character, otherwise it returns false.






0 comments:

Post a Comment