Saturday, October 4, 2025
HomeLanguagesJavaCalendar set() Method in Java with Examples

Calendar set() Method in Java with Examples

The set(int calndr_field, int new_val) method in Calendar class is used to set the calndr_field value to a new_val. The older field of this calendar get replaced by a new field.

Syntax:

public void set(int calndr_field, int new_val)

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 altered.
  • new_val: This refers to the new value that is to be replaced with.

Return Value: The method does not return any value.

Below programs illustrate the working of set() Method of Calendar class:
Example 1:




// Java code to illustrate
// set() 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));
  
        // Replacing with a new value
        calndr.set(Calendar.MONTH, 11);
  
        // Displaying the modified result
        System.out.println("Altered Month is: "
                           + calndr.get(
                                 Calendar.MONTH));
    }
}


Output:

The Current Month is: 1
Altered Month is: 11

Example 2:




// Java code to illustrate
// set() 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));
  
        // Replacing with a new value
        calndr.set(Calendar.YEAR, 1996);
  
        // Displaying the modified result
        System.out.println("Altered year is: "
                           + calndr.get(
                                 Calendar.YEAR));
    }
}


Output:

The Current year is: 2019
Altered year is: 1996

Reference: https://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html#set-int-int-

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32335 POSTS0 COMMENTS
Milvus
86 POSTS0 COMMENTS
Nango Kala
6705 POSTS0 COMMENTS
Nicole Veronica
11869 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11932 POSTS0 COMMENTS
Shaida Kate Naidoo
6821 POSTS0 COMMENTS
Ted Musemwa
7086 POSTS0 COMMENTS
Thapelo Manthata
6778 POSTS0 COMMENTS
Umr Jansen
6778 POSTS0 COMMENTS