String to Array Java

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.

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 Reply

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