withYear(int year) method of the YearMonth class used to alter the year of YearMonth object using year passed as a parameter and after that method returns the copy of altered YearMonth. This instance is immutable and unaffected by this method call.
public YearMonth withYear(int year)
Parameters: This method accepts month as parameter which is the year to set in the returned year-month, from MIN_YEAR to MAX_YEAR.
Return value: This method returns a YearMonth based on this year-month with the requested year.
Exception: This method throws DateTimeException if the year value is invalid.
Below programs illustrate the withYear() method:
YearMonth before applying method: 2019-12 YearMonth after applying method: 2023-12
YearMonth before applying method: 2022-07 YearMonth after applying method: 1992-07
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.