What is the URL.getQuery() method in Java?

The getQuery() method of the URL class can be used to get the query or parameter of a specified URL.

The image below shows the different parts of a URL.

Parts of the url

The URL class is present in the java.net package.

Syntax

The syntax of the getQuery() method is shown below.

public String getQuery()

Parameters

The getQuery() method doesn’t take any parameters.

Return value

The return type of the getQuery() method is string. If the URL doesn’t have any query then null is returned.

Code

The code below shows how to use the getQuery() method in Java.

import java.net.URL;
class GetQueryExample {
public static void main( String args[] ) {
try {
URL url= new URL("https:// www.educative.io?userid=123&lang=en");
//Get Query
String query=url.getQuery();
System.out.println("The URL is : "+url);
System.out.println("\nReference or anchor is : "+ query);
} catch (Exception e) {
System.out.println(e);
}
}
}

Explanation

In the code above:

  • Line 66 creates a URL object.
URL url= new URL("https:// www.educative.io?userid=123&lang=en");
  • In line 88, the getQuery() method gets the query segment of the URL object.
String query=url.getQuery();
  • Finally, the URL and its query segment are printed in lines 99 and 1010.

Free Resources