Open In App

java.nio.charset.CoderResult Class in Java

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 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.

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.

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.




// 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:

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.

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


Article Tags :