Java Program to convert String to byte array


Here is our string.

String str = "Asia is a continent!";

Now let us use a byte array and the getBytes() method to fulfill our purpose.

byte[] byteVal = str.getBytes();

Now, if we will get the length of the array, it would return the length as shown in the complete example below −

Example

 Live Demo

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

Output

Asia is a continent!
20

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 26-Jun-2020

278 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements