Let's dissect these:
This:
System.out.println(cal.toString());
prints out the toString()
for your Calendar object, the state of its fields, and returns this:
java.util.GregorianCalendar[time=?,areFieldsSet=false,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Etc/UTC",offset=0,dstSavings=0,useDaylight=false,transi
tions=0,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2019,MONTH=1,WEEK_OF_YEAR=7,WEEK_OF_MONTH=3,DAY_OF_MONTH=15,DAY_OF_YEAR=46,DAY_OF_WEEK=6,DAY_OF_WEEK_IN
_MONTH=3,AM_PM=0,HOUR=11,HOUR_OF_DAY=11,MINUTE=38,SECOND=14,MILLISECOND=374,ZONE_OFFSET=0,DST_OFFSET=0]
And yes, here DAY_OF_WEEK is 6
While this:
System.out.println(cal.DAY_OF_WEEK); //7 which is unchanged by cal.set
returns the Calendar.DAY_OF_WEEK
field result, which is a constant and is == to 7.
Finally this:
System.out.println(cal.get(cal.DAY_OF_WEEK)); //6
returns 6, which is the DAY_OF_WEEK field held by your Calendar object.
Picture your Calendar object (simplified) to look like this:
public abstract class Calendar {
public static int DAY_OF_WEEK = 7; // a constant that never changes
// ..... many more fields
// field name may be different
private int dayOfWeek = 0; // or some other default value
public void set(...) {
// sets the dayOfWeek value
}
public int get(int ) {
if (field == DAY_OF_WEEK) {
return this.dayOfWeek;
}
// .... more code
}
public String toString() {
return .... + "DAY_OF_WEEK:" + dayOfWeek + .....;
}
}
make sense now? There is a hidden dayOfWeek field that you're setting and getting the result of
So this:
System.out.println(cal.get(cal.DAY_OF_WEEK));
actually returns the dayOfWeek
private field result