Charset.forName() in Java

Charset.forName(): This method is available in java.nio.charset.Charset class of Java.

Syntax:

Charset java.nio.charset.Charset.forName(String charsetName)

This method takes one argument of type String as its parameter. This method returns a charset object for the named charset.

Parameters: One parameter is required for this method.

charsetName: The name of the requested charset; may be either a canonical name or an alias.

Returns: A charset object for the named charset.

Throws:

1. IllegalCharsetNameException - If the given charset name is illegal.
2. IllegalArgumentException - If the given charsetName is null.
3. UnsupportedCharsetException - If no support for the named charset is available in this instance of the Java virtual machine

Approach 1: No exceptions

Java

import java.nio.charset.Charset;

public class CharsetforName {
    public static void main(String[] args) {

        String charsetName = "UTF-8";
        System.out.println(Charset.forName(charsetName));
    }
}

Output:

UTF-8


Approach 2: IllegalCharsetNameException 

Java

import java.nio.charset.Charset;

public class CharsetforName {
    public static void main(String[] args) {

        String charsetName = "";
        System.out.println(Charset.forName(charsetName));
    }
}


Output:

Exception in thread "main" java.nio.charset.IllegalCharsetNameException: at java.base/java.nio.charset.Charset.checkName(Charset.java:293) at java.base/java.nio.charset.Charset.lookup2(Charset.java:479) at java.base/java.nio.charset.Charset.lookup(Charset.java:459) at java.base/java.nio.charset.Charset.forName(Charset.java:523)



Approach 3: IllegalArgumentException 

Java

import java.nio.charset.Charset;

public class CharsetforName {
    public static void main(String[] args) {

        String charsetName = null;
        System.out.println(Charset.forName(charsetName));
    }
}


Output:

Exception in thread "main" java.lang.IllegalArgumentException: Null charset name at java.base/java.nio.charset.Charset.lookup(Charset.java:452) at java.base/java.nio.charset.Charset.forName(Charset.java:523)



Approach 4: UnsupportedCharsetException 

Java

import java.nio.charset.Charset;

public class CharsetforName {
    public static void main(String[] args) {

        String charsetName = "UTF-99";
        System.out.println(Charset.forName(charsetName));
    }
}


Output:

Exception in thread "main" java.nio.charset.UnsupportedCharsetException: UTF-99 at java.base/java.nio.charset.Charset.forName(Charset.java:526)


No comments:

Post a Comment