Char array Byte array to String

Very often, as code demands, the array elements may be required to convert into string, especially, char arrays and byte arrays. For conversion, the string constructors and methods like copyValueOf() method is used.

Following program illustrates the Char array Byte array to String.

public class StringArrayManipulations
  public static void main(String args[])
    char letters[] = { 'A', 'B', 'C', 'D', 'E' };
    String str1 = new String(letters);

    byte numbers[] = { 97, 98, 99, 100, 101, 102, 103 };
    String str2 = new String(numbers);
 		        	// another style
    String str3 = String.copyValueOf(letters);

Char array Byte array to String
Output screen of of Char array Byte array to String

It is simple to convert with the overloaded constructors of String class. The string class constructor takes a char array and byte array as parameters and straightaway converts them into strings. The same technique is used in the above code. Alternatively, the static method of String class copyValue() method can be used.

Following are another two String constructors that take a few elements of the array and convert into string (in the program, all the elements are converted).

String(char[] value, int offset, int count)
String(byte[] bytes, int offset, int length)

Following method is also overloaded that converts a few elements into array (in the program, all the elements are converted).

copyValueOf(char[] data, int offset, int count)

The other way, "conversion of strings to char array and byte array" is also possible.

All Array Operations at a Glance

Two questions for you?

1. Why Java introduced StringBuilder with the same functionality (usage) of StringBuffer?
2. Why split() method was introduced when Java has already StringTokenizer?Ans: StringTokenizer comes with JDK1.0 version where as split() method comes with JDK1.4 version. StringTokenizer beongs to java.util package and split() is defined in String class of java.lang package. One major difference is, split() supports regular expressions but StringTokenizer does not. If tokens (independent words) are required in an array form for easy retrieval and operation, split() is preferred. No operations on elements and only retrieval, StringTokenizer is preferred. It is jsut only coding requirements.

Ten questions for you, perhaps you are very much interested?

2 thoughts on “Char array Byte array to String”

Leave a Comment

Your email address will not be published.