Java String getBytes Method

The Java String.getBytes method is one of the String Methods, which is to encode the given string into a sequence of bytes using the user-specified Charset and return Byte array.

In this article, we will show how to write the getBytes method with an example. The syntax of the string.getBytes in Java Programming language is as shown below.

Java String getBytes syntax

The Java Programming Language provides three different getBytes methods to encode the string. The following method will not accept any argument and encode the given string into a sequence of bytes using the default charset.

public byte[] getBytes(); // It will return Byte Array 

//In order to use in program
String_Object.getBytes();

Below Java getBytes method will accept Charset as an argument and encode the given string into a sequence of bytes using the user-specified Charset. It means we are allowing the user to specify the Charset (dynamic).

public byte[] getBytes(Charset charset); // It will return Byte Array 

//In order to use in program
String_Object.getBytes(Charset charset);

The following Java String getBytes method will accept Charset’s name as an argument. And then encodes the given string into a sequence of bytes by invoking the specified charset name. It means we are calling the required Charset name (static).

public byte[] getBytes(String Charset_Name); // It will return Byte Array 

//In order to use in program
String_Object.getBytes(String Charset_Name);

Return Value: The Java getBytes Method encodes this string into a sequence of bytes using the user-specified Charset, and it will store the result in a byte array.

Java String getBytes Example

The Java getBytes method encodes the given string into a sequence of bytes and returns a byte array. In this Java program, We are going to encode the string using the platform’s default charset.

TIP: This Method throws an Unsupported Encoding Exception. So, it is always advisable to use Try catch block.

package StringFunctions;

public class getBytesMethod {

	public static void main(String[] args) {
		String str = "ABCDE";
		byte[] byteArray = str.getBytes();
		System.out.println("Byte Array after using the getBytes Method:");
		arrayPrint(byteArray);	
		
		String str1 = "abcd";
		byte[] bitArray = str1.getBytes();
		System.out.println("\nByte Array after using the getBytes Method:");
		arrayPrint(bitArray);	
	}
	public static void arrayPrint(byte[] anByteArray) {
		for (byte Number: anByteArray) {
			System.out.format("%d \t", Number);
		}
	}
}
Java String getBytes Method 1

TIP: Please refer to the ASCII Table to understand the byte values in Java Programming.

Within the Java getBytes example, we first declared two string variables, str1, and assigned corresponding values.

The following String Function statements will call the getBytes() method to encode the above-specified str and str1 into a sequence of bytes. From the above screenshot, you can observe that both these statements are using the platform’s default charset.

byte[] byteArray = str.getBytes();
byte[] bitArray = str1.getBytes();

The following statement is to print the Byte array elements to the output.

arrayPrint(byteArray);

When the compiler reaches the above statement, the compiler will jump to the following function. From the code snippet below, we used the Foreach Loop to iterate the Byte Array. Then we are printing every array element using the System.out.println statement.

public static void arrayPrint(byte[] anByteArray) {
	for (byte Number: anByteArray) {
		System.out.format("%d \t", Number);
	}
}

Java String getBytes Example 2

In this Java program, we are going to encode the string using the available standard charsets (Providing Dynamic functionality to the end-user).

package StringFunctions;
import java.io.UnsupportedEncodingException;

public class getBytesMethod2 {
	public static void main(String[] args) {
		String str = new String("A" + "\u00ea" + "\u00f1" + "\u00fc" + "C");
		try {
			byte[] byteArray = str.getBytes();
			System.out.println("Byte Array after using:");
			arrayPrint(byteArray);	
			String s1 = new String(byteArray);
			System.out.println("\nDecryted Text = " + s1);
			
			byte[] bitArray = str.getBytes("UTF-8");
			System.out.println("\nByte Array after using:");
			arrayPrint(bitArray);
			String s2 = new String(bitArray);
			System.out.println("\nDecryted Text = " + s2);
			
			byte[] bArray = str.getBytes("ISO-8859-1");
			System.out.println("\nByte Array after using:");
			arrayPrint(bArray);
			String s3 = new String(bArray);
			System.out.println("\nDecryted Text = " + s3);
		}
     catch( UnsupportedEncodingException e){
        System.out.println("Unsupported character set");
     }
	}
	public static void arrayPrint(byte[] anByteArray) {
		for (byte bit: anByteArray) {
			System.out.format("%d \t", bit);
		}
	}
}

