Home » Java programming language

What is static import in java?

Java static import - In this article, we are going to learn about it, and how to implement static import in java?
Submitted by Preeti Jain, on February 18, 2018

With Static import

With the help of static import we can access static members directly. It is not required to use static member with class name.

Static import is not recommended because it reduces readability of the code.

Syntax

    import static packagename.classname.object(optional);

Example (With static import):

import static java.lang.System.out;
class StaticImport{
	static String s = "My Name is Preeti Jain"; 
	public static void main(String[] args){
		out.println("Length of the string is " + 
			StaticImport.s.length());	
	}
}

Output

D:\Java Articles>java StaticImport
Length of the string is 22

Without Static import

Without the help of static import we can access static members with classname. It is required to use static member with class name.

Without static import is recommended because it improves readability of the code.

Syntax:

    import  packagename.classname.object(optional);

Case 1: Without Static Import

class WithoutStaticImport{
	static String s = "My Name is Preeti Jain"; 
	public static void main(String[] args){
		out.println("Length of the string is " +
			WithoutStaticImport.s.length());
	}
}

Output

D:\Java Articles>javac WithoutStaticImport.java
WithoutStaticImport.java:8: 
error: cannot findsymbol
out.println("Length of the string is " + WithoutStaticImport.s.length())
;
        ^
  symbol:   variable out
  location: class WithoutStaticImport
1 error

In the above example, we will get compile time error just because we are using static object out without static import. To resolve this problem we have two options one is to go with static import and another is to use object with classname.

Case 2: Use static object with classname without static import

class WithoutStaticImport1{
	static String s = "My Name is Preeti Jain"; 
	public static void main(String[] args){
		System.out.println("Length of the string is " + 
			WithoutStaticImport1.s.length());
	}
}

Output

D:\Java Articles>java WithoutStaticImport1
Length of the string is 22


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.