This post will discuss how to convert a string containing exactly one character to its equivalent primitive char value in Java. If the string contains more than one character, the solution should copy the character present at the first index.

1. Using String.charAt() method

The idea is to call the charAt(int) method on the specified string to retrieve the character value present at the first index. This is a standard approach to convert a string to a char in Java.

2. Using String.toCharArray() method

Another approach is to convert the string into a character array by using String.toCharArray() and simply return the element present at the first index.

 
In Java 8 we can do like,

 
We can save some time (and memory) if we only need to print the character:

3. Using String.codePointAt() method

We can also use the String.codePointAt() method that returns the code point value of the character present at the specified index.

 
We can also use String.codePointBefore() method, which is similar to String.codePointAt() method, except it returns the code point value of the character present before the specified index.

4. Using String.getChars() method

Here, the idea is to construct an empty char array of size 1 and fill it with the first character of the string using the String.getChars() method.

That’s all about converting a String to a char in Java.