In Java, String.copyValueOf() builds a new string from a char[]. It is a static method, so you call it on String, not on an instance.
You pass the array, or the array plus offset and count. The array is required. Later edits to the array do not change the string.
Syntax
Call copyValueOf on the String class. Start with this line.
java
String s = String.copyValueOf(data);
Call
What it does
String.copyValueOf(data)
Builds a string from the whole char array.
String.copyValueOf(data, 1, 2)
Builds a string from 2 characters starting at offset 1.
This is the same idea as valueOf(char[]). Call it on String, not on a string instance.
Library declarations
java
public static String copyValueOf(char[] data);
public static String copyValueOf(char[] data, int offset, int count);
Parameters
Parameter
Description
data
Required. The char array to copy from.
offset
Optional. Where to start in the array.
count
Optional. How many characters to take.
Return Value
Return Value
Description
New String
A string made from the chosen characters.
Java Examples
Example 1 — Copy the Full Array
Turn every character into one String.
java
public class CopyValueOfBasic {
public static void main(String[] args) {
char[] data = {'J', 'a', 'v', 'a'};
String s = String.copyValueOf(data);
System.out.println(s);
}
}
Output
Java
How It Works
Build a char array. Four letters spell Java.
Call the static method.String.copyValueOf(data) copies all entries.
Get a new String. Result is "Java".
Print it. Confirms the conversion worked.
Example 2 — Copy a Range
Take only part of a buffer with offset and count.
java
public class CopyValueOfRange {
public static void main(String[] args) {
char[] data = {'C', 'o', 'd', 'e'};
String mid = String.copyValueOf(data, 1, 2);
String last = String.copyValueOf(data, 2, 2);
System.out.println(mid);
System.out.println(last);
}
}
Output
od
de
How It Works
Start at index 1.count 2 copies 'o' and 'd' → "od".
Start at index 2. Next two chars are 'd' and 'e' → "de".
Handy for buffers. You can ignore unused prefix/suffix slots.
Stay in bounds.offset + count must not pass the array length.
Example 3 — Same Result as new String(char[])
Full-array copyValueOf matches the String constructor; pick the style you prefer.
java
public class CopyValueOfVsCtor {
public static void main(String[] args) {
char[] data = {'H', 'i'};
String a = String.copyValueOf(data);
String b = new String(data);
System.out.println(a);
System.out.println(b);
System.out.println(a.equals(b));
}
}
Output
Hi
Hi
true
How It Works
Same source. Both paths read {'H','i'}.
Two construction styles. Static helper vs constructor.