This article will discuss Chars class by Guava, which provides static utility methods to work with primitive char values and arrays.

The Chars class is part of the com.google.common.primitives package in Guava, which is a Google core library for Java. This class offers various functionalities such as converting, comparing, concatenating, hashing, sorting, searching, and manipulating char values and arrays. Some of the methods are:

1. Using Chars.asList() method

The Guava Chars.asList() method wraps a primitive char array as a List<Character> object and returns a fixed list that is backed by the array. This is a sample of how the method works:

Download Code

2. Using Chars.toArray() method

We can use Guava’s Chars.toArray() method to convert a List (or Set) of Character into an array of primitive chars. The list’s values are copied into a new char array, preserving their order. This is a sample of how the method works:

Download Code

3. Using Chars.concat() method

The Guava Chars.concat() method takes the multiple char arrays that need to be joined as parameters and combines values from specified arrays into a single char array and returns it. This is a sample of how the method works:

Download Code

4. Using Chars.contains() method

The Guava Chars.contains() method determines if the specified character is present in the primitive char array or not. This is a sample of how the method works:

Download Code

5. Using Chars.indexOf() and Chars.lastIndexOf() method

These methods allow us to search for a character in a char array. The Chars.indexOf() method returns the index of the first appearance of the given character in a char array and returns -1 if the character is not found in the array. The Chars.lastIndexOf() method works similarly, but it returns the index of the last appearance instead. Here is an example of using the Chars.indexOf() method:

Download Code

6. Using Chars.join() method

The Guava Chars.join() method takes a separator and a char array as the parameters, in that order, and returns a string containing characters from the array, separated by a separator. This is a sample of how the method works:

Download Code

7. Using Chars.min() and Chars.max() method

The Guava Chars.min() method returns the minimum char value present in a char array, and the Chars.max() method returns the maximum char value. The following is a demonstration of the methods:

Download Code

That’s all about Chars class by Guava in Java.