How to convert String or StringBuffer to byte array?

public byte[] getBytes() method is used to convert string to byte array. see more about String getBytes

To convert byte array to string use new String(bytes)

Example

package com.pretech;
public class ByteArrayConversion {
	public static void main(String[] args) {
		StringBuffer sb=new StringBuffer();
		sb.append("hello").append("world");
		System.out.println(sb);
	
		byte[] bytearray=String.valueOf(sb).getBytes();
		
		System.out.println(new String(bytearray));
		
		
		
	}
}

Output



helloworld
helloworld


No comments:

Post a Comment

12 classic String-based Java interview questions with simple explanations and code.

  1️⃣ Check if a String is a Palindrome Problem Given a string, check if it reads the same forward and backward. Example: "madam...

Featured Posts