Java String getBytes() Method

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]); } } }

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]); } } }

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()); } } }

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