String methods – getBytes() and getChars()

In this post, we will discuss about String methods – getBytes() and getChars().Let’s look at them one by one with examples.


Encodes this String into a sequence of bytes using the platform’s default charset, storing the result into a new byte array.It throws UnsupportedEncodingException – If the specified charset is not supported.

Output: 72-101-108-108-111-32-119-111-114-108-100-33-33-

byte[] getBytes(Charset charset):

Instead of default character set, We can also specify the character set as well in getByte() method.

Output: -2–1-0-72-0-101-0-108-0-108-0-111-0-32-0-119-0-111-0-114-0-108-0-100-0-33-0-33-



void getChars(int srcBegin,int srcEnd,char[] dst,int dstBegin) :

This method is used to copy string into destination array.

srcBegin – index of the first character in the string to copy.
srcEnd – index after the last character in the string to copy.
dst – Destination array of characters in which the characters from String gets copied.
dstBegin – The index in Array starting from where the chars will be pushed into the Array.

Output: l-o- -w-o-r-l-
Ask Question
Have any question or suggestion for us?Please feel free to post in Q&A Forum
String methods - contentEquals
String methods - toString,toUppercase,toLowercase,toChararray
Shekhar Sharma

Shekhar Sharma

Shekhar Sharma is founder of This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...