Skip to content
Related Articles

Related Articles

Improve Article
URL sameFile() method in Java with Examples
  • Last Updated : 10 May, 2019

The sameFile() function of Java.net.URL class is used to compare two URLs excluding the fragment part. This method returns true if both the URL are same excluding the fragment part else returns false.

Function Signature

public boolean sameFile(URL u)

Syntax

url1.sameFile(url2);

Parameter: This method accepts a mandatory parameter url which is the second url to be compared to this url.

Return Value: This method returns true if both the URL are same excluding the fragment part else returns false.



Below methods illustrate URL.sameFile() method:

Example 1:




// Java program to illustrate
// URL.sameFile() method
  
import java.net.*;
  
class GFG {
    public static void main(String args[]) throws Exception
    {
  
        // create URL1
        URL url1
            = new URL("https:// www.geeksforgeeks.org");
  
        // create URL2
        URL url2
            = new URL("https:// www.geeksforgeeks.org");
  
        // check if two URL are same or not
        System.out.print("URL 1 is compared to URL 2: ");
  
        if (url1.sameFile(url2))
            System.out.println("same");
        else
            System.out.println("not same");
    }
}
Output:
URL 1 is compared to URL 2: same

Example 2: The sameFile() function has a specific use that makes it different from the equals() function. The sameFile() function compares the URL excluding the fragment part. The following example will illustrate the use which makes it different from equals function.




// Java program to check the use of sameFile
  
import java.net.*;
  
class GFG {
    public static void main(String args[]) throws Exception
    {
        // create URL1
        URL url1
            = new URL("https:// www.geeksforgeeks.org");
  
        // create URL2
        URL url2
            = new URL("https:// www.geeksforgeeks.org#print");
  
        // check if two URL are same or not
        System.out.print("URL 1 is compared to URL 2: ");
  
        if (url1.sameFile(url2))
            System.out.println("same");
        else
            System.out.println("not same");
    }
}
Output:
URL 1 is compared to URL 2: same

Note: If equals function would have been used, then the second code would have printed “not same” but using the sameFile() function it will give result “same”.

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. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.




My Personal Notes arrow_drop_up