The roll(int calndr_field, int amt) method in Calendar class is used to operate on the passed calendar field by adding the passed amount to a specific calendar field without the alteration of large field values.
Note: The positive amount must be added and the negative amount must be subtracted.
Syntax:
public void roll(int calndr_field, int amt)
Parameters: The method takes two parameters:
- calndr_field: This is of Calendar type and refers to the field of the calendar that is to be operated upon.
- amt: This is of the Integer type that is to be added or subtracted depending upon the sign of the value.
Return Value: The method does not return any value.
Below programs illustrate the working of roll() Method of Calendar class:
Example 1:
// Java code to illustrate // isSet() method import java.util.*;
public class Calendar_Demo {
public static void main(String args[])
{
// Creating a calendar
Calendar calndr = Calendar.getInstance();
// Displaying the year
System.out.println( "The Current Year"
+ " is: "
+ calndr.get(
Calendar.YEAR));
// Decrementing the year
// by 5
calndr.roll(Calendar.YEAR, - 5 );
// Displaying the result after the operation
System.out.println( "The New Year is: "
+ calndr.get(
Calendar.YEAR));
// Incrementing the year
// by 2
calndr.roll(Calendar.YEAR, 2 );
// Displaying the result after operation
System.out.println( "The new year is: "
+ calndr.get(
Calendar.YEAR));
}
} |
The Current Year is: 2019 The New Year is: 2014 The new year is: 2016
Example 2:
// Java code to illustrate // isSet() method import java.util.*;
public class Calendar_Demo {
public static void main(String args[])
{
// Creating a calendar
Calendar calndr = Calendar.getInstance();
// Displaying the month
System.out.println( "The Current Month"
+ " is: "
+ calndr.get(
Calendar.MONTH));
// Incrementing the month
// by 3
calndr.roll(Calendar.MONTH, 3 );
// Displaying the result after operation
System.out.println( "The New Month is: "
+ calndr.get(
Calendar.MONTH));
// Decrementing the month
// by 1
calndr.roll(Calendar.MONTH, - 1 );
// Displaying the result after operation
System.out.println( "The new month is: "
+ calndr.get(
Calendar.MONTH));
}
} |
The Current Month is: 2 The New Month is: 5 The new month is: 4
Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#roll(int, %20int)