Java String copyValueOf() Method

Beginner
⏱️ 8 min read
📚 Updated: Jul 2026
🎯 5 Examples
String Methods

What You’ll Learn

The copyValueOf() method is a static factory on the String class. It builds a new String by copying characters from a char[] array—either the whole array or a slice defined by offset and count.

01

char[] to String

Array conversion.

02

Static Method

String.copyValueOf().

03

Two Overloads

Full or partial copy.

04

offset + count

Pick a range.

05

New String

Immutable result.

06

Buffer Data

Files and streams.

Definition and Usage

In Java, String.copyValueOf(char[] data) and String.copyValueOf(char[] data, int offset, int count) create a brand-new String whose characters are copied from the given array. The original array can be changed later without affecting the String, because strings are immutable.

This method is handy when you read characters into a buffer—from a file, network stream, or parser—and need a String representation of all or part of that buffer.

💡
Beginner Tip

Call it on the class, not on a string variable: String.copyValueOf(chars), not myString.copyValueOf(...).

📝 Syntax

The copyValueOf() method has two static overloads in the String class:

java
public static String copyValueOf(char[] data)
public static String copyValueOf(char[] data, int offset, int count)

Parameters

  • data — the source character array. Must not be null.
  • offset — (two-arg form) index in data where copying starts. Must be ≥ 0.
  • count — (two-arg form) number of characters to copy. Must be ≥ 0 and offset + count must not exceed data.length.

Return Value

Returns a new String containing the copied characters.

Exceptions

  • NullPointerException if data is null.
  • IndexOutOfBoundsException if offset or count are negative, or if offset + count > data.length.

⚡ Quick Reference

ExpressionResult
String.copyValueOf(new char[]{'H','i'})"Hi"
String.copyValueOf(chars, 1, 3)3 chars from index 1
String.copyValueOf(new char[0])"" (empty string)
new String(chars)Similar for full array
String.copyValueOf(null)NullPointerException
Full array
String.copyValueOf(data)

Copy every character

Partial range
String.copyValueOf(data, off, len)

Slice of the buffer

Constructor
new String(data)

Full array alternative

Safe bounds
off >= 0 && len >= 0

Avoid IOOBE

Examples Gallery

These programs run in Java 8+. They show copying an entire array, extracting a substring range, handling an empty array, comparing with the constructor, and invalid bounds.

📚 Getting Started

Convert a character array into a String using both overloads.

Example 1 — Copy the Entire Array

Every character in charArray becomes the new string "Hello".

java
public class CopyValueOfExample {
    public static void main(String[] args) {
        char[] charArray = {'H', 'e', 'l', 'l', 'o'};

        String result = String.copyValueOf(charArray);

        System.out.println(result);
    }
}

How It Works

Java walks the array from index 0 to the end and copies each char into a new immutable String object.

Example 2 — Copy a Range (offset and count)

Start at index 1, copy 3 characters — producing "ell" from "Hello".

java
public class PartialCopyDemo {
    public static void main(String[] args) {
        char[] charArray = {'H', 'e', 'l', 'l', 'o'};

        String slice = String.copyValueOf(charArray, 1, 3);

        System.out.println(slice);
    }
}

How It Works

Index 1 is 'e'. Count 3 reads 'e', 'l', 'l'. The first character 'H' and trailing 'o' are skipped.

📈 Practical Patterns

Edge cases, alternatives, and safe usage.

Example 3 — Empty Character Array

An array with zero elements produces an empty string.

java
public class EmptyArrayCopy {
    public static void main(String[] args) {
        char[] empty = new char[0];

        String text = String.copyValueOf(empty);

        System.out.println("Length: " + text.length());
        System.out.println("Is empty? " + text.isEmpty());
    }
}

How It Works

No characters are copied, so the result is "". This is valid and does not throw an exception.

Example 4 — copyValueOf() vs String Constructor

For a full array, String.copyValueOf(chars) and new String(chars) produce the same text.

java
public class CopyVsConstructor {
    public static void main(String[] args) {
        char[] data = {'J', 'a', 'v', 'a'};

        String viaCopy        = String.copyValueOf(data);
        String viaConstructor = new String(data);

        System.out.println("copyValueOf:  " + viaCopy);
        System.out.println("constructor:  " + viaConstructor);
        System.out.println("Equal text?   " + viaCopy.equals(viaConstructor));
    }
}

How It Works

