Easy Tutorial
❮ Env Classpath Java Filewriter ❯

Java getBytes() Method

Java String Class


The getBytes() method has two forms:

-

getBytes(String charsetName): Encodes this string into a sequence of bytes using the specified charset, storing the result into a new byte array.

-

getBytes(): Encodes this string into a sequence of bytes using the platform's default charset, storing the result into a new byte array.

Syntax

public byte[] getBytes(String charsetName) throws UnsupportedEncodingException

or

public byte[] getBytes()

Parameters

-

charsetName -- The name of a supported charset.

Return Value

Returns a byte array.

Example

import java.io.*;

public class Test {
    public static void main(String args[]) {
        String Str1 = new String("tutorialpro");

        try{
            byte[] Str2 = Str1.getBytes();
            System.out.println("Return value: " + Str2 );

            Str2 = Str1.getBytes( "UTF-8" );
            System.out.println("Return value: " + Str2 );

            Str2 = Str1.getBytes( "ISO-8859-1" );
            System.out.println("Return value: " + Str2 );
        } catch ( UnsupportedEncodingException e){
            System.out.println("Unsupported charset");
        }
    }
}

The above program execution results are:

Return value: [B@7852e922
Return value: [B@4e25154f
Return value: [B@70dea4e

Java String Class

❮ Env Classpath Java Filewriter ❯