Comparing Strings with (possible) null values in java?


Strings in Java represents an array of characters. They are represented by the String class.

Using compareTo() method

The compareTo() method of the String class two Strings (char by char) it also accepts null values. This method returns an integer representing the result, if the value of the obtained integer is −

  • 0: Given two Strings are equal or, null.
  • 1 or less: The current String preceeds the argument.
  • 1 or more: The current String succeeds the argument.

Example

import java.util.Scanner;
public class CompringStrings {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter your first string value: ");
      String str1 = sc.next();
      System.out.println("Enter your second string value: ");
      String str2 = sc.next();
      //Comparing two Strings
      int res = str1.compareTo(str2);
      System.out.println(res);
      if(res==0) {
         System.out.println("Both Strings are null or equal");
      }else if(res<0){
         System.out.println(""+str1+" preceeds "+str2+"");
      }else if(res>0){
         System.out.println(""+str2+" preceeds "+str1+"");
      }
   }
}

Output

Enter your first string value:
null
Enter your second string value:
null
0
Both Strings are null or equal

Output

Enter your first string value:
mango
Enter your second string value:
apple
-1
apple preceeds mango

Using equals() method of the Object class

In the same way the equals() method of the object class accepts two String values and returns a boolean value, which is true if both are equal (or, null) and false if not.

Example

import java.util.Scanner;
public class CompringStrings {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter your first string value: ");
      String str1 = sc.next();
      System.out.println("Enter your second string value: ");
      String str2 = sc.next();
      if(str1.equals(str2)) {
         System.out.println("Both Strings are null or equal");
      }else {
         System.out.println("Both Strings are not equal");
      }
   }
}

Output1

Enter your first string value:
null
Enter your second string value:
null
0
Both Strings are null or equal

Updated on: 07-Aug-2019

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements