How to Compare Two URL Objects in Java


Here this example aims to help compare two URL objects using the equals() method.

Source Code

package com.beginner.examples;
import java.net.MalformedURLException;
import java.net.URL;

public class CompareURL {

	public static void main(String[] args)  {

		try{
			//Create two URL objects
			URL googleUrl = new URL("http://www.google.com");
			
			URL oracleUrl = new URL("https://www.oracle.com/index.html");
			
			//Compare them using the equals() method
			if(googleUrl.equals(oracleUrl))
			{
				System.out.println("Both sites are equal");
			}
			else {
				System.out.println("Both sites are not equal");
			}
		}
		catch(MalformedURLException e)
		{
			e.printStackTrace();
		}
				
		
	}
		

}

Output:

Both sites are not equal

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments