In this article, we will look into the possible ways to convert Java char array to string.
- Passing the char array to the String class constructor
- Using the valueOf() method of String class
- Using the copyValueOf() method of String class
- Using append() method of StringBuilder class
- Manual way
1. Passing the char array to the String class constructor
In the below code we did the following
- We have a charArray which holds the characters ‘J’, ‘A’, ‘V’, ‘A’
- Pass the charArray to the String ‘str’ class constructor
- Finally print the string str
package com.javainterviewpoint; public class CharToString { public static void main(String[] args) { //Character array char[] charArray = new char[]{'J', 'A', 'V', 'A'}; //Create a new String object and pass the char array to the constructor String str = new String(charArray); //Printing the string after conversion System.out.println(str); } }
2. Using the valueOf() method of String class
Just pass the charArray to the valueOf() method of the String class.
package com.javainterviewpoint; public class CharToString { public static void main(String[] args) { //Character array char[] charArray = new char[]{'J', 'A', 'V', 'A'}; //Pass the charArray to valueOf() method String str = String.valueOf(charArray); //Printing the string after conversion System.out.println(str); } }
3. Using the copyValueOf() method of String class
This is similar to valueOf() method, instead of passing the charArray to valueOf() method we will be passing it to charValueOf() method
package com.javainterviewpoint; public class CharToString { public static void main(String[] args) { //Character array char[] charArray = new char[]{'J', 'A', 'V', 'A'}; //Pass the charArray to copyValueOf() method String str = String.copyValueOf(charArray); //Printing the string after conversion System.out.println(str); } }
4. Using append() method of StringBuilder class
This is a less efficient way as it takes more memory
package com.javainterviewpoint; public class CharToString { public static void main(String[] args) { //Character array char[] charArray = new char[]{'J', 'A', 'V', 'A'}; //Pass charArray to append() method StringBuilder sb = new StringBuilder().append(charArray); //Printing the string after conversion System.out.println(sb.toString()); } }
5. Manually way
Manual way this is not a recommended one.
package com.javainterviewpoint; public class CharToString { public static void main(String[] args) { //Character array char[] charArray = new char[]{'J', 'A', 'V', 'A'}; String str=""; //Read the charArray and append it everytime for(char c : charArray) { str = str+c; } System.out.println(str); } }
Leave a Reply