Calendar getDisplayName(int, int, Locale) in Java

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

Syntax:

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

This method takes three arguments two of type int and the other one of type Locale as its parameters. 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.Calendar;
import java.util.Locale;

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

        // create a calendar
        Calendar calendar = Calendar.getInstance();

        int field = 1, style = 2;
        Locale locale = Locale.ENGLISH;
        System.out.println(calendar.getDisplayName(field,
style, locale));

    }
}

Output:

null


Approach 2: IllegalArgumentException

Java

import java.util.Calendar;
import java.util.Locale;

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

        // create a calendar
        Calendar calendar = Calendar.getInstance();

        int field = -1, style = 2;
        Locale locale = Locale.ENGLISH;
        System.out.println(calendar.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.Calendar;
import java.util.Locale;

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

        // create a calendar
        Calendar calendar = Calendar.getInstance();

        int field = 1, style = 2;
        Locale locale = null;
        System.out.println(calendar.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