Java String getBytes() Method

You are Here:

Java String getBytes()

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

Note: The behavior of this method, when this string cannot be encoded in the given charset, is unspecified.

Example

Java Compiler
public class myClass { public static void main(String[] args) { String str = "ABCDEabcde"; byte[] arr = str.getBytes(); for(int i=0; i<arr.length; i++){ System.out.println(arr[i]); } } }

Output

65 66 67 68 69 97 98 99 100 101

Syntax

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

Parameter Values

ValueTypeExplanation
charsetOptionalSpecifies the charset to encode this string into a sequence of bytes.
charsetNameOptionalSpecifies the named charset to encode this string into a sequence of bytes.

Return Value

ValueExplanation
ByteReturns the sequence of bytes.

Java String getBytes(Charset charset)

Encodes this String into a sequence of bytes using the given charset, storing the result into a new byte array.

Example

Java Compiler
import java.nio.charset.Charset; public class myClass { public static void main(String[] args) { String str = "ABCDEabcde"; byte[] arr = str.getBytes(Charset.forName("ASCII")); for(int i=0; i<arr.length; i++){ System.out.println(arr[i]); } } }

Output

65 66 67 68 69 97 98 99 100 101

Java String getBytes(String charsetName)

Encodes this String into a sequence of bytes using the named charset, storing the result into a new byte array.

Example

Java Compiler
public class myClass { public static void main(String[] args) { try{ String str = "ABCDEabcde"; byte[] arr = str.getBytes("ASCII"); for(int i=0; i<arr.length; i++){ System.out.println(arr[i]); } } catch (Exception e){ System.out.println(e.toString()); } } }

Output

65 66 67 68 69 97 98 99 100 101

Reminder

Hi Developers, we almost covered 90% of String functions and Interview Question on Java with examples for quick and easy learning.

We are working to cover every Single Concept in Java.

Please do google search for:

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author