How to Convert a String to Specific Character Encoding in Java?
Last Updated :
29 Jan, 2024
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
import java.nio.charset.Charset;
public class StringToEncodingExample {
public static void main(String[] args) {
String originalString = "Hello, Rahul!" ;
byte [] utf8Bytes = originalString.getBytes(Charset.forName( "UTF-8" ));
System.out.println( "Original String: " + originalString);
System.out.println( "UTF-8 Encoded Bytes: " + bytesToHex(utf8Bytes));
}
private static String bytesToHex( byte [] bytes) {
StringBuilder hexStringBuilder = new StringBuilder();
for ( byte b : bytes) {
hexStringBuilder.append(String.format( "%01X " , b));
}
return hexStringBuilder.toString();
}
}
|
Output
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.
Share your thoughts in the comments
Please Login to comment...