Char array and Byte array to String Java

Char array and Byte array to String Java

Sometimes, it is necessary to convert an array of bytes and characters into a string in Java coding. Conversion of array to string is easy in Java, just use String constructors.
Following Example on array to String converts char array and byte array into string form.

ssOutput Screenshot on Standard Console Input Java

char letters[] = { ‘h’, ‘e’, ‘l’, ‘l’, ‘o’ };
String str1 = new String(letters);

The char array letters[] is passed to String constructor. Now the String object std1 prints all the array characters in string form.

byte alphabets[] = { 97, 98, 99, 100, 101 };
String str2 = new String(alphabets);

Similarly with byte array also. Pass the byte array alphabets[] to String constructor. The string object str2 prints all byte array elements as string. But notice here, the bytes are converted into characters implcitly by Java constructor. Observe the screenshot.

The reverse way is converting string to arrays. Example is available at String convert byte array char array in this same Web site.

Leave a Reply

Your email address will not be published. Required fields are marked *