Java String.copyValueOf
Create a string from a character array or a portion of one.
A simple example
String.copyValueOf
- Start with Characters a, b, c
- Do this Copy just the middle character
- Result b
class Main {
public static void main(String[] args) throws Exception {
System.out.println(String.copyValueOf(new char[]{'a', 'b', 'c'}, 1, 1));
}
}
b
Syntax
public static String copyValueOf(char[] data, int offset, int count)
JDK 21 method signatures (2)
public static String copyValueOf(char[] data, int offset, int count)
public static String copyValueOf(char[] data)Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaTake the serial number from a scanner buffer
A scanner returns a compound code, but the printed field needs only its numeric or trailing portion. Use the input boundaries and destination capacity to copy the intended range without including the prefix.
class Main {
public static void main(String[] args) throws Exception {
char[] buffer = "ID482".toCharArray();
System.out.println(String.copyValueOf(buffer, 2, 3));
}
}
482
Starting at offset two and copying three units selects the numeric suffix.
Keep a note after the input buffer changes
A scanner reuses its input buffer for the next item. Save the current text before that buffer changes so the label or note already accepted by the application keeps its original contents.
class Main {
public static void main(String[] args) throws Exception {
char[] buffer = "tea".toCharArray();
String saved = String.copyValueOf(buffer);
buffer[0] = 'p';
System.out.println(saved);
}
}
tea
The saved String is independent of later array edits.
Read a parcel sorting code
The depot scans a parcel marked NC-17. Copy the last two characters into a clean buffer for a numeric display. What does the copied field contain?
What to watch for
The last range argument is a count. Check that offset plus count fits the array.