C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

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[] :[B@6d06d69c

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


Liked this article? Do share with your friends :)


COMMENTS