Month of() method in Java

The of() method is a built-in method of the Month ENUM which is used to generate a Month instance from an integer value. The integer value should be in the range 1-12 representing any of the 12 months and the method generates a Month instance from it representing a month-of-year.

Syntax:

public static Month of(int month)

Parameters: This method accepts a single parameter month, which is of integer type.

Return Value: This method returns the corresponding Month instance generated using the parameter passed.

Exception: This method throws a DateTimeException if the month of year passed to the parameter is not valid.



Below programs illustrate the above method:

Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

import java.time.*;
import java.time.Month;
import java.time.temporal.ChronoField;
  
class monthEnum {
    public static void main(String[] args)
    {
        // Create a month instance
        Month month = Month.of(2);
  
        // Print the month Instance
        System.out.println(month);
    }
}

chevron_right


Output:

FEBRUARY

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

import java.time.*;
import java.time.Month;
import java.time.temporal.ChronoField;
  
class monthEnum {
    public static void main(String[] args)
    {
        // Create a month instance
        Month month = Month.of(12);
  
        // Print the month Instance
        System.out.println(month);
    }
}

chevron_right


Output:

DECEMBER

Reference: https://docs.oracle.com/javase/8/docs/api/java/time/Month.html#of-int-

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.