Java String.getBytes(Charset charset)

Syntax

String.getBytes(Charset charset) has the following syntax.

public byte[] getBytes(Charset charset)

Example

In the following code shows how to use String.getBytes(Charset charset) method.


import java.nio.charset.Charset;
/*  w ww.ja v a  2 s.c  om*/
public class Main {

  public static void main(String[] args) {

    try {
      String str1 = "java2s.com";
      System.out.println("string1 = " + str1);
      // copy the contents of the String to a byte array
      byte[] arr = str1.getBytes(Charset.forName("ASCII"));

      String str2 = new String(arr);
      System.out.println("new string = " + str2);
    } catch (Exception e) {
      System.out.print(e.toString());
    }
  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    java.lang »




Boolean
Byte
Character
Class
Double
Enum
Float
Integer
Long
Math
Number
Object
Package
Process
ProcessBuilder
Runnable
Runtime
SecurityManager
Short
StackTraceElement
StrictMath
String
StringBuffer
StringBuilder
System
Thread
ThreadGroup
ThreadLocal
Throwable