String getBytes()

This method is used to get the byte array of string. It returns the array of byte. It has two variants of the String getBytes() method because it is an overloaded method in the String class.

String getBytes()

1. String getBytes()

This method doesn’t take any argument. It is used default charset to encode the string into bytes. Its return type is a byte array.

stringName.getBytes();

stringName: The string which you want to convert into a byte array.

class ExampleOfGetByte
 {  
	 public static void main(String args[])
	 {    
		String name = "JAVA WINGS";  
		// Convert the string "name" into byte array.
		 byte byteArray[] = name.getBytes();
		 for(int i = 0; i < byteArray.length ; i++)
		 System.out.println(byteArray[i]);	
          }
}  

Output:
74
65
86
65
32
87
73
78
71
83

2. String getBytes(String charsetName)

This method takes one argument.  This method accepts the name of the charset, according to which string must be encoded while conversion into bytes. Here we have some charset name:

  • US-ASCII
  • ISO-8859-1
  • UTF-8
  • UTF-16BE
  • UTF-16LE
stringName.getBytes(charsetName);

stringName: The string which you want to convert into a byte array.
CharsteName: You must provide the name of the charset.

class ExampleOfGetChar
 {  
	 public static void main(String args[])
	 {    
		String name = "JAVA WINGS";  
		 // Convert the string "name" into byte array.
		 byte byteArray[];
		try 
		{
			byteArray = name.getBytes("UTF-16");
			for(int i = 0; i < byteArray.length ; i++)
			 System.out.println(byteArray[i]);
		} 
		catch (UnsupportedEncodingException e)
                {
			e.printStackTrace();
		}
             }
}  

Output:
-2
1
0
74
0
65
0
86
0
65
0
32
0
87
0
73
0
78
0
71
0
83

1 thought on “String getBytes()”

Leave a Comment