As we know that strings are not arrays so the String class also provides methods to convert a string to an array of characters and vice versa. These include
toCharArray();
getChars();
valueOf();
char [] toCharArray (): This method converts the invoking string to an array of individual characters. For example : The statement,
char[] ch = sl.toCharArray();
will convert the string Welcome which is referenced by sl to an array of characters such that ch [0] contains ‘W’, ch [1] contains ‘e’ and so on.
void getChars(int srcBegin, int srcEnd, chsr[] dest, int destBegin): This method copies a substring of the invoking string from index srcBegin to index srcEnd-1 into a character array dest starting from index destBegin. For example: The statement,
char[] txtArray = new char[3];
sl.getChars(3,6,txtArray,O);
will copy characters from the String object slat index position 3 to 5 (i.e. 6 – 1) inclusive, so txtArray[0] will be ‘c’, txtArray[1] will be ‘0’ and txtArray[2] will be ‘m’.
static String valueOf (char [] ch): This method will covert an array of characters to a string. For example : The statements,
char[] ch = {‘W’, ‘E’, ‘L’, ‘C’, ‘0’, ‘M’, ‘E’};
String str String.valueOf(ch);
will return the string Welcome from a character array ch and store the reference in str. There are several versions of valueOf () method that can be used to convert a character and numeric values to strings with different parameter types including in t, long, float, double and char.
Now let us consider a example to show how these work.
public class ConversionMethods
{
public static void main(String[] args)
{
String s1 = "Welcome" ;
char[] txtArray = new char[3];
char [] ch = s1.toCharArray();
for( int i =0; i<ch.length; i++)
System.out.println("ch["+i+"] = " +ch[i]);
s1.getChars(3,6,txtArray,0);
for( int i=0;i<txtArray.length;i++)
System.out.println("txtArray["+i+"] = "+txtArray[i]);
char[] c = {'W','E','L','C','O','M','E'};
String str = String.valueOf(ch);
System.out.println("str = " + str);
}
}