Both create a new String from the array. Prefer the two-argument copyValueOf when you only need part of the buffer; for a full array, either style works.

Example 5 — Invalid offset or count

Requesting characters beyond the array bounds throws IndexOutOfBoundsException.

java
public class BoundsDemo {
    public static void main(String[] args) {
        char[] data = {'A', 'B', 'C'};

        try {
            // offset 1 + count 3 exceeds length 3
            String bad = String.copyValueOf(data, 1, 3);
            System.out.println(bad);
        } catch (IndexOutOfBoundsException ex) {
            System.out.println("Caught: " + ex.getClass().getSimpleName());
        }
    }
}

How It Works

Only two characters exist from index 1 ('B' and 'C'), but count 3 asks for three. Java rejects the invalid range immediately.

🚀 Common Use Cases

  • File or stream buffers — turn a filled char[] read from input into a String.
  • Partial token extraction — copy only the meaningful slice after parsing fixed-width fields.
  • Legacy APIs — integrate with libraries that still expose char[] instead of String.
  • Test data setup — build strings from character arrays in unit tests without string concatenation.
  • Custom parsers — convert a working buffer segment into text once parsing completes.

🧠 How copyValueOf() Works

1

You pass a char array

Optionally specify offset and count for a slice.

Input
2

Bounds are validated

null arrays and out-of-range slices throw exceptions before copying.

Validate
3

Characters are copied

Java allocates a new String and copies the selected characters into it.

Copy
=

New String returned

Immutable text independent of later changes to the source array.

📝 Notes

  • copyValueOf() is static—invoke it as String.copyValueOf(...).
  • The returned String is independent of the source array; mutating the array afterward does not change the string.
  • For a full array, new String(char[]) is an alternative with the same practical result in modern Java.
  • The two-argument form is the clearest way to build a string from part of a buffer without manual copying.
  • An empty array produces "", not null.

⚡ Optimization

copyValueOf() is implemented efficiently inside the JDK and is the right choice for array-to-string conversion. Avoid building strings character by character in a loop when you already hold the data in a char[]. If you repeatedly convert the same unchanged array, store the resulting String in a variable instead of calling copyValueOf() on every iteration.

Conclusion

The copyValueOf() method gives you a clear, static way to turn character arrays into strings. Use the single-argument form for the full buffer and the three-argument form when you need a precise slice.

Remember it is static, copies characters into a new immutable String, and validates array bounds. With those rules in mind, converting buffer data to text becomes straightforward in real programs.

💡 Best Practices

✅ Do

  • Call String.copyValueOf(...) on the class, not an instance
  • Use the two-argument overload when you need only part of a buffer
  • Validate offset and count before calling in custom APIs
  • Prefer copyValueOf over manual char-by-char concatenation
  • Cache the result if the same array slice is converted repeatedly

❌ Don’t

  • Pass a null char array without checking first
  • Assume you can call it on an existing String variable
  • Request more characters than the array contains
  • Confuse count (length to copy) with end index
  • Mutate the source array expecting the String to change

Key Takeaways

Knowledge Unlocked

Five things to remember about copyValueOf()

Use these points whenever you convert char arrays to strings.

5
Core concepts
⚙️ 02

Static Method

String.copyValueOf().

Syntax
✂️ 03

offset + count

Partial copy.

Overload
🔒 04

Immutable Result

Safe from array edits.

Behavior
⚠️ 05

Bounds Matter

IOOBE if invalid.

Edge case

❓ Frequently Asked Questions

copyValueOf() is a static String method that creates a new String by copying characters from a char array. You can copy the entire array or a selected range using offset and count.
It is static. You call it on the String class: String.copyValueOf(charArray). You do not call it on an existing String object.
copyValueOf(char[] data) uses every character in the array. copyValueOf(char[] data, int offset, int count) copies count characters starting at offset inside the array.
Both produce a String from a char array. copyValueOf() reads clearly as "copy these characters into a new String." The String(char[]) constructor is equivalent for a full array; use the two-argument copyValueOf when you need only part of the array.
NullPointerException if the char array is null. IndexOutOfBoundsException if offset or count are negative, or if offset + count exceeds the array length.
Use it when reading char buffers from files, streams, or parsers and you need a String from all or part of the buffer without manual loop-and-append code.

Convert Buffers to Strings with Confidence

Next up: validate suffixes and file extensions with endsWith().

Next: endsWith() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful