Java String getBytes()

The java string getBytes() method returns the byte array of the string. In other words, it returns sequence of bytes.

Signature

There are 3 variant of getBytes() method. The signature or syntax of string getBytes() method is given:
public byte[] getBytes()  
public byte[] getBytes(Charset charset)  
public byte[] getBytes(String charsetName)throws UnsupportedEncodingException

Returns

sequence of bytes.

Java String getBytes() method example

public class StringGetBytesExample{  
public static void main(String args[]){  
String s1="XYZABC";  
byte[] barr=s1.getBytes();  
for(int i=0;i< barr.length;i++){  
System.out.println(barr[i]);
System.out.println(barr[i]);  
}  
}}

Output:

88
88
89
89
90
90
65
65
66
66
67
67

Java String getChars()

The java string getChars()method copies the content of this string into specified char array.
There are 4 arguments passed in getChars() method. The signature of getChars() method is given:

Signature

Syntax:

public void getChars(int srcBeginIndex, int srcEndIndex, char[] destination, int dstBeginIndex)

Returns

It doesn't return any value.

Throws

It throws StringIndexOutOfBoundsException if beginIndex is greater than endIndex.

Java String getChars() method example

public class StringGetCharsExample{  
public static void main(String args[]){  
 String str = new String("hello catchmecoder how r u");  
      char[] ch = new char[12];  
      try{  
         str.getChars(6, 18, ch, 0);  
         System.out.println(ch);  
      }catch(Exception ex){System.out.println(ex);}  
}}      

Output:

catchmecoder