GregorianCalendar set(int, int) in Java

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

Syntax:

void java.util.Calendar.set(int field, int value)

This method takes two arguments of type int as its parameters. This method sets the given calendar field to the given value.

Parameters: Two parameters are required for this method.

field: the given calendar field.

value: the value to be set for the given calendar field.

Throws:

ArrayIndexOutOfBoundsException - if the specified field is out of range(field < 0 || field >= FIELD_COUNT).in non-lenient mode.

Approach 1: When no exception

Java

import java.util.GregorianCalendar;

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

        GregorianCalendar cal = new GregorianCalendar();

        int field = 1, value = 10;
        cal.set(field, value);
        System.out.println(cal);
    }
}

Output:

java.util.GregorianCalendar[time=?,areFieldsSet=false,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Calcutta",offset=19800000,dstSavings=0,useDaylight=false,transitions=7,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=10,MONTH=1,WEEK_OF_YEAR=8,WEEK_OF_MONTH=3,DAY_OF_MONTH=18,DAY_OF_YEAR=49,DAY_OF_WEEK=6,DAY_OF_WEEK_IN_MONTH=3,AM_PM=0,HOUR=8,HOUR_OF_DAY=8,MINUTE=50,SECOND=58,MILLISECOND=567,ZONE_OFFSET=19800000,DST_OFFSET=0]


Approach 2: ArrayIndexOutOfBoundsException 

Java

import java.util.GregorianCalendar;

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

        GregorianCalendar cal = new GregorianCalendar();

        int field = -1, value = 10;
        cal.set(field, value);
        System.out.println(cal);
    }
}

Output:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 17 at java.base/java.util.Calendar.internalSet(Calendar.java:1888) at java.base/java.util.Calendar.set(Calendar.java:1912)


No comments:

Post a Comment