Convert String to character array to String
The String class internally uses the character array for storing the characters present in the string. This means that we can convert a String object into character array and also convert a character array to String object.
The code to convert a character array to String is shown below:
public class MyTest{
public static void main(String[] args) {
char[] charArr = new char[] {'a', 'b', 'c'};
String str1 = new String(charArr);
System.out.println("str1 : " + str1);
String str2;
str2 = String.valueOf(charArr);
System.out.println("str2 : " + str2);
}
}
The code to convert a string to character array is shown below:
public class MyTest{
public static void main(String[] args) {
String str1 = "this is a string";
System.out.println(str1.toCharArray());
}
}
The above code will print the hashcode of the array which is returned by the String class's toCharArray method.
No comments:
Post a Comment