How To Convert String To Byte In Java?

This tutorial highlights the simple example to demonstrates how to convert a string object to the byte stream. We can simply use the getBytes() method in the string object to convert the string to bytes array. Lets look at the example program.

package javabeat.net.core;

public class StringToByteExample {
	public static void main(String[] argv) {

		String str = "JavaBeat Website";
		byte[] bytes = str.getBytes();

		System.out.println("String Value : " + str);
		System.out.println("String [Byte Format] : " + bytes);
		System.out.println("-----Printing Bytes Array-------");
		for (int i=0;i<bytes.length;i++){
			System.out.println(bytes[i]);
		}

	}
}

Output

String Value : JavaBeat Website
String [Byte Format] : [B@15f5897
-----Printing Bytes Array-------
74
97
118
97
66
101
97
116
32
87
101
98
115
105
116
101

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Pin It on Pinterest

Share This

Share this post with your friends!

Share This

Share this post with your friends!