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.
getbytes():
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.
public class StringMethodsEx { public static void main(String[] args) { String val1 = "Hello world!!"; byte[] a = val1.getBytes(); // array of bytes for(byte b : a){ System.out.print(b+"-"); } } }
byte[] getBytes(Charset charset):
Instead of default character set, We can also specify the character set as well in getByte() method.
public class StringMethodsEx { public static void main(String[] args) { try{ String val1 = "Hello world!!"; byte[] a = val1.getBytes("UTF-16"); // array of bytes for(byte b : a){ System.out.print(b+"-"); } }catch(UnsupportedEncodingException e){ System.out.println("Error msg " +e.getMessage()); } } }
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.
public class StringMethodsEx { public static void main(String[] args) { String val1 = "Hello world!!"; char a[] = new char[8]; val1.getChars(3, 10, a, 0); for(char c: a){ System.out.print(c+"-"); } } }