Java copyValueOf() Method

Java String类Java String Class


copyValueOf(char[] data) in Java is a static method of the String class. It copies all characters from the specified character array into a new character array and returns a new string. This method is very similar to the valueOf(char[] data) method in the String class, but it returns a new character array rather than creating a new string object using the characters from the input array.

The copyValueOf(char[] data) method has two overloaded forms. One of them allows you to specify the starting position in the input array from which to copy and the number of characters to copy:

  • public static String copyValueOf(char[] data):Returns a string representing the character sequence in the specified array.

  • public static String copyValueOf(char[] data, int offset, int count):Returns a string representing the character sequence in the specified array.

Syntax

public static String copyValueOf(char[] data)

或

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

Parameters

  • data-- the character array.

  • offset-- the initial offset of the subarray.

  • count-- the length of the subarray.

Return Value

Returns a string representing the character sequence in the specified array.

Example

Example

public class Test { public static void main(String args[]) { char[] Str1 = {'h', 'e', 'l', 'l', 'o', ' ', 'r', 'u', 'n', 'o', 'o', 'b'}; String Str2 = ""; Str2 = Str2.copyValueOf( Str1 ); System.out.println("Output:" + Str2); Str2 = Str2.copyValueOf( Str1, 2, 6 ); System.out.println("Output:" + Str2); } }

Str2.copyValueOf( Str1 );Use the entire input character array to create a new string object.

Str2.copyValueOf( Str1, 2, 6 );Starting from the 3rd character of the input character array (i.e., offset 2), copy 6 characters and create a new string object.

Note:offsetandcountThe parameter values must not exceed the bounds of the input character array, otherwise anArrayIndexOutOfBoundsExceptionexception will be thrown.

The output of the above program is:

返回结果:hello example
返回结果:llo ru

Java String类Java String Class

Other Extensions