Charset forName() method in Java with Examples
The forName() method is a built-in method of the java.nio.charset returns a charset object for the named charset. In this function we pass a canonical name or an alias and its respective charset name is returned.
public static Charset forName?(String charsetName)
Parameters: The function accepts a single mandatory parameter charsetName which specifies the canonical name or the alias name whose object name is to be returned.
Return Value: The function returns a charset object for the named charset.
Errors and Exceptions: The function throws three exceptions as shown below:
- IllegalCharsetNameException: It is thrown if the given charset name is illegal
- IllegalArgumentException : It is thrown if the given charsetName is null
- UnsupportedCharsetException : It is thrown if no support for the named charset is available in this instance of the Java virtual machine
Below is the implementation of the above function:
The name for ISO-2022-CN is ISO-2022-CN
The name for UTF16 is UTF-16
The exception is: java.nio.charset.IllegalCharsetNameException:
The exception is: java.nio.charset.UnsupportedCharsetException: gopal
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.