java.lang.String getBytes()

Description :

This java tutorial shows how to use the getBytes() method of java.lang.String class. This method returns byte[] array. The getBytes() method of String class generally convert or encode this String into byte array. This method accepts a Charset as parameter however if none is specified or unrecognizable input then the default will be used. If the input on the overriding method is a charsetName and its not recognized, a UnsupportedEncodingException will be thrown.

Method Syntax :

public byte[] getBytes()
public byte[] getBytes(Charset charset)
public byte[] getBytes(String charsetName)

Parameter Input :

DataType Parameter Description
Charset charset the charset to be used in converting or encoding the source String

Method Returns :

This method returns byte array (byte[]).

Exception :

public byte[] getBytes(String charsetName) throws UnsupportedEncodingException

UnsupportedEncodingException is thrown when the parameter charsetName is not on recognized.

Java Code Example :

This example source code demonstrates the use of getBytes() method of String class. Basically this source code just prints the byte array from the three method override of getBytes method. The code also shows the use of the Arrays.toString method to get the string representation of character array.

package com.javatutorialhq.java.tutorial.string;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.Arrays;

/*
 * This is a sample java source code of String class getBytes() method
 */

public class StringGetBytesDemo {

    public static void main(String[] args) throws UnsupportedEncodingException {
        System.out.println(Arrays.toString("@test string".getBytes()));
        System.out.println(Arrays.toString("@test string".getBytes("US-ASCII")));
        System.out.println(Arrays.toString("@test string".getBytes(Charset.forName("UTF-8"))));

    }

}

Sample Output :

Running the getBytes() method example source code of java.lang.String class will give you the following output

java string getbytes method example

java string getbytes method example

Exception Scenario :

Exception in thread "main" java.io.UnsupportedEncodingException: US-1
	at java.lang.StringCoding.encode(Unknown Source)
	at java.lang.String.getBytes(Unknown Source)
	at com.teknoscope.java.tutorial.string.StringGetBytesDemo.main(StringGetBytesDemo.java:16)

Suggested Reading List :

References :