Saturday, July 4, 2026
HomeLanguagesJavaJava Guava | Chars.compare() method with Examples

Java Guava | Chars.compare() method with Examples

Chars.compare() method of Guava’s Chars Class is used to compare the two specified char values. These values are passed as the parameter and the result of comparison is found as the difference of 1st value and the 2nd value. Hence it can be positive, zero or negative.

Syntax:

public static int compare(char a, char b)

Parameters: This method accepts two parameters:

  • a: which is the first char object to be compared.
  • b: which is the second char object to be compared.

Return type: This method returns an int value. It returns:

  • 0 if ‘a’ is equal to ‘b’,
  • a positive value ‘a’ is greater than ‘b’,
  • a negative value ‘a’ is lesser than ‘b’

Exceptions: The method does not have any exception.

Example 1:




// Java code to show implementation of
// Guava's Chars.compare() method
import com.google.common.primitives.Chars;
  
class GFG {
    public static void main(String[] args)
    {
        char a = 'c';
        char b = 'c';
  
        // compare method in Char class
        int output = Chars.compare(a, b);
  
        // printing the output
        System.out.println("Comparing " + a
                           + " and " + b + " : "
                           + output);
    }
}


Output:

Comparing c and c : 0

Example 2:




// Java code to show implementation of
// Guava's Chars.compare() method
import com.google.common.primitives.Chars;
  
class GFG {
    public static void main(String[] args)
    {
        char a = 'd';
        char b = 'D';
  
        // compare method in Char class
        int output = Chars.compare(a, b);
  
        // printing the output
        System.out.println("Comparing " + a
                           + " and " + b + " : "
                           + output);
    }
}


Output:

Comparing d and D : 32

Example 3:




// Java code to show implementation of
// Guava's Chars.compare() method
import com.google.common.primitives.Chars;
  
class GFG {
    public static void main(String[] args)
    {
        char a = 'E';
        char b = 'c';
  
        // compare method in Char class
        int output = Chars.compare(a, b);
  
        // printing the output
        System.out.println("Comparing " + a
                           + " and " + b + " : "
                           + output);
    }
}


Output:

Comparing E and c : -30
RELATED ARTICLES

1 COMMENT

Most Popular

Dominic
32519 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6900 POSTS0 COMMENTS
Nicole Veronica
12015 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12110 POSTS0 COMMENTS
Shaida Kate Naidoo
7019 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6976 POSTS0 COMMENTS
Umr Jansen
6967 POSTS0 COMMENTS