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



Similar Reads

java.nio.charset.Charset Class in Java
In Java, Charset is a mapping technique used in Java to map the 16-bit Unicode sequence and sequences of bytes. It is also used to encode and decode the string data text into different character encoding. It comes under java.nio.charset.Charset package. The charset must begin with a number or letter. Every charset can decode and encode. For constru
2 min read
java.nio.charset.CharsetEncoder Class in Java
For the purpose of character encoding and decoding, java offers a number of classes in the 'java.nio.charset' package. The 'CharsetEncoder' class of this package performs the important task of encoding. In this article, let us understand this class, its syntax, different methods, and some examples of error handling and optimization techniques. What
6 min read
java.nio.charset.CodingErrorAction Class in Java
In Java programming, Character encoding plays an important when we talk about handling data and information across different systems. The java.nio.charset package contains classes for managing character encoding and decoding. CodingErrorAction class is one of the package's core classes. This class describes the actions to be taken when an encoding
2 min read
java.nio.CharBuffer Class in Java
CharBuffer holds a sequence of integer values to be used in an I/O operation. The CharBuffer class provides the following four categories of operations upon long buffers: Absolute and relative get method that read single Chars.Absolute and relative put methods that write single Chars.Relative bulk put and get methods that transfer contiguous sequen
4 min read
java.nio.IntBuffer Class in Java
IntBuffer holds a sequence of integer values to be used in an I/O operation. The IntBuffer class provides the following four categories of operations upon long buffers: Absolute and relative get method that read single ints.Absolute and relative put methods that write single ints.Relative bulk put and get methods that transfer contiguous sequences
4 min read
java.nio.file.attribute.FileTime Class in Java
The java.nio.file.attribute.FileTime class is used to get a value representing this file's timestamp i.e, the time when this file was last modified, accessed, or created. Class Declaration: public final class FileTime extends Object implements Comparable<FileTime>Methods: MethodDescriptioncompareTo(FileTime other)This method compares the valu
2 min read
java.nio.file.SimpleFileVisitor Class in Java
The java.nio.file.SimpleFileVisitor Class is used to visit all the files in a directory and to re-throw I/O exceptions whenever an I/O error occurs. Class declaration : public class SimpleFileVisitor<T> extends Object implements FileVisitor<T>Constructor: protected SimpleFileVIsitor(): Creates a new object of SimpleFileVisitor class.Met
3 min read
java.nio.file.Paths Class in Java
java.nio.file.Paths class contains static methods for converting path string or URI into Path. Class declaration : public final class Paths extends ObjectMethods: MethodDescriptionget(String first, String... more) This method converts a path string, or a sequence of strings that when joined form a path string, to a Path. get(URI uri) This method co
2 min read
java.nio.FloatBuffer Class in Java
A Buffer object can be termed as a container for a fixed amount of data. The buffer acts as a storing box, or temporary staging area, where data can be stored and later retrieved according to the usage. Java Buffer classes are the foundation or base upon which java.nio is built. Float buffers are created either by allocation, which allocates space
4 min read
java.nio.LongBuffer Class in Java
LongBuffer holds a sequence of long values to be used in an I/O operation. The LongBuffer class provides the following four categories of operations upon long buffers: Absolute and relative get and put methods that read and write single longs.Relative bulk get methods that transfer contiguous sequences of longs from this buffer into an array.Relati
5 min read