getBytes() String Example


Many methods exist in java.lang.String class used for different string manipulations like checking the availability of a character, to extract a part of a string or to convert a data type to string etc. The present method is on getBytes() String.

getBytes() returns a byte array where elements are ASCII (depends on charset encoding) values of the characters of the string. That is, number of characters of the string is equal to the number of elements of the array.

getBytes() is overloaded many times but 3 overloaded method signatures are given hereunder mostly used.

  1. public byte[] getBytes(): Returns a byte array representing the string. To be more clear, each character of the string is converted to a byte (ASCII numeric form) and placed in an array. This byte array is returned. The encoding is done using platform default charset. Introduced with JDK 1.1.
  2. public byte[] getBytes(Charset charset): Returns a byte array representing the string. The encoding is done using charset passed as parameter.
  3. public void getBytes(int srcStart, int srcEnd, byte[] destination, int destinationStart): Copies the characters of string starting from srcStart to srcEnd-1 into destination byte array starting at destinationStart.
    • srcBegin: Starting index number of the character to copy from string
    • srcEnd: Ending index number of the character to copy from string
    • destination: It is the byte array into which stirng characters are to be copied
    • destinationStart: It is the element in the destination array from where copying shold start

    This method is deprecated in favor of getBytes().

Following example illustrates the usage of first two overloaded methods where a full string is converted. The third one is shown in next example where a part of string is converted.

I. To convert full string into byte array with different charsets using getBytes() String.

import java.io.UnsupportedEncodingException;

public class StringMethodDemo
{
 public static void main(String args[]) throws UnsupportedEncodingException
 {
  String str = "ABCDEFGHI";
   
  byte barray1[] = str.getBytes();  // converted into bytes using OS default charset
   
  System.out.println("String length: " + str.length());
  System.out.println("Byte array length: " + barray1.length);

  System.out.println("\nString " + str + " in bytes using default charset: ");
  for(int i = 0; i < barray1.length; i++)
  {
   System.out.print(barray1[i] + ", ");
  }

  byte barray2[] = str.getBytes("UTF-8");
  System.out.println("\n\nString " + str + " in bytes using charset UTF-8: ");
  for(int i = 0; i < barray2.length; i++)
  {
   System.out.print(barray2[i] + ", ");
  }

  byte barray3[] = str.getBytes("ISO-8859-1");
  System.out.println("\n\nString " + str + " in bytes using charset ISO-8859-1: ");
  for(int i = 0; i < barray3.length; i++)
  {
   System.out.print(barray3[i] + ", ");
  }

  byte barray4[] = str.getBytes("Cp1252");
  System.out.println("\n\nString " + str + " in bytes using charset Cp1252: ");
  for(int i = 0; i < barray4.length; i++)
  {
   System.out.print(barray4[i] + ", ");
  }

  byte barray5[] = str.getBytes("Cp500");
  System.out.println("\n\nString " + str + " in bytes using charset Cp500: ");
  for(int i = 0; i < barray5.length; i++)
  {
   System.out.print(barray5[i] + ", ");
  }
 }
}


getBytes() String
Output screen on getBytes() String Example

Some charsets are UTF-8 (for 1 byte ASCII), UTF-16 (for 2 bytes Unicode), Cp1252, Cp500.

Charsets UTF-8 and ISO-8859-1 are default for many operating systems.

getBytes(String charset) method throws a checked exception UnsupportedEncodingException.

byte barray5[] = str.getBytes("Cp500");

Cp500 is a different charset encoding. See the output screen.

II. To copy a few characters of String to Array elements

Earlier, getBytes() methods converted whole string into array of bytes. Here, a few characters of string are copied into an existing byte array. That is, few elements of byte array are replaced by few characters of string.

Here, third overloaded getBytes() is used.

public class StringMethodDemo
{
 public static void main(String args[])
 {
  String str = "ABCDEFGHI";
  byte barray[] = { 97, 98, 99, 100, 101, 102};

  str.getBytes(1, 4, barray, 1);
  System.out.println("To print the byte array elements after replacing:");
  for(int i = 0; i < barray.length; i++)
  {
   System.out.print(barray[i] + ", ");   
  }
 }
}


getBytes() String
Output screen on getBytes() String Example

The elements of byte array 98, 99 and 100 are replaced by B, C and D (with their ASCII values). See the screenshot. Charaters of string str starting from 1 to ending 4-1 (that is, 1, 2, 3) are copied into array. This method does not throw any UnsupportedEncodingException and is deprecated.

A similar method exists to convert string to character array - toCharArray().

Leave a Comment

Your email address will not be published.