Home » Java programs » Java basic programs

Convert String to byte array and vice versa in java?



In this java program/example, we are converting String to byte array and byte array to String.
Submitted by Preeti Jain, on February 10, 2018

Example 1:

Java program to convert from String to byte array

class StringToByteArray{
	public static void main(String[] args){
		String s = "My Name Is Preeti Jain";
		byte[] byt = s.getBytes();
		System.out.println("String is converted in to byte[] :" + byt);
	}
}

Output

D:\Java Articles>java StringToByteArray
String is converted in to byte[] :[[email protected]

Example 2:

Java program to convert from byte array to String

class ByteArrayToString{
public static void main(String[] args){
	String qualification = "I have done MCA";
		byte[] byt = qualification.getBytes();
		String str = new String(byt);
		System.out.println("Byte[] array is converted into String :" + str);
	}
}

Output

D:\Java Articles>java ByteArrayToString
Byte[] array is converted into String :I have done MCA





Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.



Comments and Discussions


We are using Google to publish ads on our website; Google has its own privacy policies. They may save log, cookies on your system. Google may also collect information of your system like IP address, region, city, country. For more details please go through the Google’s privacy policy.