Convert Charater Arrays to String in Java | Example code using String.copyValueOf()

You can convert character arrays to string in two ways .
1. String Class has a method copyValueOf() can be used to create a String object from charater arrays. (i.e. array of type char[])
a) String str=String.copyValueOf(charArray) -> All the characters of array is converted to String
b) String str = String.copyValueOf(charArray, 5, 4) - > Only 4 charactes starting from 5th position , are converted to string.

2. String class supports several constructors . One of the constructor accepts array of characters and string object is created by the initialised array of charaters. String str=new String ('a','e','i','o','u');

The following example code explains how the character arrays are converted to string object using the above two methods.

  

public class CharArrayToString {

public static void main(String[] arg) {
char[] charArray = { 'V', 'o', 'w', 'e', 'l', 's', ':', 'a', 'e', 'i', 'o', 'u' };

System.out.println("Given CharArray\n");
for (char c:charArray) System.out.println(c);

String str = new String(charArray);
System.out.println("After converting to String using Constructor : " + str);

String str1 = String.copyValueOf (charArray);

System.out.println("After converting to String using copyValueOf method : " + str1);

// converting subset of charater arrays to string
System.out.println("\n");
System.out.println("Converting subset of charater arrays to string\n ") ;
String str2 = new String(charArray,0,5);
System.out.println("Using Constructor : " + str2);

String str3 = String.copyValueOf (charArray,7,5);

System.out.println("Using copyValueOf method : " + str3);

}

}

After Running the above program Output :

java CharArrayToString
Given CharArray

V
o
w
e
l
s
:
a
e
i
o
u
After converting to String using Constructor : Vowels:aeiou
After converting to String using copyValueOf method : Vowels:aeiou


Converting subset of charater arrays to string

Using Constructor : Vowel
Using copyValueOf method : aeiou

0 comments:

Post a Comment

 
Copyright 2011 Java Online