Java.lang.String.copyValueOf() in Java
Last Updated :
28 Aug, 2017
The copyValueOf() primarily copies the content of a character array into the string. Two variants of this function are available and both are discussed in this article.
Implementation 1 :
Syntax:
public static String copyValueOf(char[] ch)
Parameters:
ch : The character array.
Return Value :
This function returns the string with the contents of character array copied
public class Copy1 {
public static void main(String args[]) {
char [] ch = { 'A' , 's' , 't' , 'h' , 'a' , ' ' , 'T' , 'y' , 'a' , 'g' , 'i' };
String ch2 = "" ;
ch2 = ch2.copyValueOf( ch );
System.out.println( "The new copied string is : " + ch2);
}
}
|
Output:
The new copied string is : Astha Tyagi
In the second implementation, the subarray can also be extracted instead of whole array.
Implementation 2 :
Syntax:
public static String copyValueOf(char[] ch, int index, int num)
Parameters:
ch : The character array.
index : The starting position of array from which copy is to start.
num : Number of elements that has to be copied.
Return Value :
This function returns the string with the contents of character array copied
public class Copy2 {
public static void main(String args[]) {
char [] ch = { 'A' , 's' , 't' , 'h' , 'a' , ' ' , 'T' , 'y' , 'a' , 'g' , 'i' };
String ch2 = "" ;
ch2 = ch2.copyValueOf( ch , 0 , 5 );
System.out.println( "The new copied string is : " + ch2);
}
}
|
Output :
The new copied string is : Astha
Possible application : This function can be used to general copy or extract only prefix or suffix from the string using implementation 2. One possible example can be extracting only the amount from the given “Rs 1000” type of strings which deal with denominations.
public class Appli2 {
public static void main(String args[]) {
char [] ch = { 'R' , 's' , ' ' , '1' , '0' , '2' , '4' };
System.out.print( "The original array is : " );
for ( int i= 0 ; i< ch.length ; i++)
System.out.print(ch[i]);
System.out.print( "\n" );
String ch2 = "" ;
ch2 = ch2.copyValueOf( ch , 3 , 4 );
System.out.println( "The new string is : " + ch2);
}
}
|
Output :
The original array is : Rs 1024
The new string is : 1024
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...