Java - URL getQuery() Method with Examples
Description
The Java URL getQuery() method returns the query part of this URL.
Declaration
Following is the declaration for java.net.URL.getQuery() method
public String getQuery()
Parameters
NA
Return Value
the query part of this URL, or null if one does not exist.
Exception
NA
Example 1
The following example shows the usage of Java URL getQuery() method for a valid url with https protocol without query part. In this example, we're creating an instance of URL class. Now using getQuery() method, we're getting the query and printing the same −
package com.tutorialspoint;
import java.io.IOException;
import java.net.URL;
public class UrlDemo {
public static void main(String [] args) {
try {
URL url = new URL("https","www.tutorialspoint.com","/index.htm");
String result = url.getQuery();
System.out.println(result);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Let us compile and run the above program, this will produce the following result −
Output
null
Example 2
The following example shows the usage of Java URL getQuery() method for a valid url with a query part. In this example, we're creating an instance of URL class. Now using getQuery() method, we're getting the query and printing the same −
package com.tutorialspoint;
import java.io.IOException;
import java.net.URL;
public class UrlDemo {
public static void main(String [] args) {
try {
URL url = new URL("https://www.tutorialspoint.com/index.htm?language=en#j2se");
String result = url.getQuery();
System.out.println(result);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Let us compile and run the above program, this will produce the following result −
Output
language=en
Example 3
The following example shows the usage of Java URL getQuery() method for a valid url with file protocol along with query part. In this example, we're creating an instance of URL class. Now using getQuery() method, we're getting the query and printing the same −
package com.tutorialspoint;
import java.io.IOException;
import java.net.URL;
public class UrlDemo {
public static void main(String [] args) {
try {
URL url = new URL("file","www.tutorialspoint.com","/index.htm?language=en#j2se");
String result = url.getQuery();
System.out.println(result);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Let us compile and run the above program, this will produce the following result −
Output
language=en