This Java example shows how to convert string to character array (char array) in Java as well as how to convert char array to string in Java.
How to convert string to char array in Java?
Use the toCharArray
method of the String class to convert the string object to char array.
1 |
public char[] toCharArray() |
This method creates a new character array whose length is equal to the length of the string object containing the character sequence.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
package com.javacodeexamples.stringexamples; public class StringToCharArrayExample { public static void main(String[] args) { String str = "I am String object"; //use toCharArray method to convert String to char array char[] charArray = str.toCharArray(); System.out.println("String converted to char array"); //print char array using print method for(char c : charArray){ System.out.print(c); } } } |
Output
1 2 |
String converted to char array I am String object |
How to convert string to Character object array in Java?
There is no direct method to convert a string to a Character object array in Java. Below given are two possible solutions.
a) Using for loop
1 2 3 4 5 6 7 8 9 10 |
String str = "I am String object"; int stringLength = str.length(); Character[] characterArray = new Character[ stringLength ]; for(int i=0; i < stringLength; i++){ characterArray[i] = str.charAt(i); } System.out.println("String converted to Character array"); |
Basically we have created a Character array whose length is equal to the length of the string and populated it one character at a time using the for loop.
b) Using Apache Commons lang library
If you have the Apache Commons lang library, you can use the toObject
method of the ArrayUtils class to convert primitive char array to Character object array as given below.
1 |
static Character[] toObject(char[] charArray) |
This method converts an array of primitive char to array of Character wrapper objects.
1 2 3 4 |
String str = "Convert char array to Character array"; char[] charArray = str.toCharArray(); Character[] characterArray = ArrayUtils.toObject(charArray); |
How to convert a char array to a string?
Use a String constructor that accepts a char array as an argument and returns a string representation of character sequence.
1 |
public String(char[] chars) |
This constructor creates and returns a new string object containing a sequence of characters contained in the char array.
1 2 3 4 5 |
char[] charArray = new char[]{'h', 'e','l','l','o'}; String str = new String(charArray); System.out.println("character array to String: " + str); |
Output
1 |
character array to String: hello |
This example is a part of the Java String tutorial.
Please let me know your views in the comments section below.