Calendar set(int, int) in Java

set(int, int): This method is available in java.util.Calendar 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.Calendar;

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

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

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

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=0,WEEK_OF_YEAR=5,WEEK_OF_MONTH=5,DAY_OF_MONTH=23,DAY_OF_YEAR=23,DAY_OF_WEEK=1,DAY_OF_WEEK_IN_MONTH=4,AM_PM=1,HOUR=10,HOUR_OF_DAY=22,MINUTE=25,SECOND=22,MILLISECOND=372,ZONE_OFFSET=19800000,DST_OFFSET=0]



Approach 2: ArrayIndexOutOfBoundsException 

Java

import java.util.Calendar;

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

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

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

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