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

Model Context Protocol (MCP) — Complete Guide for Backend Engineers

  Model Context Protocol (MCP) — Complete Guide for Backend Engineers Build Tools, Resources, and AI-Driven Services Using LangChain Moder...

Featured Posts