Library contents

Java String.copyValueOf

Create a string from a character array or a portion of one.

A simple example

String.copyValueOf

  1. Start with Characters a, b, c
  2. Do this Copy just the middle character
  3. Result b
Starting at b and copying one position leaves a and c outside the result.
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        System.out.println(String.copyValueOf(new char[]{'a', 'b', 'c'}, 1, 1));
    }
}
Output
b

Syntax

Java 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.java

Take 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.

From the programchar[] buffer = "ID482".toCharArray()
Result482
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        char[] buffer = "ID482".toCharArray();
        System.out.println(String.copyValueOf(buffer, 2, 3));
    }
}
Output
482

Starting at offset two and copying three units selects the numeric suffix.

Advertisements

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.

From the programchar[] buffer = "tea".toCharArray()
Resulttea
Main.java
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);
    }
}
Output
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?

GivenNC-17
Worked result17

What to watch for

The last range argument is a count. Check that offset plus count fits the array.

Documentation for String.copyValueOf