How to convert a string to byte array?

Question:
How can you convert a string to a byte array?

Answer:
Use the String getBytes() method.

Code:
public class StringToBytes {
 
   public static void main(String args[]){
 
      String str = "abc DEF 123";
 
      byte[] bytes = str.getBytes();
 
      for(int i=0; i < bytes.length; i++){
 
         // print byte
         System.out.print(bytes[i]);
 
         // print char with casting
         System.out.println(" : " + (char)bytes[i]);
      }
   }
}

Output:
$ java StringToBytes
97 : a
98 : b
99 : c
32 :  
68 : D
69 : E
70 : F
32 :  
49 : 1
50 : 2
51 : 3