×

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 String equals() method

equals() method compares two string based on the their content. Syntax public boolean equals(Objects anObject) parameter anObject: Object to be compared with the current String. Returns It returns true when the current String is equivalent to...

1 minute read.

Array Programs in Java

Array Programs in Java: An array is a data structure that stores similar elements in a contiguous memory location. In Java, an array is an object that stores the same...

7 minutes read.

Java Integer equals() method

The equals() method of Integer class compares the given object to the specified object. Syntax public boolean equals(Object obj) Parameters The parameter ‘obj’ represents the object to be compared with. Overrides The equals() method overrides equals...

1 minute read.

Java CountDownLatch

Another crucial classes for concurrent execution is CountDownLatch. It is a synchronisation tool that enables one or more threads to await until a series of tasks started by another thread...

4 minutes read.

Difference Between Thread.start() and Thread.run()

In the Java programming language, the multi-threading concept consists of the start() and run() methods. Thread.start(): The thread's execution is initiated by invoking the start() method. The start() method operates two threads...

4 minutes read.

Sylvester Sequence in Java

A Sylvester Sequence is a series of numbers in which each term is the sum of the terms before it plus 1. The sequence's first two terms are 2 and...

3 minutes read.

Java program to count the occurrences of each character

The count of each character is the frequency of the characters. For example, the given String is “Programming”. In the given string, the count of the characters ‘P’ -1, ’r’-2,...

6 minutes read.

Perfect Number in Java

The concept of a perfect number in Java will be defined in this chapter, along with creating Program code that determine whether a specific number is perfect or not. Additionally,...

4 minutes read.

Ordinal Number in Java

What is the Ordinal Number in Java? An object's or person's position or rank can be expressed mathematically using an ordinal number. Depending on the criteria used to establish the positions,...

3 minutes read.

Java this keyword

This Keyword in Java This keyword can be used in many different ways in Java. This is a reference variable in Java that points to the active object. In Java, the...

8 minutes read.

Trim Method in String Java

What is a String? Strings are a bundle of different characters that are normally used in Java programming language. Strings are regarded as objects in the Java programming language. “String” is a...

3 minutes read.

Bottom view of a binary tree in Java

The lowest nodes in their horizontal distance are present and referred to as the bottom view of a binary tree. The horizontal distance between the nodes of a binary tree...

4 minutes read.

StringBuilder in Java

StringBuilder in Java Java StringBuilder class is introduced since JDK 1.5. The StringBuilder class is mainly used to create modifiable or mutable strings. Note that the StringBuilder class is not synchronized....

7 minutes read.

Java Finally Keyword

The final block in Java is used to run essential code, such as connection closure, among other things. Whether an exception is resolved or not, the Java finally block has...

3 minutes read.

java.lang.NumberFormatException for Input String

java.lang.NumberFormatException for Input String The exception java.lang.NumberFormatException for input string occurs when we try to convert a string into a number format. For example, if someone converts the string “Tutorial & Example”...

3 minutes read.

Java String replaceFirst() method

This method replace the first substring with user specified String. Syntax: public String replaceFirst(String Regexp, String Replacement) Parameter: Regexp : Regular Expression Replacement : the String which would replace found expression Return: a string Java String replaceFirst()...

1 minute read.

Best Java IDE

Applications for desktop, workplace, smartphone, and the internet can be created using Java, one of the most popular programming languages. Java will undoubtedly be a popular programming language for so...

5 minutes read.

How to remove special characters from String in Java

Strings in Java are Objects that are supported inside by a burn exhibit. Since exhibits are immutable (cannot develop), Strings are changeless too. A completely new String is made whenever...

5 minutes read.

Java.lang.Exception.NoRunnableMethods

In Programming language, the java lang unexpected no precompiled methods error generally refers to a Junit exception that happens whenever Junit is incapable of locate the precompiled test methods. When...

4 minutes read.

How to Send SMS in Java with Example

Sending SMS messages in Java is a fairly common task, and there are a number of libraries and APIs available to help you do it. One popular option is to...

2 minutes read.