1. Introduction
Converting a String to a byte array is a common programming task. In Java, this can be accomplished using the getBytes method of the String class. This method encodes the String into a sequence of bytes using the platform’s default charset and returns the resulting byte array.
2. Program Steps
1. Create a Java class and define the main method.
2. Define the input String that you want to convert to a byte array.
3. Use the getBytes method to convert the String to a byte array.
4. Print the original String and the resulting byte array.
3. Code Program
public class StringToByteArray {
public static void main(String[] args) {
// Step 2: Define the input String
String str = "Hello, World!";
// Step 3: Use the getBytes method to convert the String to a byte array
byte[] byteArray = str.getBytes();
// Step 4: Print the original String and the resulting byte array
System.out.println("Original String: " + str);
System.out.print("Byte Array: ");
for(byte b : byteArray) {
System.out.print(b + " ");
}
}
}
Output:
Original String: Hello, World! Byte Array: 72 101 108 108 111 44 32 87 111 114 108 100 33
4. Step By Step Explanation
– Step 1: A Java class named StringToByteArray is created, and the main method is defined.
– Step 2: The input String str is defined, which we want to convert to a byte array.
– Step 3: The getBytes method of the String class is used to convert str to a byte array byteArray.
– Step 4: The original String and the resulting byte array are printed to the console.
In this way, the program effectively converts a String to a byte array using the getBytes method in Java and prints the original String and the corresponding byte array.