Convert a String to a char in Java

In this post, we will see 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 character present at the first index should be copied.

 

1. String.charAt(int)

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

 

2. String.toCharArray()

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. Code Point

We can also use 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. String.getChars()

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

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz