- How to convert String to char in Java? Example
- String to char using toCharArray()
- String to char using charAt(index)
- Ways to convert String to Character[] Arrays :
- 2. Iterate through String and assign characters to char[] Arrays :
- Method signature:
- ConvertStringIntoCharArrayUsingCharAtMethod.java
- Output:
- 3. Direct assigning to Character[] array using charAt(index) method :
- Method signature:
- ConvertStringIntoCharacterArrayUsingCharAtMethod.java
- Output:
- 4. Using Java 1.8 Stream :
- Method signature:
- ConvertStringIntoCharacterArrayUsingJava8.java
- Output:
- Related Articles:
- References:
- How to Convert String to Char in Java
- Converting String to char in Java
- Method 1 to Convert String to Char in Java: Using charAt() Method
- Example 1 of Converting String to Char in Java using charAt() method
- Example 2 of Converting String to Char in Java using charAt() method
- Method 2 to Convert String to Char in Java: Using toCharArray() Method
- Example to Convert String to char in Java
- Frequently Asked Questions (FAQs)
How to convert String to char in Java? Example
Hello Java Programmers, earlier, we have seen how to convert a character to String in Java and today we’ll learn opposite i.e. converting String to a character. Suppose, you have a String with value «s» , how do you convert that to a char ‘s’ in Java (FYI, string literal are quoted inside double quotes in Java, like «c» and character literals are quoted inside single quotes e.g. ‘c’ in J)? Well, if you know, Java String is made of a character array and java.lang.String class provides a method toCharArray() to retrieve that character array.
If your String contains just one character then, the only element in character array is what you are looking after. Though that’s not the only way to convert a String to char in Java.
You can also use charAt(index) method to get a char from String at a given index. Since String index starts from 0, «s».charAt(0) will return ‘s’, which is even easier than earlier approach.
Let’s see examples of both of these approaches to convert String to char in Java.
String to char using toCharArray()
The toCharArray() method returns the character array which makes the String. So, if you have just a single character as String like «a» then the toCharArray() will return a character array with just one element e.g. array with length 1, and the first character would be the equivalent character for the String. For example, here is the code to convert «a» to character ‘a’ in Java:
String given = "a"; char[] chars = given.toCharArray(); char result = chars[0];
You can print both given String and character to see if they are same or not. Here is the output when I printed them into the console on my Eclipse IDE:
System.out.println("given string: " + given); System.out.println("result character: " + result); Output: given string: a result character: a
Btw, if you don’t know System.out.println() method is overloaded and one version takes String while another takes a character, here because we are concatenating String, the same method is called twice. See Complete Java Masterclass from Udemy to learn more about overloading and overriding in Java.
String to char using charAt(index)
Whatever we have done in the previous example, can also be done by using the charAt(int index) method.
If you look closely, in the last example, we first get the character array and then retrieve the char from the first index because we knew that our String just got one character.
Instead of doing all this you could have just called the charAt(int index) method.
This method does same, i.e. return the character from the character array which backs the String. For example, if you have a String with just one character e.g. «b» then the following code will convert this into a character ‘b’:
String given = «b»;
char b = given.charAt(0);
This code will return the character from the first index, which is ‘b’, hence we have successfully converted string «b» to character ‘b’ in Java. You can further see these free Java Online Courses for Beginners to learn more about String and character literals in Java.
Here is the screenshot of complete Java program and its output for your reference:
That’s all about how to convert String to char in Java. This is one of the fundamental things which every Java developers should be aware of. You can solve many coding problems if you know these basic techniques because most of the String based coding problems are nothing but an array-based problems, once you know how to convert a String to a character array.
Ways to convert String to Character[] Arrays :
2. Iterate through String and assign characters to char[] Arrays :
Method signature:
public char charAt(int index);
ConvertStringIntoCharArrayUsingCharAtMethod.java
package in.bench.resources.string.to.character.array.conversion; import java.util.Arrays; public class ConvertStringIntoCharArrayUsingCharAtMethod < public static void main(String[] args) < // 1. test String String str = "BenchResources"; System.out.println("Original String :- \n" + str); // 2. create primitive char[] array of string length char[] chArray = new char[str.length()]; // 3. iterate through char[] array using for-each loop for(int index = 0; index < str.length(); index++) < // 3.1 add each char to char[] array using index-position chArray[index] = str.charAt(index); >// 4. print to console System.out.print("\nString to char[] Arrays :- \n" + Arrays.toString(chArray)); > >
Output:
Original String :- BenchResources String to char[] Arrays :- [B, e, n, c, h, R, e, s, o, u, r, c, e, s]
3. Direct assigning to Character[] array using charAt(index) method :
Method signature:
public char charAt(int index);
ConvertStringIntoCharacterArrayUsingCharAtMethod.java
package in.bench.resources.string.to.character.array.conversion; import java.util.Arrays; public class ConvertStringIntoCharacterArrayUsingCharAtMethod < public static void main(String[] args) < // 1. test String String str = "BenchResources"; System.out.println("Original String :- \n" + str); // 2. Create: wrapper-type Character[] array of string length Character[] chArray = new Character[str.length()]; // 3. Add: iterate through char[] array using for-each loop for(int index = 0; index < str.length(); index++) < // 3.1 add each char to char[] array using index-position chArray[index] = str.charAt(index); >// 4. print to console System.out.print("\nString to char[] Arrays :- \n" + Arrays.toString(chArray)); > >
Output:
Original String :- BenchResources String to char[] Arrays :- [B, e, n, c, h, R, e, s, o, u, r, c, e, s]
4. Using Java 1.8 Stream :
- This is very easiest one among various alternatives discussed above
- Get input stream and map the objects to char values
- And then finally invoke toArray() method passing new Character object
Method signature:
Character[] chArray = str.chars() .mapToObj(ch -> (char)ch) .toArray(Character[]::new);
ConvertStringIntoCharacterArrayUsingJava8.java
package in.bench.resources.string.to.character.array.conversion; import java.util.Arrays; public class ConvertStringIntoCharacterArrayUsingJava8 < public static void main(String[] args) < // 1. test String String str = "BenchResources"; System.out.println("Original String :- \n" + str); // 2. convert String to char[] Arrays using Java 8 Stream Character[] chArray = str.chars() .mapToObj(ch ->(char)ch) .toArray(Character[]::new); // 3. print to console System.out.print("\nString to char[] Arrays :- \n" + Arrays.toString(chArray)); > >
Output:
Original String :- BenchResources String to char[] Arrays :- [B, e, n, c, h, R, e, s, o, u, r, c, e, s]
Hope, you found this article very helpful. If you have any suggestion or want to contribute any other way or tricky situation you faced during Interview hours, then share with us. We will include that code here.
Related Articles:
- Java – String to int conversion – 3 ways
- Java – Integer to String conversion – 6 ways
- Java – String to float conversion – 3 ways
- Java – Float to String conversion – 6 ways
- Java – String to double conversion – 3 ways
- Java – Double to String conversion – 6 ways
- Java – String to long conversion – 3 ways
- Java – Long to String conversion – 6 ways
- Java – String to boolean conversion – 3 ways
- Java – Boolean to String conversion – 6 ways
- Java – String to char conversion
- Java – Character to String conversion – 6 ways
- Java – String to char[] array conversion – 4 ways
- Java – Character[] array to String conversion – 5 ways
- Java – String to byte conversion – 3 ways
- Java – Byte to String conversion – 5 ways
- Java – String to byte[] array conversion
- Java – Byte[] array to String conversion
- Java – String to short conversion – 3 ways
- Java – Short to String conversion – 5 ways
- Java – StringBuffer to String conversion and vice-versa
- Java – StringBuilder to String conversion and vice-versa
- Java – String to Date conversion
- Java – Date to String conversion
References:
- https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
- https://docs.oracle.com/javase/tutorial/java/data/numberclasses.html
- https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html
- https://docs.oracle.com/javase/tutorial/java/data/converting.html
- https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html
- https://docs.oracle.com/javase/8/docs/api/java/lang/Character.html
- https://docs.oracle.com/javase/tutorial/java/data/strings.html
- https://docs.oracle.com/javase/8/docs/api/java/lang/String.html
- https://docs.oracle.com/javase/8/docs/api/java/lang/class-use/String.html
- https://docs.oracle.com/javase/tutorial/essential/concurrency/immutable.html
- https://docs.oracle.com/javase/tutorial/essential/concurrency/imstrat.html
Happy Coding !!
Happy Learning !!
How to Convert String to Char in Java
In Java, String and char are two different data types, and sometimes we need to convert Strings to char or char to String. Converting String to char involves extracting individual characters from the string, which can be done in multiple ways.
Converting String to char in Java
We can easily convert String to char in Java by using the built-in Functions. The String and char in Java are defined as:
- char: char is a primitive data type in Java that is used to represent a single character.
- String: A String in Java is an object which is used to store a sequence of characters.
We can convert String to char in Java by using the following two methods.
Let’s discuss both of these in detail.
Method 1 to Convert String to Char in Java: Using charAt() Method
The String Class in Java contains the “charAt()” method. This method is used to return the character at a particular location in a string. To convert a string to a char in Java, we can extract the first character of the string using the charAt() method as shown in the example given below.
Example 1 of Converting String to Char in Java using charAt() method
This example uses the charAt() method to convert the String to char in Java.
The character at first index is P
Explanation:
In the above example, we declared a String str and initialized it with the value “PrepBytes”. Then, we extracted the first character i.e., ‘P’ by using the charAt() method and printed it on the output screen.
Example 2 of Converting String to Char in Java using charAt() method
This example will convert the entire String into characters with the help of for loop and the charAt() method.
The character at index 0 is P The character at index 1 is r The character at index 2 is e The character at index 3 is p The character at index 4 is B The character at index 5 is y The character at index 6 is t The character at index 7 is e The character at index 8 is s
Explanation:
In the above code, we have first declared a string and initialized it with “PrepBytes”. Next, we used a for loop to traverse the entire string and within the for loop to extract the character one by one and printed each character along with its position on the output screen.
Method 2 to Convert String to Char in Java: Using toCharArray() Method
We can also convert the entire string in Java into a Character Array with the help of toCharArray() method. This method is also defined in the String class in Java.
Let us learn how to use this method in Java Code for converting the entire string into an array of characters with the help of the following example.
Example to Convert String to char in Java
The following code illustrates the usage of the toCharArray() method in Java.
The Character is P The Character is r The Character is e The Character is p The Character is B The Character is y The Character is t The Character is e The Character is s
Explanation:
In this code, we have declared a string “PrepBytes” and then used the toCharArray() method to convert the string into a character array. The toCharArray() method returns a character array that is stored with the name “ch”. Finally, we printed all the elements of the character array with the help of a for-each loop.
Conclusion
In this article, we have learned How we can convert String to char in Java with the help of charAt() and toCharArray() methods. We have also discussed examples for a better understanding of both methods. The charAt() method extracts a character at a specified index whereas the toCharArray() method converts the entire string into the Character Array. Depending on the requirements, we can use any of the two methods to convert String to char in Java.
Frequently Asked Questions (FAQs)
Some Frequently Asked Questions related to “String to char in Java” are listed below.
Ques 1. What is the return type of charAt() method?
Ans. The return type of the charAt() method is char.
Ques 2. Can I use the charAt() method to convert a String with multiple characters to a char?
Ans. No, you cannot use the charAt() method to convert a String with multiple characters to a char. The charAt() method only returns a single character. To convert we need to run a for loop to extract each character one by one.
Ques 3. What is the return type of toCharArray() method in Java?
Ans. The return type of the toCharArray() method is char[].
Ques 4. Can I use the substring() method to convert a String to a char?
Ans. No, you cannot use the substring() method to convert a String to a char. The substring() method returns a String, not a char.
Ques 5. How can I convert a String to a char using the valueOf() method?
Ans. You can convert a String to a char using the valueOf() method of the Character class. The valueOf() method returns a Character object that represents the specified char value.