×

Comparetoignorecase in Java

In Java, the function compareToIgnoreCase ( ) is part of the String class, which is part of the java.lang package. It is used to compare any two strings while disregarding lower- and upper-case distinctions. The technique compares strings by utilising the Unicode value of each character included in both texts. The way we supply both strings to the method compareToIgnoreCase ( ) is identical to how we pass both strings to the method compareTo ( ) , and the function returns the following results.

  • If string 1 is longer than string 2 ,  a positive integer is returned.
  • If string 1 is smaller than string 2 , a negative integer is returned.
  • If string 1 and string 2 are equal , zero is returned.
public class CompareToIgnoreCase  
{ 
  


public static void main ( String args [ ] )  
{  
String str1 = " Book ";  
String str2 = " book ";  
String str3 = " look ";  
String str4 = " abc ";  
String str5 = " BEEN ";  
  
System.out.println ( str1.compareToIgnoreCase ( str2 ) ) ;  
System.out.println ( str1.compareToIgnoreCase ( str3 ) ) ;  
System.out.println ( str1.compareToIgnoreCase ( str4 ) ) ;  
System.out.println ( str1.compareToIgnoreCase (str5 ) ) ;  
  
}  
} 

Explanation : Because we are using compareToIgnoreCase ( ) for string comparison , str1 and str2 are viewed as identical strings. As a result , the first output is 0.

For the second output , the string str1 ( " Book " ) is compared to the str3  ( " look " ) , and the distance between ' B ' and 'l' is 10 according to the alphabetical order ( case sensitiveness is ignored ). As a result, 'l' can be considered as 'L'). Because ' B ' comes after ' l , ' the answer is -10.

The character ' B ' is compared to the character  ' a ' for the third output , and we know that the difference between ' B ' and ' a ' is 1. As a result , the output is 1.

" Book " is compared to " BEEN " for the fourth output. The first character of   " Book " is compared to the first character of "Been," and the result is 0. So , we take the second letter of both strings ( ' o ' of " Book " and ' E ' of BEEN ) into account , and we observe that the difference between ' o ' and ' E ' is 10.0 Because  ' o ' comes after ' E , ' the output is + 10.

In Java, we may also define our own compareToIgnoreCase() function. The method accepts two parameters, string str1 and string str2, and returns an integer. The following programme demonstrates this.

CompToIgnCase.java

public class CompToIgnCase  
{  
public int compToIgnCase ( String str1 , String str2 )  
{  
int i = 0 ;  
int j = 0 ;  
// converting strings to the   
// lowercase to maintain case insensitivity 
str1 = str1.toLowerCase ( ) ;  
str2 = str2.toLowerCase ( ) ;  
int cap1 = str1.length ( ) ;  
int cap2 = str2.length ( ) ;  
while (i < cap1 && j < cap2)  
{  
    char c1 = str1.charAt ( i ) ;  
    char c2 = str2.charAt ( j ) ;  
      
    // if equal characters, proceed to next iteration   
    if (c1 == c2)  
    {  
        i = i + 1 ;  
        j = j + 1 ;  
    }  
      
    else  
    {  
        // The codePointAt ( ) function returns the Unicode of characters in this case, 
    // we are calculating the difference
  // between Unicode of character 
        // at index I of string str1 and character at index j of  string str2.
        return (str1.codePointAt ( i ) - str2.codePointAt( j ) ) ;  
    }  
    }  
// if all the characters of the strings and lengths are equal return 0  
if (i == cap1 && j == cap2)  
{  
    return 0;  
}  


if (i < cap1)  
{  
    return cap1 – i ;  
}  
   
return (j - cap2) ;  
}  
 
public static void main ( String argvs [ ] )  
{  


CompToIgnCase object = new CompToIgnCase ( );  
String str1 = " Book " ;  
String str2 = " book " ;  
String str3 = " look " ;  
String str4 = " abc " ;  
String str5 = " BEEN " ;  
// invoking our own compToIgnCase ( ) method and displaying the result  
System.out.println (object.compToIgnCase (str1 , str2) ) ;  
System.out.println (object.compToIgnCase (str1 , str3) ) ;  
System.out.println (object.compToIgnCase (str1 , str4) ) ;  
System.out.println (object.compToIgnCase (str1 , str5) ) ;  
}  
}  

Output :

Comparetoignore case in Java

To retain case insensitivity, all alphabets in both strings are transformed to lowercase letters (not in uppercase). The following example will help to clarify things.

CompToIgnCase.java

public class CompToIgnCase  
{  
  
// main method  
public static void main(String argvs[])  
{  
String str1 = "6";  
String str2 = "Book";  
  
System.out.println(str1.compareToIgnoreCase(str2));  
  
}  
}  

Output :

Comparetoignore case in Java

