Wednesday 29 January 2020

Convert string to UTF-8 byte array

'getBytes' method is used to convert string to byte array with specific charset.

Example
String str = "Hello World";
byte[] bytes = str.getBytes(StandardCharsets.UTF_8);

App.java
package com.sample.app;

import java.nio.charset.StandardCharsets;

public class App {
 
 private static void printByteArray(byte[] arr) {
  for(byte b: arr) {
   System.out.print(b + " ");
  }
  System.out.println();
 }

 public static void main(String args[]){
  String str = "Hello World";
  
  byte[] bytes = str.getBytes(StandardCharsets.UTF_8);
  
  printByteArray(bytes);
 }

}

Output
72 101 108 108 111 32 87 111 114 108 100



You may like

No comments:

Post a Comment