The static import is a new feature which is added in Java 5 through which we can access any static member of a class directly. There is no need to qualify it by the class name. For example we can use “System.out.println()” directly with out prefixing System class like “out.println” (As out is a static member of System class).
Static Import example in Java
In this below example lets see how we can we use static import in accessing the static members of a class.
package com.javainterviewpoint; import static java.lang.System.*; public class StaticImportExample { public static void main(String args[]) { //With out static import System.out.println("\"out\" member of \"System\" class without static import"); System.err.println("\"err\" member of \"System\" class without static import"); //Using static import out.println("\"out\" member of \"System\" class with static import"); err.println("\"err\" member of \"System\" class with static import"); } }
Output :
"err" member of "System" class without static import "err" member of "System" class with static import "out" member of "System" class without static import "out" member of "System" class with static import
we can see in the above code we have accessed the out and err static members directly.
Note :
Important point to be noted here is that we need to add static keyword in the import statement
‘import static java.lang.System.*’ and not like ‘import java.lang.System.*’
Leave a Reply