STRING STATIC METHODS
Java String copyValueOf() method
String.copyValueOf() copies the characters of a char array into a new String. You can copy the entire array or just a selected part.
Why is this a static method?
The method is called through the class name, String, because it needs no existing string object:
String tekstas = String.copyValueOf(raides);
String on the left is the return type. The second String before the dot is the class that owns the static method. There is no need to write tekstas.copyValueOf(...) .
Copying an entire char array
char[] raides = {'L', 'a', 'b', 'a', 's'};
String tekstas = String.copyValueOf(raides);
System.out.println(tekstas);Labas
char[]array stores five separate characters.String.copyValueOf(raides)reads every array element.- The characters are copied in order into a new
String. println()displays the complete text Labas.
Two method variants
| Syntax | Purpose |
|---|---|
copyValueOf(char[] data) | Copies every character in the array. |
copyValueOf(char[] data, int offset, int count) | Copies count characters, starting at index offset. |
Both variants return a new String object. They behave like the corresponding String.valueOf(char[]) variants.
Copying only a selected part
char[] uzrasas = {'P', 'i', 'e', 't', 'ū', 's', ':', ' ', '1', '2'};
String zodis = String.copyValueOf(uzrasas, 0, 6);
System.out.println(zodis);Pietūs
- The array contains the full text Pietūs: 12.
offsetvalue0means copying starts at the first character.countvalue6specifies that six characters should be copied.- The colon, space and digits remain outside the selected range.
offset is not the end index
char[] tekstas = {'A', 'B', 'C', 'D', 'E'};
String dalis = String.copyValueOf(tekstas, 1, 3);
System.out.println(dalis);BCD
The number 1 is the starting index, so the first character copied is B. The number 3 is the character count, not an end index, so the copied characters are B, C and D.
The created String is independent of the array
char[] raides = {'k', 'a', 'v', 'a'};
String zodis = String.copyValueOf(raides);
raides[0] = 's';
System.out.println(raides);
System.out.println(zodis);sava
kava
- The array initially forms the word kava.
copyValueOf()copies the characters into a newString.- Later, the first array character changes from
ktos. - The array becomes sava, but the previously created immutable
Stringremains kava.
Common mistakes
- Passing
nullinstead of an array causes aNullPointerException. - A negative
offsetorcountis invalid. - If
offset + countexceeds the array bounds, it causes anIndexOutOfBoundsException. - The method accepts a
char[], notString[]or another array type.
When should you use copyValueOf()?
It is useful when text arrives as a mutable char array and you want an independent, immutable String. Everyday code more often uses String.valueOf(char[]) or the constructor new String(char[]); copyValueOf() expresses the same clear copying intention.