Write a program to get the contents of a given string as a byte array


This Java program converts a given String to a byte array and then creates a new String from that byte array.

  • The program first imports the Calendar class and defines a public class named "String_ByteArray" with a main method that takes no arguments. The main method declares a String variable str1 with the value "This is a sample String."
  • Then, the program uses the getBytes method of the String class to convert str1 to a byte array and stores the result in the byte array variable bytearr.
  • Next, the program creates a new String from the byte array bytearr using the String constructor that takes a byte array as an argument. The new String is stored in the String variable str2.
  • Finally, the program prints out the new String str2 by concatenating the string "The new String equals " with the variable str2 using the + operator and using System.out.println method to display the result.

Source Code

import java.util.Calendar;
public class String_ByteArray
{
	public static void main(String[] args)
	{
		String str1 = "This is a sample String.";
		byte[] bytearr = str1.getBytes();
		String str2 = new String(bytearr);
		System.out.println("The new String equals " +str2);
	}
}

Output

The new String equals This is a sample String.

Example Programs