You are here: Home / Topics / Java String compareTo() Example Code

Java String compareTo() Example Code

Filed under: Java on 2023-10-26 21:45:31

class Main {
 public static void main(String[] args) {
   String str1 = "Learn Java";
   String str2 = "Learn Java";
   String str3 = "Learn Kolin";
   int result;

   // comparing str1 with str2
   result = str1.compareTo(str2);

   System.out.println(result);  // 0

   // comparing str1 with str3
   result = str1.compareTo(str3);

   System.out.println(result);  // -1

   // comparing str3 with str1
   result = str3.compareTo(str1);

   System.out.println(result);  // 1
 }
}

 

Example 2: Check if Two Strings are Equal

class Main {
 public static void main(String[] args) {
   String str1 = "Learn Python";
   String str2 = "Learn Java";
       
   // if str1 and str2 are equal, the result is 0
   if (str1.compareTo(str2) == 0) {

     System.out.println("str1 and str2 are equal");
   }
   else {
     System.out.println("str1 and str2 are not equal");
   }
 }
}


About Author:
M
Mr. Dubey     View Profile
Founder of MCQ Buddy. I just like to help others. This portal helps students in getting study material free. Share your stuff here so that others can get benefitted.