The String.copyValueOf() method returns a new String representing the character sequence in a specified char[] array.
Static Factory & Defensive Copying: Creates an independent copy of array elements, ensuring future array edits cannot alter the string. Identical to String.valueOf(char[]). To convert a string back into an array, see toCharArray() or copy slices with getChars().
Java provides two static methods in java.lang.String to construct strings from character arrays:
// 2 Overloaded static signatures in java.lang.String
public static String copyValueOf(char[] data)
public static String copyValueOf(char[] data, int offset, int count)
| Signature | Parameters | Description & Operational Rule |
|---|---|---|
copyValueOf(char[] data) |
data (char array) |
Converts all elements of the character array into a new String. |
copyValueOf(char[] data, int offset, int count) |
data, offset, count |
Copies count characters starting at index offset from the array. |
Converting complete arrays or targeting specific slices using offset coordinates:
char[] chars = {'p', 'l', 'u', 's', '2', 'n', 'e', 't'};
String full = String.copyValueOf(chars);
System.out.println("Full copy: " + full); // plus2net
String first = String.copyValueOf(chars, 0, 4);
System.out.println("Offset 0, 4: " + first); // plus
String last = String.copyValueOf(chars, 5, 3);
System.out.println("Offset 5, 3: " + last); // netTerminal Output:
Full copy: plus2net
Offset 0, 4: plus
Offset 5, 3: net
Because arrays are mutable but strings are immutable, copyValueOf() creates a defensive clone of the underlying characters:
char[] buffer = {'J', 'a', 'v', 'a'};
String str = String.copyValueOf(buffer);
System.out.println("Before edit: " + str); // Java
// Modifying the char array DOES NOT affect the String!
buffer[0] = 'L';
System.out.println("After edit: " + str); // Java
System.out.println("Array value: " + new String(buffer)); // LavaTerminal Output:
Before edit: Java
After edit: Java
Array value: Lava
Comparing techniques for creating strings from character arrays:
| Technique | Implementation | Standard Usage |
|---|---|---|
String.copyValueOf(chars) |
Calls new String(data, 0, data.length) |
Legacy method retained for backward compatibility. |
String.valueOf(chars) |
Calls new String(data, 0, data.length) |
Modern preference: Uniform naming across types. |
new String(chars) |
Direct constructor invocation | Allocates fresh string on heap. |
copyValueOf() is a static method. Calling it on an existing instance variable compiles but triggers IDE warnings:
// ANTI-PATTERN: Calling static method on an instance variable
String dummy = "";
String s1 = dummy.copyValueOf(new char[]{'A', 'B'}); // Warning!
// RECOMMENDED: Call statically on String class
String s2 = String.copyValueOf(new char[]{'A', 'B'});
System.out.println("Result: " + s2);Terminal Output:
Result: AB
Requires non-negative offset, non-negative count, and offset + count <= data.length:
char[] letters = {'a', 'b', 'c', 'd'};
try {
String.copyValueOf(letters, -1, 2);
} catch (IndexOutOfBoundsException e) {
System.out.println("Caught: negative offset!");
}
try {
String.copyValueOf(letters, 2, 5);
} catch (IndexOutOfBoundsException e) {
System.out.println("Caught: offset + count exceeds length!");
}Terminal Output:
Caught: negative offset!
Caught: offset + count exceeds length!
Masking sensitive user tokens in memory before converting them to audit strings:
public class PasswordMasker {
public static String maskData(char[] input) {
if (input == null) return "";
if (input.length <= 2) return String.copyValueOf(input);
char[] masked = new char[input.length];
masked[0] = input[0];
for (int i = 1; i < input.length - 1; i++) {
masked[i] = '*';
}
masked[input.length - 1] = input[input.length - 1];
return String.copyValueOf(masked);
}
public static void main(String[] args) {
char[] token = {'S', 'e', 'c', 'r', 'e', 't', '9', '9'};
System.out.println("Masked: " + maskData(token)); // S******9
}
}Terminal Output:
Masked: S******9
Extracting fixed-width message fields from character stream buffers using offset coordinates:
public class FixedPacketParser {
public static void parseHeader(char[] raw) {
String protocol = String.copyValueOf(raw, 0, 3);
String msgType = String.copyValueOf(raw, 3, 4);
System.out.println("Protocol: " + protocol);
System.out.println("Type: " + msgType);
}
public static void main(String[] args) {
char[] packet = {'T', 'C', 'P', 'I', 'N', 'I', 'T', '1', '0', '0'};
parseHeader(packet);
}
}Terminal Output:
Protocol: TCP
Type: INIT
Unlike substring(beginIndex, endIndex), the third parameter of copyValueOf(data, offset, count) is the length (number of characters), not the end index. Passing an end index causes bounds errors.
Passing null as the character array throws an immediate NullPointerException. Guard array references before calling copyValueOf().
You can compile and run this complete verification class locally in any Java IDE or environment:
public class StringCopyValueOfFullDemo {
public static void main(String[] args) {
char[] source = {'w', 'e', 'l', 'c', 'o', 'm', 'e'};
String all = String.copyValueOf(source);
if (all.equals("welcome")) {
System.out.println("Check 1 Passed: Char array converted to String.");
}
String slice = String.copyValueOf(source, 3, 4);
if (slice.equals("come")) {
System.out.println("Check 2 Passed: Subarray slice converted accurately.");
}
if (String.copyValueOf(source).equals(String.valueOf(source))) {
System.out.println("Check 3 Passed: copyValueOf exactly matches valueOf.");
}
System.out.println("All String.copyValueOf() unit verification checks passed!");
}
}Terminal Output:
Check 1 Passed: Char array converted to String.
Check 2 Passed: Subarray slice converted accurately.
Check 3 Passed: copyValueOf exactly matches valueOf.
All String.copyValueOf() unit verification checks passed!
No. In standard Java, copyValueOf() simply redirects to valueOf(char[]). Both perform a defensive array copy.
copyValueOf() was introduced in Java 1.0 before method overloading was widely standardized across the library. It is preserved for backwards compatibility.
Yes. Calling String.copyValueOf(new char[0]) returns an empty string "" with length() equal to 0.
Use str.toCharArray() to obtain a fresh character array copy of the string's content.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.