1 /*
  2  * Copyright (c) 2012, 2025, Oracle and/or its affiliates. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.  Oracle designates this
  8  * particular file as subject to the "Classpath" exception as provided
  9  * by Oracle in the LICENSE file that accompanied this code.
 10  *
 11  * This code is distributed in the hope that it will be useful, but WITHOUT
 12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 14  * version 2 for more details (a copy is included in the LICENSE file that
 15  * accompanied this code).
 16  *
 17  * You should have received a copy of the GNU General Public License version
 18  * 2 along with this work; if not, write to the Free Software Foundation,
 19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 20  *
 21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 22  * or visit www.oracle.com if you need additional information or have any
 23  * questions.
 24  */
 25 
 26 /*
 27  * This file is available under and governed by the GNU General Public
 28  * License version 2 only, as published by the Free Software Foundation.
 29  * However, the following notice accompanied the original version of this
 30  * file:
 31  *
 32  * Copyright (c) 2007-2012, Stephen Colebourne & Michael Nascimento Santos
 33  *
 34  * All rights reserved.
 35  *
 36  * Redistribution and use in source and binary forms, with or without
 37  * modification, are permitted provided that the following conditions are met:
 38  *
 39  *  * Redistributions of source code must retain the above copyright notice,
 40  *    this list of conditions and the following disclaimer.
 41  *
 42  *  * Redistributions in binary form must reproduce the above copyright notice,
 43  *    this list of conditions and the following disclaimer in the documentation
 44  *    and/or other materials provided with the distribution.
 45  *
 46  *  * Neither the name of JSR-310 nor the names of its contributors
 47  *    may be used to endorse or promote products derived from this software
 48  *    without specific prior written permission.
 49  *
 50  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 51  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 52  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 53  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 54  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 55  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 56  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 57  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 58  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 59  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 60  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 61  */
 62 package java.time;
 63 
 64 import static java.time.temporal.ChronoField.DAY_OF_MONTH;
 65 import static java.time.temporal.ChronoField.MONTH_OF_YEAR;
 66 
 67 import java.io.DataInput;
 68 import java.io.DataOutput;
 69 import java.io.IOException;
 70 import java.io.InvalidObjectException;
 71 import java.io.ObjectInputStream;
 72 import java.io.ObjectStreamField;
 73 import java.io.Serial;
 74 import java.io.Serializable;
 75 import java.time.chrono.Chronology;
 76 import java.time.chrono.IsoChronology;
 77 import java.time.format.DateTimeFormatter;
 78 import java.time.format.DateTimeFormatterBuilder;
 79 import java.time.format.DateTimeParseException;
 80 import java.time.temporal.ChronoField;
 81 import java.time.temporal.Temporal;
 82 import java.time.temporal.TemporalAccessor;
 83 import java.time.temporal.TemporalAdjuster;
 84 import java.time.temporal.TemporalField;
 85 import java.time.temporal.TemporalQueries;
 86 import java.time.temporal.TemporalQuery;
 87 import java.time.temporal.UnsupportedTemporalTypeException;
 88 import java.time.temporal.ValueRange;
 89 import java.util.Objects;
 90 
 91 import jdk.internal.util.DecimalDigits;
 92 
 93 /**
 94  * A month-day in the ISO-8601 calendar system, such as {@code --12-03}.
 95  * <p>
 96  * {@code MonthDay} is an immutable date-time object that represents the combination
 97  * of a month and day-of-month. Any field that can be derived from a month and day,
 98  * such as quarter-of-year, can be obtained.
 99  * <p>
100  * This class does not store or represent a year, time or time-zone.
101  * For example, the value "December 3rd" can be stored in a {@code MonthDay}.
102  * <p>
103  * Since a {@code MonthDay} does not possess a year, the leap day of
104  * February 29th is considered valid.
105  * <p>
106  * This class implements {@link TemporalAccessor} rather than {@link Temporal}.
107  * This is because it is not possible to define whether February 29th is valid or not
108  * without external information, preventing the implementation of plus/minus.
109  * Related to this, {@code MonthDay} only provides access to query and set the fields
110  * {@code MONTH_OF_YEAR} and {@code DAY_OF_MONTH}.
111  * <p>
112  * The ISO-8601 calendar system is the modern civil calendar system used today
113  * in most of the world. It is equivalent to the proleptic Gregorian calendar
114  * system, in which today's rules for leap years are applied for all time.
115  * For most applications written today, the ISO-8601 rules are entirely suitable.
116  * However, any application that makes use of historical dates, and requires them
117  * to be accurate will find the ISO-8601 approach unsuitable.
118  * <p>
119  * This is a <a href="{@docRoot}/java.base/java/lang/doc-files/ValueBased.html">value-based</a>
120  * class; programmers should treat instances that are {@linkplain #equals(Object) equal}
121  * as interchangeable and should not use instances for synchronization, mutexes, or
122  * with {@linkplain java.lang.ref.Reference object references}.
123  *
124  * <div class="preview-block">
125  *      <div class="preview-comment">
126  *          When preview features are enabled, {@code MonthDay} is a {@linkplain Class#isValue value class}.
127  *          Use of value class instances for synchronization, mutexes, or with
128  *          {@linkplain java.lang.ref.Reference object references} result in
129  *          {@link IdentityException}.
130  *      </div>
131  * </div>
132  *
133  * @implSpec
134  * This class is immutable and thread-safe.
135  *
136  * @since 1.8
137  */
138 @jdk.internal.ValueBased
139 @jdk.internal.MigratedValueClass
140 public final class MonthDay
141         implements TemporalAccessor, TemporalAdjuster, Comparable<MonthDay>, Serializable {
142 
143     /**
144      * Serialization version.
145      */
146     @java.io.Serial
147     private static final long serialVersionUID = -939150713474957432L;
148 
149     /**
150      * For backward compatibility of the serialized {@code MonthDay.class} object,
151      * explicitly declare the types of the serialized fields as defined in Java SE 8.
152      * Instances of {@code MonthDay} are serialized using the dedicated
153      * serialized form by {@code writeReplace}.
154      * @serialField month int The month-of-year.
155      * @serialField day int The day-of-month.
156      */
157     @Serial
158     private static final ObjectStreamField[] serialPersistentFields = {
159             new ObjectStreamField("month", int.class),
160             new ObjectStreamField("day", int.class)
161     };
162     /**
163      * Parser.
164      */
165     private static final DateTimeFormatter PARSER = new DateTimeFormatterBuilder()
166         .appendLiteral("--")
167         .appendValue(MONTH_OF_YEAR, 2)
168         .appendLiteral('-')
169         .appendValue(DAY_OF_MONTH, 2)
170         .toFormatter();
171 
172     /**
173      * @serial The month-of-year.
174      */
175     private final transient byte month;
176     /**
177      * @serial The day-of-month.
178      */
179     private final transient byte day;
180 
181     //-----------------------------------------------------------------------
182     /**
183      * Obtains the current month-day from the system clock in the default time-zone.
184      * <p>
185      * This will query the {@link Clock#systemDefaultZone() system clock} in the default
186      * time-zone to obtain the current month-day.
187      * <p>
188      * Using this method will prevent the ability to use an alternate clock for testing
189      * because the clock is hard-coded.
190      *
191      * @return the current month-day using the system clock and default time-zone, not null
192      */
193     public static MonthDay now() {
194         return now(Clock.systemDefaultZone());
195     }
196 
197     /**
198      * Obtains the current month-day from the system clock in the specified time-zone.
199      * <p>
200      * This will query the {@link Clock#system(ZoneId) system clock} to obtain the current month-day.
201      * Specifying the time-zone avoids dependence on the default time-zone.
202      * <p>
203      * Using this method will prevent the ability to use an alternate clock for testing
204      * because the clock is hard-coded.
205      *
206      * @param zone  the zone ID to use, not null
207      * @return the current month-day using the system clock, not null
208      */
209     public static MonthDay now(ZoneId zone) {
210         return now(Clock.system(zone));
211     }
212 
213     /**
214      * Obtains the current month-day from the specified clock.
215      * <p>
216      * This will query the specified clock to obtain the current month-day.
217      * Using this method allows the use of an alternate clock for testing.
218      * The alternate clock may be introduced using {@link Clock dependency injection}.
219      *
220      * @param clock  the clock to use, not null
221      * @return the current month-day, not null
222      */
223     public static MonthDay now(Clock clock) {
224         final LocalDate now = LocalDate.now(clock);  // called once
225         return MonthDay.of(now.getMonth(), now.getDayOfMonth());
226     }
227 
228     //-----------------------------------------------------------------------
229     /**
230      * Obtains an instance of {@code MonthDay}.
231      * <p>
232      * The day-of-month must be valid for the month within a leap year.
233      * Hence, for February, day 29 is valid.
234      * <p>
235      * For example, passing in April and day 31 will throw an exception, as
236      * there can never be April 31st in any year. By contrast, passing in
237      * February 29th is permitted, as that month-day can sometimes be valid.
238      *
239      * @param month  the month-of-year to represent, not null
240      * @param dayOfMonth  the day-of-month to represent, from 1 to 31
241      * @return the month-day, not null
242      * @throws DateTimeException if the value of any field is out of range,
243      *  or if the day-of-month is invalid for the month
244      */
245     public static MonthDay of(Month month, int dayOfMonth) {
246         Objects.requireNonNull(month, "month");
247         DAY_OF_MONTH.checkValidValue(dayOfMonth);
248         if (dayOfMonth > month.maxLength()) {
249             throw new DateTimeException("Illegal value for DayOfMonth field, value " + dayOfMonth +
250                     " is not valid for month " + month.name());
251         }
252         return new MonthDay(month.getValue(), dayOfMonth);
253     }
254 
255     /**
256      * Obtains an instance of {@code MonthDay}.
257      * <p>
258      * The day-of-month must be valid for the month within a leap year.
259      * Hence, for month 2 (February), day 29 is valid.
260      * <p>
261      * For example, passing in month 4 (April) and day 31 will throw an exception, as
262      * there can never be April 31st in any year. By contrast, passing in
263      * February 29th is permitted, as that month-day can sometimes be valid.
264      *
265      * @param month  the month-of-year to represent, from 1 (January) to 12 (December)
266      * @param dayOfMonth  the day-of-month to represent, from 1 to 31
267      * @return the month-day, not null
268      * @throws DateTimeException if the value of any field is out of range,
269      *  or if the day-of-month is invalid for the month
270      */
271     public static MonthDay of(int month, int dayOfMonth) {
272         return of(Month.of(month), dayOfMonth);
273     }
274 
275     //-----------------------------------------------------------------------
276     /**
277      * Obtains an instance of {@code MonthDay} from a temporal object.
278      * <p>
279      * This obtains a month-day based on the specified temporal.
280      * A {@code TemporalAccessor} represents an arbitrary set of date and time information,
281      * which this factory converts to an instance of {@code MonthDay}.
282      * <p>
283      * The conversion extracts the {@link ChronoField#MONTH_OF_YEAR MONTH_OF_YEAR} and
284      * {@link ChronoField#DAY_OF_MONTH DAY_OF_MONTH} fields.
285      * The extraction is only permitted if the temporal object has an ISO
286      * chronology, or can be converted to a {@code LocalDate}.
287      * <p>
288      * This method matches the signature of the functional interface {@link TemporalQuery}
289      * allowing it to be used as a query via method reference, {@code MonthDay::from}.
290      *
291      * @param temporal  the temporal object to convert, not null
292      * @return the month-day, not null
293      * @throws DateTimeException if unable to convert to a {@code MonthDay}
294      */
295     public static MonthDay from(TemporalAccessor temporal) {
296         if (temporal instanceof MonthDay) {
297             return (MonthDay) temporal;
298         }
299         try {
300             if (IsoChronology.INSTANCE.equals(Chronology.from(temporal)) == false) {
301                 temporal = LocalDate.from(temporal);
302             }
303             return of(temporal.get(MONTH_OF_YEAR), temporal.get(DAY_OF_MONTH));
304         } catch (DateTimeException ex) {
305             throw new DateTimeException("Unable to obtain MonthDay from TemporalAccessor: " +
306                     temporal + " of type " + temporal.getClass().getName(), ex);
307         }
308     }
309 
310     //-----------------------------------------------------------------------
311     /**
312      * Obtains an instance of {@code MonthDay} from a text string such as {@code --12-03}.
313      * <p>
314      * The string must represent a valid month-day.
315      * The format is {@code --MM-dd}.
316      *
317      * @param text  the text to parse such as "--12-03", not null
318      * @return the parsed month-day, not null
319      * @throws DateTimeParseException if the text cannot be parsed
320      */
321     public static MonthDay parse(CharSequence text) {
322         return parse(text, PARSER);
323     }
324 
325     /**
326      * Obtains an instance of {@code MonthDay} from a text string using a specific formatter.
327      * <p>
328      * The text is parsed using the formatter, returning a month-day.
329      *
330      * @param text  the text to parse, not null
331      * @param formatter  the formatter to use, not null
332      * @return the parsed month-day, not null
333      * @throws DateTimeParseException if the text cannot be parsed
334      */
335     public static MonthDay parse(CharSequence text, DateTimeFormatter formatter) {
336         Objects.requireNonNull(formatter, "formatter");
337         return formatter.parse(text, MonthDay::from);
338     }
339 
340     //-----------------------------------------------------------------------
341     /**
342      * Constructor, previously validated.
343      *
344      * @param month  the month-of-year to represent, validated from 1 to 12
345      * @param dayOfMonth  the day-of-month to represent, validated from 1 to 29-31
346      */
347     private MonthDay(int month, int dayOfMonth) {
348         this.month = (byte) month;
349         this.day = (byte) dayOfMonth;
350     }
351 
352     //-----------------------------------------------------------------------
353     /**
354      * Checks if the specified field is supported.
355      * <p>
356      * This checks if this month-day can be queried for the specified field.
357      * If false, then calling the {@link #range(TemporalField) range} and
358      * {@link #get(TemporalField) get} methods will throw an exception.
359      * <p>
360      * If the field is a {@link ChronoField} then the query is implemented here.
361      * The supported fields are:
362      * <ul>
363      * <li>{@code MONTH_OF_YEAR}
364      * <li>{@code YEAR}
365      * </ul>
366      * All other {@code ChronoField} instances will return false.
367      * <p>
368      * If the field is not a {@code ChronoField}, then the result of this method
369      * is obtained by invoking {@code TemporalField.isSupportedBy(TemporalAccessor)}
370      * passing {@code this} as the argument.
371      * Whether the field is supported is determined by the field.
372      *
373      * @param field  the field to check, null returns false
374      * @return true if the field is supported on this month-day, false if not
375      */
376     @Override
377     public boolean isSupported(TemporalField field) {
378         if (field instanceof ChronoField) {
379             return field == MONTH_OF_YEAR || field == DAY_OF_MONTH;
380         }
381         return field != null && field.isSupportedBy(this);
382     }
383 
384     /**
385      * Gets the range of valid values for the specified field.
386      * <p>
387      * The range object expresses the minimum and maximum valid values for a field.
388      * This month-day is used to enhance the accuracy of the returned range.
389      * If it is not possible to return the range, because the field is not supported
390      * or for some other reason, an exception is thrown.
391      * <p>
392      * If the field is a {@link ChronoField} then the query is implemented here.
393      * The {@link #isSupported(TemporalField) supported fields} will return
394      * appropriate range instances.
395      * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
396      * <p>
397      * If the field is not a {@code ChronoField}, then the result of this method
398      * is obtained by invoking {@code TemporalField.rangeRefinedBy(TemporalAccessor)}
399      * passing {@code this} as the argument.
400      * Whether the range can be obtained is determined by the field.
401      *
402      * @param field  the field to query the range for, not null
403      * @return the range of valid values for the field, not null
404      * @throws DateTimeException if the range for the field cannot be obtained
405      * @throws UnsupportedTemporalTypeException if the field is not supported
406      */
407     @Override
408     public ValueRange range(TemporalField field) {
409         if (field == MONTH_OF_YEAR) {
410             return field.range();
411         } else if (field == DAY_OF_MONTH) {
412             return ValueRange.of(1, getMonth().minLength(), getMonth().maxLength());
413         }
414         return TemporalAccessor.super.range(field);
415     }
416 
417     /**
418      * Gets the value of the specified field from this month-day as an {@code int}.
419      * <p>
420      * This queries this month-day for the value of the specified field.
421      * The returned value will always be within the valid range of values for the field.
422      * If it is not possible to return the value, because the field is not supported
423      * or for some other reason, an exception is thrown.
424      * <p>
425      * If the field is a {@link ChronoField} then the query is implemented here.
426      * The {@link #isSupported(TemporalField) supported fields} will return valid
427      * values based on this month-day.
428      * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
429      * <p>
430      * If the field is not a {@code ChronoField}, then the result of this method
431      * is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}
432      * passing {@code this} as the argument. Whether the value can be obtained,
433      * and what the value represents, is determined by the field.
434      *
435      * @param field  the field to get, not null
436      * @return the value for the field
437      * @throws DateTimeException if a value for the field cannot be obtained or
438      *         the value is outside the range of valid values for the field
439      * @throws UnsupportedTemporalTypeException if the field is not supported or
440      *         the range of values exceeds an {@code int}
441      * @throws ArithmeticException if numeric overflow occurs
442      */
443     @Override  // override for Javadoc
444     public int get(TemporalField field) {
445         return range(field).checkValidIntValue(getLong(field), field);
446     }
447 
448     /**
449      * Gets the value of the specified field from this month-day as a {@code long}.
450      * <p>
451      * This queries this month-day for the value of the specified field.
452      * If it is not possible to return the value, because the field is not supported
453      * or for some other reason, an exception is thrown.
454      * <p>
455      * If the field is a {@link ChronoField} then the query is implemented here.
456      * The {@link #isSupported(TemporalField) supported fields} will return valid
457      * values based on this month-day.
458      * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
459      * <p>
460      * If the field is not a {@code ChronoField}, then the result of this method
461      * is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}
462      * passing {@code this} as the argument. Whether the value can be obtained,
463      * and what the value represents, is determined by the field.
464      *
465      * @param field  the field to get, not null
466      * @return the value for the field
467      * @throws DateTimeException if a value for the field cannot be obtained
468      * @throws UnsupportedTemporalTypeException if the field is not supported
469      * @throws ArithmeticException if numeric overflow occurs
470      */
471     @Override
472     public long getLong(TemporalField field) {
473         if (field instanceof ChronoField chronoField) {
474             return switch (chronoField) {
475                 // alignedDOW and alignedWOM not supported because they cannot be set in with()
476                 case DAY_OF_MONTH -> day;
477                 case MONTH_OF_YEAR -> month;
478                 default -> throw new UnsupportedTemporalTypeException("Unsupported field: " + field);
479             };
480         }
481         return field.getFrom(this);
482     }
483 
484     //-----------------------------------------------------------------------
485     /**
486      * Gets the month-of-year field from 1 to 12.
487      * <p>
488      * This method returns the month as an {@code int} from 1 to 12.
489      * Application code is frequently clearer if the enum {@link Month}
490      * is used by calling {@link #getMonth()}.
491      *
492      * @return the month-of-year, from 1 to 12
493      * @see #getMonth()
494      */
495     public int getMonthValue() {
496         return month;
497     }
498 
499     /**
500      * Gets the month-of-year field using the {@code Month} enum.
501      * <p>
502      * This method returns the enum {@link Month} for the month.
503      * This avoids confusion as to what {@code int} values mean.
504      * If you need access to the primitive {@code int} value then the enum
505      * provides the {@link Month#getValue() int value}.
506      *
507      * @return the month-of-year, not null
508      * @see #getMonthValue()
509      */
510     public Month getMonth() {
511         return Month.of(month);
512     }
513 
514     /**
515      * Gets the day-of-month field.
516      * <p>
517      * This method returns the primitive {@code int} value for the day-of-month.
518      *
519      * @return the day-of-month, from 1 to 31
520      */
521     public int getDayOfMonth() {
522         return day;
523     }
524 
525     //-----------------------------------------------------------------------
526     /**
527      * Checks if the year is valid for this month-day.
528      * <p>
529      * This method checks whether this month and day and the input year form
530      * a valid date. This can only return false for February 29th.
531      *
532      * @param year  the year to validate
533      * @return true if the year is valid for this month-day
534      * @see Year#isValidMonthDay(MonthDay)
535      */
536     public boolean isValidYear(int year) {
537         return (day == 29 && month == 2 && Year.isLeap(year) == false) == false;
538     }
539 
540     //-----------------------------------------------------------------------
541     /**
542      * Returns a copy of this {@code MonthDay} with the month-of-year altered.
543      * <p>
544      * This returns a month-day with the specified month.
545      * If the day-of-month is invalid for the specified month, the day will
546      * be adjusted to the last valid day-of-month.
547      * <p>
548      * This instance is immutable and unaffected by this method call.
549      *
550      * @param month  the month-of-year to set in the returned month-day, from 1 (January) to 12 (December)
551      * @return a {@code MonthDay} based on this month-day with the requested month, not null
552      * @throws DateTimeException if the month-of-year value is invalid
553      */
554     public MonthDay withMonth(int month) {
555         return with(Month.of(month));
556     }
557 
558     /**
559      * Returns a copy of this {@code MonthDay} with the month-of-year altered.
560      * <p>
561      * This returns a month-day with the specified month.
562      * If the day-of-month is invalid for the specified month, the day will
563      * be adjusted to the last valid day-of-month.
564      * <p>
565      * This instance is immutable and unaffected by this method call.
566      *
567      * @param month  the month-of-year to set in the returned month-day, not null
568      * @return a {@code MonthDay} based on this month-day with the requested month, not null
569      */
570     public MonthDay with(Month month) {
571         Objects.requireNonNull(month, "month");
572         if (month.getValue() == this.month) {
573             return this;
574         }
575         int day = Math.min(this.day, month.maxLength());
576         return new MonthDay(month.getValue(), day);
577     }
578 
579     /**
580      * Returns a copy of this {@code MonthDay} with the day-of-month altered.
581      * <p>
582      * This returns a month-day with the specified day-of-month.
583      * If the day-of-month is invalid for the month, an exception is thrown.
584      * <p>
585      * This instance is immutable and unaffected by this method call.
586      *
587      * @param dayOfMonth  the day-of-month to set in the return month-day, from 1 to 31
588      * @return a {@code MonthDay} based on this month-day with the requested day, not null
589      * @throws DateTimeException if the day-of-month value is invalid,
590      *  or if the day-of-month is invalid for the month
591      */
592     public MonthDay withDayOfMonth(int dayOfMonth) {
593         if (dayOfMonth == this.day) {
594             return this;
595         }
596         return of(month, dayOfMonth);
597     }
598 
599     //-----------------------------------------------------------------------
600     /**
601      * Queries this month-day using the specified query.
602      * <p>
603      * This queries this month-day using the specified query strategy object.
604      * The {@code TemporalQuery} object defines the logic to be used to
605      * obtain the result. Read the documentation of the query to understand
606      * what the result of this method will be.
607      * <p>
608      * The result of this method is obtained by invoking the
609      * {@link TemporalQuery#queryFrom(TemporalAccessor)} method on the
610      * specified query passing {@code this} as the argument.
611      *
612      * @param <R> the type of the result
613      * @param query  the query to invoke, not null
614      * @return the query result, null may be returned (defined by the query)
615      * @throws DateTimeException if unable to query (defined by the query)
616      * @throws ArithmeticException if numeric overflow occurs (defined by the query)
617      */
618     @SuppressWarnings("unchecked")
619     @Override
620     public <R> R query(TemporalQuery<R> query) {
621         if (query == TemporalQueries.chronology()) {
622             return (R) IsoChronology.INSTANCE;
623         }
624         return TemporalAccessor.super.query(query);
625     }
626 
627     /**
628      * Adjusts the specified temporal object to have this month-day.
629      * <p>
630      * This returns a temporal object of the same observable type as the input
631      * with the month and day-of-month changed to be the same as this.
632      * <p>
633      * The adjustment is equivalent to using {@link Temporal#with(TemporalField, long)}
634      * twice, passing {@link ChronoField#MONTH_OF_YEAR} and
635      * {@link ChronoField#DAY_OF_MONTH} as the fields.
636      * If the specified temporal object does not use the ISO calendar system then
637      * a {@code DateTimeException} is thrown.
638      * <p>
639      * In most cases, it is clearer to reverse the calling pattern by using
640      * {@link Temporal#with(TemporalAdjuster)}:
641      * <pre>
642      *   // these two lines are equivalent, but the second approach is recommended
643      *   temporal = thisMonthDay.adjustInto(temporal);
644      *   temporal = temporal.with(thisMonthDay);
645      * </pre>
646      * <p>
647      * This instance is immutable and unaffected by this method call.
648      *
649      * @param temporal  the target object to be adjusted, not null
650      * @return the adjusted object, not null
651      * @throws DateTimeException if unable to make the adjustment
652      * @throws ArithmeticException if numeric overflow occurs
653      */
654     @Override
655     public Temporal adjustInto(Temporal temporal) {
656         if (Chronology.from(temporal).equals(IsoChronology.INSTANCE) == false) {
657             throw new DateTimeException("Adjustment only supported on ISO date-time");
658         }
659         temporal = temporal.with(MONTH_OF_YEAR, month);
660         return temporal.with(DAY_OF_MONTH, Math.min(temporal.range(DAY_OF_MONTH).getMaximum(), day));
661     }
662 
663     /**
664      * Formats this month-day using the specified formatter.
665      * <p>
666      * This month-day will be passed to the formatter to produce a string.
667      *
668      * @param formatter  the formatter to use, not null
669      * @return the formatted month-day string, not null
670      * @throws DateTimeException if an error occurs during printing
671      */
672     public String format(DateTimeFormatter formatter) {
673         Objects.requireNonNull(formatter, "formatter");
674         return formatter.format(this);
675     }
676 
677     //-----------------------------------------------------------------------
678     /**
679      * Combines this month-day with a year to create a {@code LocalDate}.
680      * <p>
681      * This returns a {@code LocalDate} formed from this month-day and the specified year.
682      * <p>
683      * A month-day of February 29th will be adjusted to February 28th in the resulting
684      * date if the year is not a leap year.
685      * <p>
686      * This instance is immutable and unaffected by this method call.
687      *
688      * @param year  the year to use, from MIN_YEAR to MAX_YEAR
689      * @return the local date formed from this month-day and the specified year, not null
690      * @throws DateTimeException if the year is outside the valid range of years
691      */
692     public LocalDate atYear(int year) {
693         return LocalDate.of(year, month, isValidYear(year) ? day : 28);
694     }
695 
696     //-----------------------------------------------------------------------
697     /**
698      * Compares this month-day to another month-day.
699      * <p>
700      * The comparison is based first on value of the month, then on the value of the day.
701      * It is "consistent with equals", as defined by {@link Comparable}.
702      *
703      * @param other  the other month-day to compare to, not null
704      * @return the comparator value, that is less than zero if this is before {@code other},
705      *          zero if they are equal, greater than zero if this is after {@code other}
706      * @see #isBefore
707      * @see #isAfter
708      */
709     @Override
710     public int compareTo(MonthDay other) {
711         int cmp = (month - other.month);
712         if (cmp == 0) {
713             cmp = (day - other.day);
714         }
715         return cmp;
716     }
717 
718     /**
719      * Checks if this month-day is after the specified month-day.
720      *
721      * @param other  the other month-day to compare to, not null
722      * @return true if this is after the specified month-day
723      */
724     public boolean isAfter(MonthDay other) {
725         return compareTo(other) > 0;
726     }
727 
728     /**
729      * Checks if this month-day is before the specified month-day.
730      *
731      * @param other  the other month-day to compare to, not null
732      * @return true if this point is before the specified month-day
733      */
734     public boolean isBefore(MonthDay other) {
735         return compareTo(other) < 0;
736     }
737 
738     //-----------------------------------------------------------------------
739     /**
740      * Checks if this month-day is equal to another month-day.
741      * <p>
742      * The comparison is based on the time-line position of the month-day within a year.
743      *
744      * @param obj  the object to check, null returns false
745      * @return true if this is equal to the other month-day
746      */
747     @Override
748     public boolean equals(Object obj) {
749         if (this == obj) {
750             return true;
751         }
752         return (obj instanceof MonthDay other)
753                 && month == other.month
754                 && day == other.day;
755     }
756 
757     /**
758      * A hash code for this month-day.
759      *
760      * @return a suitable hash code
761      */
762     @Override
763     public int hashCode() {
764         return (month << 6) + day;
765     }
766 
767     //-----------------------------------------------------------------------
768     /**
769      * Outputs this month-day as a {@code String}, such as {@code --12-03}.
770      * <p>
771      * The output will be in the format {@code --MM-dd}:
772      *
773      * @return a string representation of this month-day, not null
774      */
775     @Override
776     public String toString() {
777         StringBuilder buf = new StringBuilder(10);
778         buf.append("--");
779         DecimalDigits.appendPair(buf, month);
780         buf.append('-');
781         DecimalDigits.appendPair(buf, day);
782         return buf.toString();
783     }
784 
785     //-----------------------------------------------------------------------
786     /**
787      * Writes the object using a
788      * <a href="{@docRoot}/serialized-form.html#java.time.Ser">dedicated serialized form</a>.
789      * @serialData
790      * <pre>
791      *  out.writeByte(13);  // identifies a MonthDay
792      *  out.writeByte(month);
793      *  out.writeByte(day);
794      * </pre>
795      *
796      * @return the instance of {@code Ser}, not null
797      */
798     @java.io.Serial
799     private Object writeReplace() {
800         return new Ser(Ser.MONTH_DAY_TYPE, this);
801     }
802 
803     /**
804      * Defend against malicious streams.
805      *
806      * @param s the stream to read
807      * @throws InvalidObjectException always
808      */
809     @java.io.Serial
810     private void readObject(ObjectInputStream s) throws InvalidObjectException {
811         throw new InvalidObjectException("Deserialization via serialization delegate");
812     }
813 
814     void writeExternal(DataOutput out) throws IOException {
815         out.writeByte(month);
816         out.writeByte(day);
817     }
818 
819     static MonthDay readExternal(DataInput in) throws IOException {
820         byte month = in.readByte();
821         byte day = in.readByte();
822         return MonthDay.of(month, day);
823     }
824 
825 }