I tried to run your code and it prints 7 each time (even tried to uncomment this line). What seems right to me.
EDIT Problem explained in detail Java Calendar - Date unpredictable after setting day_of_week
I'm glad that with Java 8 a new API for working with date and time has appeared.
EDIT2
My understanding of what happened:
Only reasonable combinations
YEAR + MONTH + DATE (let call it A)
or
YEAR + MONTH + WEEK_OF_MONTH + DAY_OF_WEEK (let call it B)
And the calendar has its internal state in which he thinks. Therefore, before installing
DAY_OF_WEEK
you worked with combination A, but after that you worked with combination B and this line
tmp.set(Calendar.DAY_OF_MONTH, 4);
was ignored. Thus, this happened on Monday in the first week of August (2015-07-27). But when did you call
tmp.get(Calendar.MONTH);
you “materialized” the date in accordance with combination A (until 2015-08-04) and
DAY_OF_WEEK
has been installed "correctly" since 2015-08-04.
Anyway, could you try this with JDK 8?
source share