Oswald Oswald - 1 year ago 38
Java Question

Static Variables Not Affecting Other Objects in Java Calendar Class

Since the

class in Java has static data fields such as
, why don't the other objects change when the static field is modified?
I have made two different Gregorian Calendars and thought static data fields changed the value for all of the objects instead of one.

import java.util.Calendar;
import java.util.GregorianCalendar;

public class TEST {
public static void main(String[] args) {

GregorianCalendar cal = new GregorianCalendar();


GregorianCalendar cal2 = new GregorianCalendar();

cal2.set(Calendar.DATE, 12);



Answer Source

Calendar.DATE is not a static field, it's a static variable that's used to reference which type of value you want to set/get in a specific Calendar instance.

If you look at the actual source code of java.util.Calendar you would see that it has an internal int array that holds all the values, i.e. day, month, year, etc.

Calendar.DATE is just a nice way of referencing the fifth element of that array.

Declaration of member in the Java 8 source code.

 * Field number for <code>get</code> and <code>set</code> indicating the
 * day of the month. This is a synonym for <code>DAY_OF_MONTH</code>.
 * The first day of the month has value 1.
 * @see #DAY_OF_MONTH
public final static int DATE = 5;