Saturday, December 30, 2017

Java Import statement concepts in detail

case 1: Types of import statement:-

 There are two types of import statement.
 1. Explicit class import
 2. Implicit class import

 Explicit class import: -

 Example: import java.util.Arraylist;
 It is highly recommended to use explicit class import because it improve readablity of the code.

 Implicit class import:-

 Example: import java.util.*;
 Not recommended to use because it reduces readablity of the code.


 case 2: Which of the following import statement are meaningful.

 import java.util.ArrayList;   // Correct
 import java.util.ArrayList.*; // Incorrect
 import java.util.*;           // Correct
 import java.util;            //  Incorrect

 case 3: Consider the following code
 
     class MyObject extends java.rmi.UnicastRemoteObject
{

}

The code compile fine even though we are not writing import statement because we used fully qualified name.

Note: Whenever we are using fully qualified name, it is not required to write import statement similarly whenever we are writing import statement it is not
required to use fully qualified name.

 case 4:

   import java.util.*;
  import java.sql.*;
  class  Test{
 
     public static void main(String args[])
{

Date d = new Date();

}

  Compiler gives error like: reference to Date is Ambiguous.


  Note: Even in a case of List also we may get same ambiguity problem because it available in both util and awt packages.

  case 5: While resolving class name compiler will always gives the precedence in the following order:

  1. Explicit class import
  2. class present in current working directory (default package)
  3. Implicit class import

  Example:
     
  import java.util.Date;
import java.sql.*;
class Test{
public static void main(String args[])
{
Date d = new Date();
System.out.println(d.getClass().getName());
}
}

In the above example util package date got considered.

case 6: Whenever we are importing a java package all classes and interfaces present in that package by default available but not sub-package classes. if we want to use sub-package class compulsory we should write import statement until sub package level.

             



To use patteren class in our program which import statement is required:-

1.import java .*;
2.import java.util.*;
3.import java.util.regex.*; // This one is correct
4.No import is required


case 7: All classes and interfaces present in the following packages are by default available to every java program hence we are not required to write import statement.

    1. java.lang package
    2. default package (current working directory)

case 8: Import statement is totally compile time related concept. More number of import then more will be the compile time but there is no effect on execution time(run time).





No comments:

Post a Comment