YouTip LogoYouTip

Java String Copyvalueof

# Java copyValueOf() Method [![Image 3: Java String Class](#)Java String Class](#) * * * The `copyValueOf(char[] data)` method 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 instead of creating a new string object using the characters from the input array. The `copyValueOf(char[] data)` method has two overloaded forms, one of which allows you to specify the starting position in the input array to copy from 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) or 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("Return result:" + Str2); Str2 = Str2.copyValueOf(Str1, 2, 6); System.out.println("Return result:" + Str2); }} `Str2.copyValueOf( Str1 );` uses the entire input character array to create a new string object. `Str2.copyValueOf( Str1, 2, 6 );` copies 6 characters starting from the 3rd character (i.e., offset 2) of the input character array and creates a new string object. **Note:** The values of the **offset** and **count** parameters must not exceed the bounds of the input character array, otherwise an **ArrayIndexOutOfBoundsException** will be thrown. The output of the above program is: Return result:hello tutorial Return result:llo ru * * Java String Class](#)
← Java String EqualsJava String Concat β†’