×

Example of Static import in Java

Static keyword

Java's static keyword is mainly used to control memory. Variables, methods, blocks, and nested classes are compatible with the static keyword. Instead of an instance, the static keyword is part of the class.

The static may be

  • Variable (also can be said as inference variable or class variable)
  • Method (also can be expressed as or class Method)
  • Block
  • nested class

Static as import statement in Java

The concept of static import was first introduced in Java 1.5. A static import lets us immediately access a class's static members without using the class name or other objects. For instance, even though we typically access the Math class' sqrt() method through Math. sqrt(), we can also access it directly using a static import.

SUN MicroSystem claims that it will boost coding and make code more readable. However, specialists in programming claim that it will cause confusion and be bad for programming. We shouldn't use static import if there are no precise requirements.

The Java 5 static import feature makes it easier for programmers to readily access every static member of such a class. It doesn't need to be qualified with the class name.

Advantages of using static import statements in Java

Using a static import statement requires minimal coding as you can access the static member in that class any number of times, as you can directly call the static members.

The disadvantage of using static import statements in Java

Using this static import statement often in the program makes the code complex as it would be unreadable and hard to understand for others.

StaticExp.java

import static Java. lang.System.*;    
class StaticExp {  
  public static void main (String args []) {  
  int a = 10, b = 20; // Initializing the variables 
   out.println("the sum of a + b :" + “ “ + a+b);
// You need not use System. out every time as it is a static member  
  out.println(“sum of a + 10 :”+ “ “ + a + 10);  
 }   
}      

Output:

the sum of a + b :  30
sum of a + 10 :  20

You can use this static import for any method.

StaticExp1.java

import static Java. lang.Math.*;
// Importing math class as the static member 
class StaticExp1 {
    public static void main (String [] args)
    {
        System.out.println(“square root of 25 :” + “ “ + sqrt (25));
// Printing square root of 25 using static class
        System.out.println(“power of 3 raised to 3 :” + “ “ + pow (3, 3));
// Printing the power of 3 raised to 3 using static class
        System.out.println(“abs of 20.5 :” + “ “ + abs (20.5));
// Printing the abs of 20.5 using static class
    }
}

Ambiguity in static import statement:

The compiler will produce an error if two static elements with the same name are loaded from distinct classes since it won't know which element to use in the missing class identity qualification.

StaticExp2.java

import static Java. lang.Integer.*;
import static Java. lang.Byte.*;
class StaticExp2 {
    public static void main(String[] args)
    {
        out.println(MIN_VALUE);
    }
}

Output

Error : Reference to MIN_VALUE is ambiguous

We are attempting to access the MIN VALUE variable in the programme above; however, every primitive data type already has a MIN VALUE variable pre-declared in its Wrapper class. We are importing the Integer and Byte classes in this case and trying to access the static value MIN VALUE. Still, the compiler will become confused by seeing two import instructions because the static variable MIN VALUE is present in both the Integer and Byte classes. As a result, the compiler reported that the reference to MIN VALUE was ambiguous.

Difference between import and static import

You can use classes and interfaces that are available in any package by using import. However, by using static import, we may easily access all of a class's static elements (variables or methods) without using the class name.

The critical distinction is readability; compared to data member(out), ClassName.dataMember (System.out) is much less readable. Static import can improve readability in your software.

While the static import feature gives access to the static members of a class even without class qualification, import allows Java programmers to access classes of a module without package qualification. While a static import just makes a class's static members accessible, an import also makes classes and their interfaces accessible.


Related Topics

Perfect Number Program in Java

Perfect Number Program in Java A perfect number is a number whose sum of all the factors, excluding the number itself, is equal to the number. For example, 28 is a...

4 minutes read.

String Matches in Java

Firstly we have to know something about String? Strings are a bundle of different characters that are normally used in Java programming language. Strings are regarded as objects in the Java...

3 minutes read.

Java callable example

What is callable in Java? Callable is an interface that is present in Java. There are two methods for constructing threads: one is to inherit the Thread class, while the other...

3 minutes read.

How to Create an API in Java?

Introduction The API can be abbreviated as Application Programming Interface. An API is a combination of set of classes and interfaces. It is also equivalent to a simple java program. To...

12 minutes read.

Creation of Multi Thread in java

What are threads in Java? We can use threads to facilitate parallel processing. Threads are helpful when you wish to execute several pieces of code concurrently. A thread is a small process...

3 minutes read.

How to Calculate the Time Difference between Two Dates in Java?

The date is used extensively in Java to calculate date discrepancies. The date of joining an organization, admittance, appointment, etc., can be included when creating the application. The differences between...

4 minutes read.

Java Code Optimization

We encounter the idea of optimization while working on any Java application. It is essential that the code we write is not only clear and error-free but also optimized, meaning...

9 minutes read.

Java Integer sum() method

The sum() method of Java Integer class add the two specified integers values. It returns the same result as given by + operator. Syntax public static int sum (int a, int b)  Parameters The...

1 minute read.

Synchronized Keyword in Java

Synchronization is the process of limiting access to a shared resource or data to a single thread at a given moment in time. This aids in shielding the data from...

6 minutes read.

File Operation in Java

In Java, a file is an Abstract data type. These are used to store the data which is related. Files are named storage locations. With a file we can perform...

7 minutes read.

Java List Interface

List interface is used when we have to order a collection which contains duplicate entries. Like an array, the elements of its implementation classes are retrieved and inserted at a...

2 minutes read.

How to add Elements in Array in Java

Consider an array of the size n, in the given size we must add the elements in the given array. In this tutorial we are preferred to learn how to add...

3 minutes read.

Java Case Keyword

Case keyword: In this article we are going to learn the concept of a java case keyword.Generally, java case keyword is used with the switch statements.Case keyword is implemented in conditional...

3 minutes read.

Program to find and replace characters on string in java

In JAVA, Strings are immutable. To overcome this Java String class contains a lot of methods to do operations on Strings. One such method is replace method. String Replace It returns a...

3 minutes read.

Java calculate age

In this section, we will create a Java program that calculates age from the given date of birth or current date. In order to get the date of birth from the current...

6 minutes read.

Untouchable Number in Java

If a number N cannot be divided properly by any positive number, it is said to be an untouchable number. Additionally known as nonaliquot numbers. The sequence is A005114 from...

3 minutes read.

Graph Problems in Java

A graph is a special type of data structure used in programming that is made up of edges connecting each set of finitely many nodes, or vertices, to each other....

14 minutes read.

How to take Array Input in Java

In this tutorial, we will learn about how to take array input in Java. So, before taking inputs let us know what an array is first. Array: An array is a collection...

10 minutes read.

Zigzag Array in Java

In this tutorial, we discuss, what is zigzag array and its example. Even we will create the java program. In this program, we convert the simple array into a zigzag...

4 minutes read.

Spliterator in Java 8

In this tutorial, we will understand the meaning of spliterator in java 8. It is just like any other iterator available in java used to traverse the elements of either...

4 minutes read.