From the output, you can observe that the default charset and the standard charset ISO-8859-1 are returning the same result.

Byte Array after using:
65 	-61 	-86 	-61 	-79 	-61 	-68 	67 	
Decryted Text = AêñüC

Byte Array after using:
65 	-61 	-86 	-61 	-79 	-61 	-68 	67 	
Decryted Text = AêñüC

Byte Array after using:
65 	-22 	-15 	-4 	67 	
Decryted Text = A���C

First, we declared a String variable str and assigned non-Unicode text using the following statement.

str = new String("A" + "\u00ea" + "\u00f1" + "\u00fc" + "C");

The following statements will encode the above-specified str into a sequence of bytes. It is using the platform’s default charset.

byteArray = str.getBytes();

It will call the public byte [] getBytes (Charset charset) method to encode the above-specified str into a sequence of bytes using standard charset UTF-8.

bitArray = str.getBytes("UTF-8");

The following statements will call the getBytes method to encode the above-specified str into a sequence of bytes using standard charset ISO-8859-1.

bArray = str.getBytes("ISO-8859-1");

The following Java getBytes statement is to convert the Byte array to string.

s3 = new String(bArray);

getBytes Example 3

In this Java program, We are going to encode the string by calling the available standard charsets names (Static functionality).

package StringFunctions;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

public class getBytesMethod3 {
	public static void main(String[] args) {
		String str = new String("A" + "\u00ea" + "\u00f1" + "\u00fc" + "C");
		byte[] byteArray = str.getBytes(StandardCharsets.UTF_16BE);
		System.out.println("Byte Array after using:");
		arrayPrint(byteArray);	
		String s1 = new String(byteArray);
		System.out.println("\nDecryted Text = " + s1);
		
		byte[] bitArray = str.getBytes(StandardCharsets.UTF_8);
		System.out.println("\nByte Array after using:");
		arrayPrint(bitArray);
		String s2 = new String(bitArray);
		System.out.println("\nDecryted Text = " + s2);
		
		byte[] bArray = str.getBytes(Charset.defaultCharset());
		System.out.println("\nByte Array after using:");
		arrayPrint(bArray);
		String s3 = new String(bArray);
		System.out.println("\nDecryted Text = " + s3);
	}
	public static void arrayPrint(byte[] anByteArray) {
		for (byte bit: anByteArray) {
			System.out.format("%d \t", bit);
		}
	}
}
Byte Array after using:
0 	65 	0 	-22 	0 	-15 	0 	-4 	0 	67 	
Decryted Text = A���C

Byte Array after using:
65 	-61 	-86 	-61 	-79 	-61 	-68 	67 	
Decryted Text = AêñüC

Byte Array after using:
65 	-61 	-86 	-61 	-79 	-61 	-68 	67 	
Decryted Text = AêñüC

Within the example, First, we declared a String variable str and assigned non-Unicode text.

str = new String("A" + "\u00ea" + "\u00f1" + "\u00fc" + "C");

It will call the Java getBytes method to encode the string str into a sequence of bytes. It is calling the standard charset name UTF_16BE.

byte[] byteArray = str.getBytes(StandardCharsets.UTF_16BE);

Calls the method to encode the above-specified str into a sequence of bytes. It is calling the standard charset name UTF_8.

byte[] bitArray = str.getBytes(StandardCharsets.UTF_8);

Within the below statement, we are assigning the default charset name.

byte[] bArray = str.getBytes(Charset.defaultCharset());

The following statement is to convert the Byte array to a string.

s1 = new String(byteArray);

To use the Charset.defaultCharset() method, You have to import charset namespace by adding import java.nio.charset.Charset;

To use the Standard Charsets, You have to import the Standard charset namespace by adding import java.io.charset.StandardCharsets;