What are the differences between import and static import statements in Java?

JavaObject Oriented ProgrammingProgramming

We can use an import statement to import classes and interface of a particular package. Whenever we are using import statement it is not required to use the fully qualified name and we can use short name directly. We can use static import to import static member from a particular class and package. Whenever we are using static import it is not required to use the class name to access static member and we can use directly.

import statement

  • To access a class or method from another package we need to use the fully qualified name or we can use import statements.
  • The class or method should also be accessible. Accessibility is based on the access modifiers.
  • Private members are accessible only within the same class. So we won't be able to access a private member even with the fully qualified name or an import statement.
  • The java.lang package is automatically imported into our code by Java.

Example

Live Demo

import java.util.Vector;
public class ImportDemo {
   public ImportDemo() {
   //Imported using keyword, hence able to access directly in the code without package qualification.
      Vector v = new Vector();
      v.add("Tutorials");
      v.add("Point");
      v.add("India");
      System.out.println("Vector values are: "+ v);
   //Package not imported, hence referring to it using the complete package.
      java.util.ArrayList list = new java.util.ArrayList();
      list.add("Tutorix");
      list.add("India");
      System.out.println("Array List values are: "+ list);
   }
   public static void main(String arg[]) {
      new ImportDemo();
   }
}

Output

Vector values are: [Tutorials, Point, India]
Array List values are: [Tutorix, India]

Static Import Statement

  • Static imports will import all static data so that can use without a class name.
  • A static import declaration has two forms, one that imports a particular static member which is known as single static import and one that imports all static members of a class which is known as a static import on demand.
  • Static imports introduced in Java5 version.
  • One of the advantages of using static imports is reducing keystrokes and re-usability.

Example

Live Demo

import static java.lang.System.*; //Using Static Import
public class StaticImportDemo {
   public static void main(String args[]) {
      //System.out is not used as it is imported using the keyword stati.
      out.println("Welcome to Tutorials Point");
   }
}

Output

Welcome to Tutorials Point
raja
Published on 21-Jun-2019 18:02:08
Advertisements