String convert byte array char array

String convert byte array char array

Summary: Many a times it is required to convert the string characters into a char array or byte array; of course, very often, the reverse is also required. Discussed at length in this tutorial "String convert byte array char array".

Program converting strings to char array and byte array

Methods toCharArray() and getBytes() of String class are used.

public class StringToArray
 public static void main(String args[])
   String str1 = "ABCDEF";
                                                          // string to char array
   System.out.print("String as character array: "); 
   char letters[] = str1.toCharArray();                   // usage of toCharArray() method
   for(int i=0; i < letters.length; i++)
     System.out.print(letters[i] + ", ");
                                                         // string to byte array
   System.out.println();                                 // for a new line
   System.out.print("String as byte array: ");
   byte alphabets[] = str1.getBytes();                   // usage of getBytes() method
   for(int i=0; i < alphabets.length; i++)
     System.out.print(alphabets[i] + ", ");

String convert byte array char array
Output screen of of String convert byte array char array

                  String str1 = "ABCDEF"
                  char letters[] = str1.toCharArray();
                  byte alphabets[] = str1.getBytes();

Two methods of String class toCharArray() and getBytes() are used here. toCharArray() returns a char array that contains the elements nothing but the characters present in the string itself. Similarly, the getBytes() returns a byte array, the byte representation (ASCII values) of the characters present in the string. In a for loop the output is printed.

These methods are frequently by the Developer in coding.

The other methods of String class useful in these conversions are getChars() and overloaded copyValueOf().

The reverse is converting char array and byte array to string is available at Char array and Byte array to String Java.

Leave a Comment

Your email address will not be published.