The method copyValueOf()
is used for copying an array of characters to the String
. The point to note here is that this method does not append the content in String, instead it replaces the existing string value with the sequence of characters of array.
It has two variations:
1) static copyValueOf(char[] data)
: It copies the whole array (data) to the string.
2) static String copyValueOf(char[] data, int offset, int count)
: It copies only specified characters to the string using the specified offset and count values. offset is the initial index from where characters needs to be copied and count is a number of characters to copy. For e.g. offset 2 and count 3 would be interpreted as: Only 3 characters of array starting from 2nd index(3rd position as index starts with 0) should be copied to the concerned String.
Example
In this example we have two strings str1 & str2 and an array of chars named data. We are copying the array to the strings using both the variations of method copyValueOf()
.
public class CopyValueOfExample { public static void main(String args[]) { char[] data = {'a','b','c','d','e','f','g','h','i','j','k'}; String str1 = "Text"; String str2 = "String"; //Variation 1:String copyValueOf(char[] data) str1 = str1.copyValueOf(data); System.out.println("str1 after copy: " + str1); //Variation 2:String copyValueOf(char[] data,int offset,int count) str2 = str2.copyValueOf(data, 5, 3 ); System.out.println("str2 after copy: " + str2); } }
Output:
str1 after copy: abcdefghijk str2 after copy: fgh
Leave a Reply