How do you use character encodings and Charset with a simple code example?

In Java, character encodings and Charset are used to convert between different character sets. This is particularly important when reading or writing text data that may contain characters not represented in a single-byte encoding.

Character Encoding Example

// Import necessary classes import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; public class CharsetExample { public static void main(String[] args) { // Define a string String originalString = "Hello, World!"; // Get a byte array of the string using UTF-8 encoding byte[] utf8Bytes = originalString.getBytes(StandardCharsets.UTF_8); // Convert back to string using UTF-8 Charset String utf8String = new String(utf8Bytes, StandardCharsets.UTF_8); // Print the output System.out.println("Original String: " + originalString); System.out.println("UTF-8 Encoded String: " + utf8String); } }

Java Charset Character Encoding UTF-8 NIO