String to Array Java


After learning how to convert a Java byte array and char array to string, let us see the other way of converting sting to array Java.

The methods used for the job are toCharArray() and getBytes() method. Let us see first their signatures as defined in String class.

  1. public char[] toCharArray(): Returns a new char array with the characters of string.
  2. public byte[] getBytes(): Returns a new byte array with the characters of the string. The characters are decoded and copied into the array.
Following example on String to Array uses the above methods.
import java.util.Arrays;
public class StringToArray
{
  public static void main(String args[])
  {
    String str1 = "abcdef";
    System.out.println("String str1: " + str1);
    char charArray[] = str1.toCharArray();
    System.out.println("charArray elements: " + Arrays.toString(charArray));

    byte byteArray[] = str1.getBytes();
    System.out.println("byteArray elements: " + Arrays.toString(byteArray));
  }
}

String to Array JavaOutput Screenshot on String to Array Java

char charArray[] = str1.toCharArray();
byte byteArray[] = str1.getBytes();

The string str1 is converted to char array and byte array with String methods toCharArray() and getBytes().

Know the reverse way of converting a Java byte array and char array to string

Leave a Comment

Your email address will not be published.