Java String getBytes() method example.

Java 8Object Oriented ProgrammingProgramming

The getBytes() method encodes the current String into a sequence of bytes using the given charset, storing the result into a new byte array.

Example

Live Demo

import java.lang.*;
public class StringDemo {
   public static void main(String[] args) {
      try {
         String str1 = "admin";
         System.out.println("string1 = " + str1);

         //copy the contents of the String to a byte array
         byte[] arr = str1.getBytes();
         String str2 = new String(arr);

         //print the contents of the byte array
         System.out.println("new string = " + str2);
      } catch(Exception e) {
         System.out.print(e.toString());
      }
   }
}

Output

string1 = admin
new string = admin
raja
Published on 12-Feb-2018 10:43:53
Advertisements