In Java, the process of converting a String to a certain character encoding is converting the string’s character sequence to a byte array and applying the chosen character encoding.
Java Program to Convert a String to a Specific Character Encoding
Using the String class’s getBytes() function to transform a string into a byte array is the fundamental idea. The Charset class also allows you to define the character encoding. An overloaded version of the getBytes() function accepts a Charset as a parameter.
Syntax:
public byte[] getBytes()
Below is the implementation to Convert a String to a specific character encoding in Java:
// Java Program to Convert a String // Specific Character Encoding import java.nio.charset.Charset;
// Driver Class public class StringToEncodingExample {
// Main Function
public static void main(String[] args) {
// Create a sample string
String originalString = "Hello, Rahul!" ;
// Convert the string to bytes using a specific encoding
byte [] utf8Bytes = originalString.getBytes(Charset.forName( "UTF-8" ));
// Display the original string and the encoded bytes
System.out.println( "Original String: " + originalString);
System.out.println( "UTF-8 Encoded Bytes: " + bytesToHex(utf8Bytes));
}
// Method to convert byte array to hexadecimal string
private static String bytesToHex( byte [] bytes) {
StringBuilder hexStringBuilder = new StringBuilder();
for ( byte b : bytes) {
hexStringBuilder.append(String.format( "%01X " , b));
}
return hexStringBuilder.toString();
}
} |
Original String: Hello, Rahul! UTF-8 Encoded Bytes: 48 65 6C 6C 6F 2C 20 52 61 68 75 6C 21
Explaination of the above Program:
The Program is divided it in different section:
- Input String is declared
- Converting String to Byte array storing
- Converting byte to hexadecimal string and then printing.
- Printing the Final Result.