GregorianCalendar getDisplayName(int, int, Locale) in Java

getDisplayName(int, int, Locale): This method is available in java.util.GregorianCalendar class of Java.

Syntax:

String java.util.Calendar.getDisplayName(int field, int style, Locale locale)

This method takes three arguments. This method returns the string representation of the calendar field value in the given style and locale.

Parameters: Three parameters are required for this method.

field: the calendar field for which the string representation is returned.

style: the style applied to the string representation; one of SHORT_FORMAT (SHORT), SHORT_STANDALONE, LONG_FORMAT (LONG), LONG_STANDALONE, NARROW_FORMAT, or NARROW_STANDALONE.

locale: the locale for the string representation.

Returns: the string representation of the given field in the given style, or null if no string representation is applicable.

Throws:

1.IllegalArgumentException - if the field or style is invalid, or if this Calendar is non-lenient and any of the calendar fields have invalid values.

2. NullPointerException - if the locale is null.

Approach 1: When no exception

Java

import java.util.GregorianCalendar;
import java.util.Locale;

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

        GregorianCalendar cal = new GregorianCalendar();

        int field = 0, style = 1;
        Locale locale = Locale.US;

        System.out.println(cal.getDisplayName(field,
style, locale));
    }
}

Output:

AD


Approach 2: IllegalArgumentException 

Java

import java.util.GregorianCalendar;
import java.util.Locale;

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

        GregorianCalendar cal = new GregorianCalendar();

        int field = -1, style = 1;
        Locale locale = Locale.US;

        System.out.println(cal.getDisplayName(field,
style, locale));
    }
}

Output:

Exception in thread "main" java.lang.IllegalArgumentException at java.base/java.util.Calendar.checkDisplayNameParams(Calendar.java:2252) at java.base/java.util.Calendar.getDisplayName(Calendar.java:2112)



Approach 3: NullPointerException 

Java

import java.util.GregorianCalendar;
import java.util.Locale;

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

        GregorianCalendar cal = new GregorianCalendar();

        int field = 0, style = 1;
        Locale locale = null;

        System.out.println(cal.getDisplayName(field,
style, locale));
    }
}

Output:

Exception in thread "main" java.lang.NullPointerException at java.base/java.util.Calendar.checkDisplayNameParams(Calendar.java:2255) at java.base/java.util.Calendar.getDisplayName(Calendar.java:2112)


No comments:

Post a Comment