The roll(int calndr_field, boolean up_down) method in Calendar class is used to operate on the passed calendar field by moving the passed field, up or down by a single unit of time. This involves addition or subtraction of the time field without changing the larger fields.
Syntax:
Java
Java
public abstract void roll(int calndr_field, boolean up_down)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.
- up_down: This is of the boolean type that is used to indicate whether to move calndr_field up or down or to increase or decrease. The true indicates adding a unit of time and false subtracts the same.
// 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
// false indicates subtraction
calndr.roll(Calendar.YEAR, false);
// Displaying the result after operation
System.out.println("The New Year is: "
+ calndr.get(
Calendar.YEAR));
// Incrementing the year
// true indicates addition
calndr.roll(Calendar.YEAR, true);
// Displaying the result after operation
System.out.println("The new year is: "
+ calndr.get(
Calendar.YEAR));
}
}
Output:
Example 2:
The Current Year is: 2019 The New Year is: 2018 The new year is: 2019
// 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
// true indicates addition
calndr.roll(Calendar.MONTH, true);
// Displaying the result after operation
System.out.println("The New Month is: "
+ calndr.get(
Calendar.MONTH));
// Decrementing the month
// false indicates subtraction
calndr.roll(Calendar.MONTH, false);
// Displaying the result after operation
System.out.println("The new month is: "
+ calndr.get(
Calendar.MONTH));
}
}
Output:
Reference: https://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html#roll-int-boolean-The Current Month is: 1 The New Month is: 2 The new month is: 1