Home »
Java programming language
Java GregorianCalendar roll() Method with Example
GregorianCalendar Class roll() method: Here, we are going to learn about the roll() method of GregorianCalendar Class with its syntax and example.
Submitted by Preeti Jain, on February 15, 2020
GregorianCalendar Class roll() method
Syntax:
public void roll(int fi, boolean status);
public void roll(int fi, int amt);
- roll() method is available in java.util package.
- roll(int fi, boolean status) method is used to roll up or down a single quantity of time on the given time field (fi).
- roll(int fi, int amt) method is used to roll up or down the given time field (fi) with the given amt (amount) of time.
- These methods may throw an exception at the time of rolling the given field (fi).
IllegalArgumentException: This exception may throw when the given field (fi) is not in a range in non-lenient mode.
- These are non-static methods, so it is accessible with the class object and if we try to access these methods with the class name then we will get an error.
Parameter(s):
-
In the first case, roll(int fi, boolean status)
- int fi – represent the calendar field.
- boolean status – sets true when the given field (fi) roll up otherwise it sets false.
-
In the first case, roll(int fi, int amt)
- int fi – represent the calendar field.
- int amt – represents the amount(amt) to add or substract to field (positive amt to add & negative amt to substract).
Return value:
In both the cases, the return type of the method is void, it does not return anything.
Example:
// Java program is to demonstrate the example of
// roll() method of GregorianCalendar
import java.util.*;
public class RollOfGregorianCalendar {
public static void main(String[] args) {
// Instantiating a GregorianCalendar object
GregorianCalendar g_ca = (GregorianCalendar) GregorianCalendar.getInstance();
// Display current GregorianCalendar
System.out.println("g_ca.getTime(): " + g_ca.getTime());
// By using roll(int,boolean) method is to
// up a single unit of the given field if
// boolean sets to true
g_ca.roll(GregorianCalendar.YEAR, true);
// Display Updated GregorianCalendar
System.out.println("g_ca.roll(GregorianCalendar.YEAR, true): " + g_ca.getTime());
// By using roll(int,int) method is to up
// or down the given field with the given
// amount of time
g_ca.roll(GregorianCalendar.MONTH, 5);
// Display Updated Calendar
System.out.println("g_ca.roll(GregorianCalendar.MONTH, 5): " + g_ca.getTime());
}
}
Output
g_ca.getTime(): Sat Feb 15 12:41:19 GMT 2020
g_ca.roll(GregorianCalendar.YEAR, true): Mon Feb 15 12:41:19 GMT 2021
g_ca.roll(GregorianCalendar.MONTH, 5): Thu Jul 15 12:41:19 GMT 2021