Convert String to char in Java

To convert String to char in Java we can use the charAt() method of the String class. This method returns the char value at the specified index.

Syntax

public char charAt(int index)

Example

class Test {

  public static void main(String[] args) {

    char ch = "java".charAt(1); // returns char 'a'

    System.out.println("char: " + ch);
  }
}
Output: char: a
 
We can also convert a String to a char array using the toCharArray() method.

Syntax

public char[] toCharArray()

Example

class Test {

  public static void main(String[] args) {

    String str = "hello java";

    char[] charArray = str.toCharArray();

    for (char ch : charArray) {
      System.out.print(ch + ", ");
    }
  }
}
Output: h, e, l, l, o, , j, a, v, a,
 
That was all about how to convert String to char in Java. Proceed to the next lesson.
 
Happy coding!

Leave a Reply

Your email address will not be published.