Convert Character Array to String Example in Java
On this page (11sections)
Introduction
Convert Character Array to String is a classic Java console program that demonstrates the concept with complete source code and sample output. Strings are immutable objects in Java; the examples show comparison, searching and transformation.
This tutorial walks through the program line by line, explains how the logic works, and highlights best practices you can apply in your own code.
Aim
To convert a character array to string. This can be achieved by two methods.
Procedure
- By initializing a new instance of string using character array like ‘new String(character_array)’
- By using a default method in String package like ‘String.valueOf(character_array)‘
Syntax
new String(character_array)
(OR)
String.valueOf(character_array)
Example Program
public class CharacterArrayToString {
public static void main(String[] args) {
char[] array = new char[]{'L','I','T','T','L','E','D','R','O','P','S'};
System.out.println("Converting character array to string");
String methodOne = new String(array);
System.out.println("Result by method 1 : "+methodOne);
String methodTwo = String.valueOf(array);
System.out.println("Result by method 2 : "+methodTwo);
}
}
Sample Output
Converting character array to string
Result by method 1 : LITTLEDROPS
Result by method 2 : LITTLEDROPS
When to use
Use string manipulation when cleaning user input, parsing text files or formatting messages.
How it works
-
Execution begins in the
mainmethod — the JVM calls this method when you run the class. -
char[] array = new char[]{'L','I','T','T','L','E','D','R','O','P','S'};updates a variable used in the calculation or output. -
A
println/printcall writes text to the console — part of the sample output below. -
String methodOne = new String(array);updates a variable used in the calculation or output. -
A
println/printcall writes text to the console — part of the sample output below. -
String methodTwo = String.valueOf(array);updates a variable used in the calculation or output. -
A
println/printcall writes text to the console — part of the sample output below. -
Compare your console output with the sample output for Convert Character Array to String to confirm the program behaves correctly.
Best Practices
- Use meaningful variable and class names that describe their purpose.
- Compile and run the program locally — modify values to see how output changes.
- Read compiler errors carefully; they usually point to the exact line to fix.
Common Mistakes
- Copying code without understanding each line — practice by changing one statement at a time.
- Mismatching the public class name and the
.javafilename. - Forgetting semicolons at the end of statements.