Explanation:

 The Unicode value for ' 6 ' is 54 , while the value for ' B ' is 66 . As a result , the solution should be 54 - 66 = -12 . However , we receive -44 . Because the string " Book " is being transformed into " book , " and the Unicode value of ' b ' is 98 , this is the case. Thus , 54 - 98 equals -44 , as seen in the output. It demonstrates that the strings ' alphabets are changed into lowercase letters rather than uppercase letters . As a result , our custom compareToIgnoreCase ( ) function employs the toLoweCase ( ) method rather than the toUpperCase ( ) method.

When the first discrepancy is identified in the method compareToIgnoreCase ( ) , the comparison is terminated . It is seen from the first programme in this section, where " Book " is compared to " abc . " The first characters of each string are compared in this case, and we receive a mismatch . As a result , the remaining characters in both strings are ignored , and the comparison loop terminates to deliver the proper results .

When one of the strings has some extra characters and the remaining characters match the other string , simply the count of the extra characters is returned. Consider the following scenario .

CompToIgnCase.java

public class CompToIgnCase 
{  
  
// main method  
public static void main ( String args [ ] )  
{  
String str1 = " Booksss " ;  
String str2 = " Book " ;  
  
System.out.println (str1.compareToIgnoreCase (str2 ) ) ;  
  
}  
}  

Output :

Comparetoignore case in Java

Related Topics

Java float vs double

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

7 minutes read.

Tetranacci Number in Java

This article mainly describes tetranacci number identification and the Java Program for Tetranacci numbers. Tetranacci number Tetranacci numbers and Fibonacci numbers are related. The key contrast is that a Tetranacci number depends...

3 minutes read.

Resultset in java

Resultset: A result set is an interface that is present in the package java.sql and the resultset is used to store the data that are returned from the database table after...

5 minutes read.

How to Import Packages in Java

To know about the importing the packages of Java, we need to understand about how to packages work. Packages The package in Java is a collection of Classes and Interfaces. The packages...

3 minutes read.

Repdigit Numbers in Java

A combination of repeated and digit, the term is. A repdigit, also known as a monodigit or a positional number system, is a natural number in recreational mathematics made up...

3 minutes read.

Java Substring

What is a substring in Java? Here by the name  " substring " itself, we can easily come to know it is a part of a string or a subset of...

4 minutes read.

Binary Search Java

Binary search is a search mechanism for key elements from the given List/Array. In Binary search, the search mechanism is followed by dividing the array into parts; hence the search...

3 minutes read.

Memory Areas in Java

Let’s have a look at how memory management in Java works. We will be going to discuss how the objects get destroyed, the working of a garbage collector, and things...

5 minutes read.

Java 16

Java 16 is the most recent short-term incremental release, based on Java 15, and it was released on March 16, 2021. Records and sealed classes are just two of the...

11 minutes read.

Java Swing

Java Swing is the extension of Abstract Windows Toolkit (AWT). Any component designed in Swing will appear the same on any platform. Problems/Disadvantage of Abstract Windows Toolkit (AWT): As we know that...

27 minutes read.

Java exception list

Java uses exceptions, like the majority of contemporary programming languages, to deal with both errors and "extraordinary events." When an exception arises inside the program, it messes up the regular...

6 minutes read.

Annotations in Java

Annotations in Java Java Annotations are metadata about the source code. They do not have any direct effect on the execution of the java program. Annotations in Java were introduced in...

4 minutes read.

LCM Program in Java

LCM Program in Java The LCM program in Java outputs the LCM of the given numbers. In Arithmetic, the lowest common multiple, least common multiple or smallest common multiple of the...

6 minutes read.

How to Convert String to boolean in Java

How to Convert String to boolean in Java There are two methods to convert String to boolean: Using parseBoolean(string) method Using valueOf(string) method If the string contains "True," "true," or "TRUE,"...

3 minutes read.

Java Flags Enum

In a programming language, enumerations represent a group of named constants.For instance; the four suits in a deck of playing cards could be the enumerators Club, Diamond, Heart, and Spade,...

3 minutes read.

How to compare three dates in Java?

While using the date and the time in Java, we occasionally have to compare the dates. Java does not compare dates the same way it compares the two numbers. Therefore,...

6 minutes read.

Constructor Program in Java

Constructor Program in Java In Java, a constructor is a piece of code that is used to create an object. A constructor is called implicitly when an object is created in...

7 minutes read.

Median Of Stream Of Running Integers in Java

An integer array is given to us. Compute the median of the elements traversed so far in the input array. For the sake of simplicity, assume that there are no...

10 minutes read.

Three-way operator in Java

The ternary operator in Java is the only conditional operator that takes three operands. It's a popular one-line substitute for the if-then-else expression among Java programmers. If-else clauses can be...

3 minutes read.

Types of Garbage Collector in Java

Garbage collection is a Java feature that offers automatic memory management. The JVM is in charge of it. The programmer does not have to handle object creation and deallocation. We...

3 minutes read.