java.util.Calendar get(int field)

Description :

This java tutorial shows how to use the get(int field) method of Calendar class of java.util package. This method returns the value of the given calendar field.

Method Syntax :

public int get(int field)

Parameter Input :

DataType Parameter Description
int field the given Calendar field.

Method Returns :

This method returns returns the value of the given calendar field

Compatibility Version :

Requires Java 1.1 and up

Exception :

ArrayIndexOutOfBoundsException

– will be thrown by this method if we specify a method argument that is outside of its range.

Discussion :

The Calender get(int field) method is used to get the value at the specified Calendar field as method argument. Like for example if we want to get the value of the year specified by the Calendar object we would be leveraging the static field of this class Calendar.YEAR. The Calendar.Year would be returning an int value of 1. If we input this value to the get(int field), we would be getting the actual year of this Calendar object.

Java Code Example :

This java example source code demonstrates the use of get(int field) method of Calendar class. Basically we print first the time and we experimented on putting fields of Calendar object.

package com.javatutorialhq.java.examples;

import java.util.Calendar;

/* * This example source code demonstrates the use of * get(int field) method of Calendar class */

public class CalendarGetExample {

public static void main(String

[] args) throws InterruptedException {

Calendar cal = Calendar.getInstance();

// Printing the date System.out.println("Current Time:"+cal.getTime());

// Getting the desired parameters System.out.println("Field 1:"+cal.get(1)); System.out.println("Field YEAR:"+cal.get(Calendar.YEAR)); System.out.println("Field Month:"+cal.get(Calendar.MONTH)); System.out.println("Field Day:"+cal.get(Calendar.DAY_OF_MONTH)); System.out.println("Field Hour:"+cal.get(Calendar.HOUR)); System.out.println("Field Minute:"+cal.get(Calendar.MINUTE)); System.out.println("Field Second:"+cal.get(Calendar.SECOND));

}

}

Sample Output :

Running the get(int field) method example source code of Calendar class will give you the following output:

Calendar get(int field) method example

Calendar get(int field) method example

Exception Scenario :

Current Time:Mon Jan 19 21:23:19 CST 2015
Field 1:2015
Field YEAR:2015
Field Month:0
Field Day:19
Field Hour:9
Field Minute:23
Field Second:19
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 100
	at java.util.Calendar.internalGet(Calendar.java:1840)
	at java.util.Calendar.get(Calendar.java:1827)
	at com.javatutorialhq.java.examples.CalendarGetExample.main(CalendarGetExample.java:27)

Similar Method :

  • set(int,int)
  • complete()

Suggested Reading List :

References :