Java String getBytes Method

The Java String.getBytes method is one of the Java 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 Java String 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 Java String getBytes 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 String 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 1

The Java String.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 default charset.

TIP: The String.getBytes Method throws UnsupportedEncodingException. So, it is always advisable to use Try catch block.

// Java String.getBytes example
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 String getBytes example, First, we declared two String variables str, str1, and assigned corresponding values using the following statement.

String str = "ABCDE";
String str1 = "abcd";

The following getBytes String Function statements will call the public byte [] getBytes () method to encode the above-specified string (str & str1) into a sequence of bytes. From the above screenshot, you can observe that both these statements are using the platform 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 below code snippet, you can observe that 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 end-user).

// Java String.getBytes example
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 the getBytes Method:");
			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 the getBytes Method:");
			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 the getBytes Method:");
			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 the getBytes Method:
65 	-61 	-86 	-61 	-79 	-61 	-68 	67 	
Decryted Text = AêñüC

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

Byte Array after using the getBytes Method:
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.

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

The following statements will call the public byte [] getBytes () method to encode the above-specified string (str) into a sequence of bytes. It is using the platform default charset.

byte[] byteArray = str.getBytes();

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

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

The following String getBytes statements will call the public byte [] getBytes (Charset charset) method to encode the above-specified string (str) into a sequence of bytes using standard charset ISO-8859-1.

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

The following String getBytes statement is to convert the Byte array to string

String s3 = new String(bArray);

String getBytes Example 3

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

// Java String.getBytes example
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 the getBytes Method:");
		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 the getBytes Method:");
		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 the getBytes Method:");
		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 the getBytes Method:
0 	65 	0 	-22 	0 	-15 	0 	-4 	0 	67 	
Decryted Text = A���C

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

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

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

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

It will call the public byte [] getBytes (String Charset_name) 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 public byte [] getBytes (String Charset_name) method to encode the above-specified string (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 Java String getBytes statement, we are assigning the default charset name.

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

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

String s1 = new String(byteArray);

NOTE:

  • 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 Standard charset namespace by adding import java.nio.charset.StandardCharsets;