CharsetEncoder replacement() Method in Java with Examples7 May 2025 | 2 min read One of the built-in methods of the java.nio.charset is the replacement() method. The encoder's replacement value is returned as a byte array by CharsetEncoder. When encoding operations come within an unmappable character, Java's CharsetEncoder class's replacement() function retrieved the encoder's current replacement sequence. A byte array known as this replacement sequence is used to replace characters that are not present in the destination charset. A common replacement in many charsets is the "?" character or its counterpart in the target encoding. The technique assures that the replacement sequence is valid and follows the target charset's standards. Particularly when interacting with non-standard or unsupported characters, it is essential to preserve the integrity of data during encoding. Syntax: Parameters: There are no parameters accepted by the above method. Return Value: The current replacement for this encoder is returned by the method; it is never empty or null. Example 1:A class EncoderReplacementExample1 is defined in the code to show how to use the replacement() method in a CharsetEncoder. For the UTF-8 character set, it uses the newEncoder() method to build a CharsetEncoder instance. Usually used when encoding comes across unmappable characters, the replacement() method is used on the encoder to acquire its current replacement byte array. After being retrieved, the replacement sequence is shown as a string. The implementation illustrates the use of the replacement() method to access and comprehend the encoder's fallback mechanism. Implementation:FileName: EncoderReplacementExample1.java Output: The encoder's current replacement is: [B@2a139a55 Example 2:For the US-ASCII charset, the code uses the Charset.forName and newEncoder methods to construct a CharsetEncoder instance. To obtain the default byte sequence to be used for characters that cannot be encoded in the designated charset, it invokes the encoder's replacement() method. The method's output is then shown on the console. The use of the replacement() method to retrieve the encoder's substitution byte sequence configuration is demonstrated in this example. Implementation:FileName: EncoderReplacementExample2.java Output: The encoder's current replacement is: [B@659e0bfd Next TopicJava Plot |
We request you to subscribe our newsletter for upcoming updates.

We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India