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+"-");
		}
	}
}
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.

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());
		}
	}
}
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.

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+"-");
		}
	}
}
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
Avatar photo

Shekhar Sharma

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

You may also like...