Wednesday, February 18, 2026
HomeLanguagesJavaYearMonth query() Method in Java with Examples

YearMonth query() Method in Java with Examples

query() method of an YearMonth class used to query this YearMonth using the specified query as parameter.The TemporalQuery object passed as parameter define the logic to be used to obtain the result from this YearMonth.

Syntax:

public <R> R query(TemporalQuery<R> query)

Parameters: This method accepts only one parameter query which is the query to invoke.

Return value: This method returns the query result, null may be returned.

Exception:
This method throws following Exceptions:

  • DateTimeException – if unable to query .
  • ArithmeticException – if numeric overflow occurs.

Below programs illustrate the query() method:
Program 1:




// Java program to demonstrate
// YearMonth.query() method
  
import java.time.*;
import java.time.temporal.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // create YearMonth object
        YearMonth yM = YearMonth.of(2020, 12);
  
        // apply query method of YearMonth class
        String value = yM.query(TemporalQueries
                                    .precision())
                           .toString();
  
        // print the result
        System.out.println("Precision value"
                           + " for YearMonth is "
                           + value);
    }
}


Output:

Precision value for YearMonth is Months

Program 2: Showing if query did not found the required object then it returns null.




// Java program to demonstrate
// YearMonth.query() method
  
import java.time.*;
import java.time.temporal.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // create YearMonth object
        YearMonth YM = YearMonth.of(2019, 3);
  
        // apply query method of YearMonth class
        // print the result
        System.out.println("Zone value for YearMonth is "
                           + YM.query(
                                 TemporalQueries.offset()));
    }
}


Output:

Zone value for YearMonth is null

References: https://docs.oracle.com/javase/10/docs/api/java/time/YearMonth.html#query(java.time.temporal.TemporalQuery)

RELATED ARTICLES

1 COMMENT

Most Popular

Dominic
32506 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6882 POSTS0 COMMENTS
Nicole Veronica
12005 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12099 POSTS0 COMMENTS
Shaida Kate Naidoo
7011 POSTS0 COMMENTS
Ted Musemwa
7255 POSTS0 COMMENTS
Thapelo Manthata
6967 POSTS0 COMMENTS
Umr Jansen
6956 POSTS0 COMMENTS