Open In App

java.nio.charset.CoderResult Class in Java

Last Updated : 08 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The ‘java.nio.charset’ package in Java contains classes for character encoding and decoding. The CoderResult class is used for determining the outcome of an encoding or decoding operation.

Before we get started, let’s review the ideas behind character encoding and decoding in CoderResult.

  • The process of converting characters from one representation to another, usually from a human-readable format to one that can be transmitted or stored is known as character encoding.
  • Character decoding is the opposite procedure that returns encoded characters to their original state.

The CoderResult class is part of the Java NIO (New I/O) package and serves as a mechanism for reporting the result of a coding operation performed by a CharsetEncoder or CharsetDecoder.

  • It offers an approach for handling the results of these operations by displaying both success and failure scenarios.
  • CoderResult instances can hold extra information about the position in the input and output buffers in addition to serving as a status indicator for the encoding or decoding operation.

Note: java.nio.charset package was introduced in Java 1.4 to improve character set and character encoding handling

Class Declaration for CoderResult

public class CoderResult extends Object

The syntax for the class declaration of CoderResult is a publicly accessible class and implicitly inherits from the Object class which is the root class for all Java classes.

  • Basic methods like equals() and toString() are provided by Extending Object, so the instances of the CoderResult class have access to these functions.

Fields of CoderResult

Following are the fields offered by the CoderResult class:

Modifier and Type

Field

Description

static CoderResult

OVERFLOW

An overflow result object indicates that there is not enough space in the output buffer.

static CoderResult

UNDERFLOW

Result object indicating underflow, which indicates that more input is needed if the input buffer is not yet empty, or that it has been fully consumed.

Methods of CoderResult Class

Here are the key methods which are supported by CoderResult class to ensure effective handling of encoding and decoding outcomes.

Modifier and Type

Class

Description

boolean

isError()

Indicates if this object represents an error condition or not.

boolean

isMalformed()

Indicates if the object in question represents a malformed input error or not.

boolean

isOverflow()

Shows whether the object represents an overflow situation or not.

boolean

isUnderflow()

Shows whether the object represents an underflow situation or not.

boolean

isUnmappable()

Denotes if the object corresponds to an unmappable character error or not.

int

length()

It returns the length of the incorrect input that this object (optional operation) described.

static CoderResult

malformedForLength(int length)

A static factory method that provides a unique object expressing a given length malformed input error.

void

throwException()

It throws an exception suitable for the outcome this object describes.

String

toString()

Returns a string that describes the result of the Coder.

static CoderResult

unmappableForLength(int length)

The unique result object describing an unmappable-character error of the specified length is returned by this static factory method.

The methods of the CoderResult class are also inherited from the java.lang.Object class.

Example CoderResult Class in Java

This Java program uses the CoderResult class to for character encoding. For UTF-8 encoding, it initializes a Charset and matching CharsetEncoder.

  • The string “GeeksforGeeks,” which is contained in the input buffer
  • then the input buffer is encoded into an output buffer that has been previously allocated.
  • To verify the encoding outcome, utilize the CoderResult object.

Java




// Java program to demonstrate the use of CoderResult class
  
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CoderResult;
  
public class Coder {
  
    // Main method
    public static void main(String[] args)
    {
        try {
            
            // Initialize the charset and encoder
            Charset charset = Charset.forName("UTF-8");
            CharsetEncoder encoder = charset.newEncoder();
  
            // Create the input and output buffers for encoding
            CharBuffer inputBuffer= CharBuffer.wrap("GeeksforGeeks");
            ByteBuffer outputBuffer= ByteBuffer.allocate(20);
  
            // Encode the input buffer into the output buffer
            CoderResult result = encoder.encode(
                inputBuffer, outputBuffer, true);
  
            // Check if encoding is successful
            if (result.isUnderflow()) {
                
                // Print the output buffer
                System.out.println("Encoding successful: "
                                   + outputBuffer.flip());
            }
            
            // Check for overflow condition
            else if (result.isOverflow()) {
                
                // Print the error message
                System.err.println(
                    "Output buffer overflow");
            }
            
            // Check for error condition
            else {
                result.throwException();
            }
        }
        // Catch the exception
        catch (CharacterCodingException e) {
            e.printStackTrace();
        }
    }
}


Output

Encoding successful: java.nio.HeapByteBuffer[pos=0 lim=13 cap=20]



Explanation of the above program:

  • To encode UTF-8 data, the application initializes a Charset instance and a CharsetEncoder.
  • To store the encoded result and the input string, char and byte buffers called inputBuffer and outputBuffer, respectively are created.
  • To encode the characters from the input buffer into the output buffer, the CharsetEncoder’s encode() method is called.
  • To verify the result of the encoding process, utilize the CoderResult object (result).
  • It looks for underflow (successful encoding) first, overflow (insufficient space in the output buffer), and error.

The output buffer is flipped to print the encoded result if the encoding process is successful. An error message is printed in the event that there is not enough space in the output buffer. The throwException() method of CoderResult is triggered in the event of an encoding error, throwing a CharacterCodingException. The catch block handles this exception and prints the stack trace.

Uses of the CoderResult class

Now that we have a basic understanding of this class, let us look at some of the actual use-cases of the same to understand it in a better way.

  • Outcome Reporting: To report the outcomes of character encoding and decoding operations, use CoderResult. It contains details about whether the operation was successful, encountered an error, or ran into particular problems, such as buffer overflow
  • Error Handling: CoderResult offers an exception handling mechanism in case of an error during encoding or decoding. Developers can handle and respond to encoding or decoding errors gracefully by invoking the throwException() method to throw a CharacterCodingException
  • Integration with Charset APIs: It easily interacts with CharsetEncoder and CharsetDecoder, two classes in the java.nio.charset package. To convey the outcome of encoding and decoding attempts, these classes make use of CoderResult instances
  • Status Checking: The CoderResult class offers a number of methods, including isUnderflow(), isOverflow(), isMalformed(), and isUnmappable(), that make it easy to monitor the progress of an encoding or decoding operation. These methods let developers run code conditionally depending on how a particular operation turns out.
  • Buffer Management: By indicating if there is
    • underflow (insufficient input in the source buffer),
    • overflow (insufficient space in the destination buffer),
    • or other error conditions, it helps with buffer management.

This helps developers in taking the proper steps, like resizing buffers or customizing error handling



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads