- Given String value in java.
- We would like to convert String to char & char array using following methods.
- charAt method of String class returns character of String at specified index.
- toCharArray method of String class converts String to new character array
Example: convert String to char & char array in java
Example : Given inputString = "Java"
//character at specified Index
char at 0 index = 'J'
char at 1 index = 'a'
char at 2 index = 'v'
char at 3 index = 'a'
//Convert String to character array:
Character array would be like = [J, a, v, a]
Java methods of String class to convert String to char & char array
Method Name | Description |
char charAt(int index) | Returns the char value at the specified index. |
char[] toCharArray() | Converts this string to a new character array. |
Program: Convert string to char & character array in java
package org.learn;
import java.util.Arrays;
public class ConvertStringToCharAndArray {
public static void main(String[] args) {
String strValue = "Java";
System.out.println("Input String : " + strValue);
//Convert char to string using Character.toString
System.out.println("Char at zero index : "+ strValue.charAt(0));
System.out.println("Char at 1 index : "+ strValue.charAt(1));
System.out.println("Char at 2 index : "+ strValue.charAt(2));
System.out.println("Char at 3 index : "+ strValue.charAt(3));
System.out.print("Print all characters using loop : ");
//Loop through string & print all characters
for(int index = 0; index < strValue.length(); index++) {
System.out.print(strValue.charAt(index));
}
//Convert String to char array
char chArray[] = strValue.toCharArray();
System.out.println("\nString to Character array :"+
Arrays.toString(chArray));
}
}
Output: convert String to char & character array in java
Input String : Java
Char at zero index : J
Char at 1 index : a
Char at 2 index : v
Char at 3 index : a
Print all characters using loop : Java
String to Character array :[J, a, v, a]