Java String compareToIgnoreCase example

String's compareToIgnoreCase method is similar to compareTo method. Only difference with compareTo is that it ignores cases.It also compares Strings lexigraphically. Both String get converted to unicode value and then compares.

If you call str1. compareToIgnoreCase(str2)

then if it returns
positive number : str1 is greater than str2
0: str1 is equal to str2
negative number : str1 is smaller than str2

package org.arpit.java2blog;

public class StringCompareToIgnoreCaseMain {
 public static void main(String[] args) {
  String str1="Java2blog";
     String str2="hello";
    String str3="World";
    String str4="JAVA2BLOG";
    
    System.out.println("comparing java2blog with hello : "+str1.compareToIgnoreCase(str2));
    System.out.println("comparing hello with world : "+str2.compareToIgnoreCase(str3));
  System.out.println("comparing java2blog with java2blog : "+str1.compareToIgnoreCase(str4));
  
 }
 
}

When you run above program, you will get below output:
comparing java2blog with hello : 2
comparing hello with world : -15
comparing java2blog with java2blog : 0

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus

 

Java tutorial for beginners Copyright © 2012