Thursday, January 30, 2025
HomeProgrammingJava Convert String to Char

Java Convert String to Char

In Java, you can convert a String to a char in multiple ways. If you need a single character from a String, use the charAt(index) method:

java
String str = "Hello";
char ch = str.charAt(0); // 'H'

For converting an entire String into a char array, use the toCharArray() method:

java
char[] charArray = str.toCharArray();

Alternatively, using getChars() allows copying specific characters into an existing array:

java
char[] dest = new char[3];
str.getChars(0, 3, dest, 0); // ['H', 'e', 'l']

Ensure the string isn’t empty to prevent exceptions.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x