java.nio.charset.CoderResult Class in Java
Last Updated :
08 Dec, 2023
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:
|
OVERFLOW
| An overflow result object indicates that there is not enough space in the output buffer.
|
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.
|
isError()
| Indicates if this object represents an error condition or not.
|
isMalformed()
| Indicates if the object in question represents a malformed input error or not.
|
isOverflow()
| Shows whether the object represents an overflow situation or not.
|
isUnderflow()
| Shows whether the object represents an underflow situation or not.
|
isUnmappable()
| Denotes if the object corresponds to an unmappable character error or not.
|
length()
| It returns the length of the incorrect input that this object (optional operation) described.
|
malformedForLength(int length)
| A static factory method that provides a unique object expressing a given length malformed input error.
|
throwException()
| It throws an exception suitable for the outcome this object describes.
|
toString()
| Returns a string that describes the result of the Coder.
|
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();
}
}
}
OutputEncoding 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 Tutorial Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. It is known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Java s
10 min read
Java OOP(Object Oriented Programming) Concepts Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it,
13 min read
Java Interview Questions and Answers Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Arrays in Java Arrays in Java are one of the most fundamental data structures that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of me
15+ min read
Collections in Java Any group of individual objects that are represented as a single unit is known as a Java Collection of Objects. In Java, a separate framework named the "Collection Framework" has been defined in JDK 1.2 which holds all the Java Collection Classes and Interface in it. In Java, the Collection interfac
15+ min read
Inheritance in Java Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from an
13 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Java Exception Handling Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc. An Exception is an unwanted or unexpected event that occurs during the execution of a program, i.e., at runt
10 min read
Java Programs - Java Programming Examples In this article, we will learn and prepare for Interviews using Java Programming Examples. From basic Java programs like the Fibonacci series, Prime numbers, Factorial numbers, and Palindrome numbers to advanced Java programs.Java is one of the most popular programming languages today because of its
8 min read