How to Convert String to char in Java

Facebooktwitterredditpinterestlinkedinmailby feather

How to Convert String to char in Java

There are two methods to convert String to char are:

  • Using charAt() method
  • Using tocharArray() method

Using charAt() method

This is the method of String class that belongs to java.lang package. It returns the character at the specified index value. The value of the index lies between 0 to length()-1 (where length() is the method of String class which returns the number of character in the string ). The signature of the method is given below:

Example

In the following example, str is a variable of String type that contains “Computer “.  charAt() is a method of String classthat returns the character at the specified index. ch is a variable of type char that stores the returned character. The println statement prints the character return by the method.

Output

If the index value is higher than string length or negative, then it throws IndexOutOfBoundsException. In the above example, string length is 7. If we specify the index value negative or higher, then it throws the IndexOutOfBoundsException.

Let’s see another example that returns each character.

Output

Using charArray() method

The tocharArray() method converts the String into the character array. It is a predefined method of String class that belongs to java.lang package. It returns the character array, which makes the String. If you want to get all character at a time, you can use a loop.

Example

In this example,”moon” is a string which we want to convert into the character array. char[] is an array that stores the array of characters. tocharArray() is a method that converts String to a character array.

In for loop, we have taken a variable i of type int that represents the index value of character. The variable i initialized with 0 because array index starts from 0. The test condition i<ch.length compares the value of i with the size of the array. i++ increments the value of i on each iteration until the test condition become false.

The println statement prints the character and its index value.

Output

Remember

There is a slight difference between length() and length.

  • length() is a method of  the String class that returns the number of characters in the string. The length() method can be used only with strings not with arrays.
  • The length is the property of array that determines the size of array. length can be used only with arrays not with strings.
Facebooktwitterredditpinterestlinkedinmailby feather