English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java program converts string to byte array

This is our string.

String str = "Asia is a continent!";

Now, let's use the byte array andgetBytes()Method to achieve our purpose.

byte[] byteVal = str.getBytes();

Now, if we want to get the length of an array, it will return the length, as shown in the complete example below:

Example

public class Demo {
   public static void main(String args[]) {
      String str = "Asia is a continent!";
      System.out.println(str);
      //Convert to byte array
      byte[] byteVal = str.getBytes();
      //Get Length
      System.out.println(byteVal.length);
   }
}

Output Result

Asia is a continent!
20