Java Program to get the Characters in a String as an Array of Bytes

Java 8Object Oriented ProgrammingProgramming

To get the characters in a string as an array of bytes, use the getBytes() method.

Let’s say we have the following string.

String str = "Demo Text!";

Convert it to array of bytes.

byte[] arr = str.getBytes();

Example

 Live Demo

public class Demo {
   public static void main(String[] args) {
      String str = "Demo Text!";
      // getting as an array of bytes
      byte[] arr = str.getBytes();
      // displaying each character as a Byte value
      for(byte res: arr) {
         System.out.println(res);
      }
   }
}

Output

68
101
109
111
32
84
101
120
116
33
raja
Published on 13-Dec-2018 14:23:08
Advertisements