×

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

Java Font

The font is a Java class that is a part of java.awt package. The Serializable interface is implemented by it. The direct recognized child of a Java Font class is...

8 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.

Level order Traversal of a Binary Tree in Java

In Java, a level order traversal of a tree structure is also referred to as the breadth-first traversal of the binary tree. Regarding the subsequent binary tree: Level order traversal is as...

5 minutes read.

Converting Long to Date in Java

What Long and Date are in Java and how are they implemented in the Java programming language are the topics of this article. Additionally, we'll go into great detail on...

4 minutes read.

Moran Numbers in Java

In this article, we will be acknowledged about the moran numbers in Java, how they are formed, what are the approaches to achieve the moran numbers. Moran Number A moran numbers are...

3 minutes read.

Java Math acos() Method

The acos() method of Math class computes the trigonometric Arc Cosine (inverse of cosine ) of an angle. The value returned is between 0.0 to pi. Syntax: public static double acos(double a) Parameters: The...

1 minute read.

How to enable java in chrome

The Java module is huge for the Java Runtime Environment (JRE). It permits a program to work with the Java stage to run Java applets. Essentially, each of the undertakings connect...

3 minutes read.

Constructor in Java with Example

Java Constructor  The constructor is used for object initialization. It's a block of code that initializes a newly created object. It contains a collection of statements that are executed at the...

5 minutes read.

Java Math nextDown() Method

The nextDown() method of Math class returns the floating-point number adjacent to the argument in direction of the negative infinity. Syntax: public static double nextDown (double d)public static float nextDown (float f) Parameters: The...

2 minutes read.

Use Of Adapter class in Java

An adapter class in Java enables listener interfaces to be implemented by default. The Delegation Event Model is where the idea of listener interfaces first appeared. It is one of...

3 minutes read.

How to add 4 Hours to the Current Date in Java?

In this tutorial, we will learn how to add 4 hours to the local or current date in Java language. We will begin our topic with basic concepts and would...

2 minutes read.

Convert JSON to Map in Java

JACKSON and GSON libraries are two extremely capable JSON-related libraries offered by Java. To efficiently work with the returned JSON data, we frequently need to convert JSON responses into a...

6 minutes read.

How to stop execution after a certain time in Java

We will learn how to stop a long-running execution after a set amount of time in this post. We will take a look at a few alternative approaches to this...

6 minutes read.

Empty Statement in Java

The three sorts of statements in Java are control, expression, and declaration statements. Additionally, another statement is referred to as an empty statement. In this section, we will discuss about...

4 minutes read.

Relatively Prime in Java

In this article, you will be very well equipped with a knowledge of a relatively prime number and also Java programs to determine whether a given integer is a relatively...

4 minutes read.

MVC in Java

A well-known design pattern is Model-View-Controller. The discipline of web development. We can organize our code in this manner. The document stipulates that a program or application must include a...

4 minutes read.

Generic Linked List in Java

A linear data structure known as a Linked List stores values in nodes. As we already know, each node has two properties: its value and a link to the node...

6 minutes read.

Salesman Problem in Java

The Traveling Salesman Problem determines the shortest path that visits each city approximately once and loops back to the starting location. Another Java problem that is most like the Traveling...

5 minutes read.

How to Convert Decimal to Octal in Java

How to Convert Decimal to Octal in Java There are two methods to convert Decimal to Octal: Using toOcatlString() method Using user-defined logic Using Integer.toOctalString() method The toOctalString() is astaticmethod of the Integer...

2 minutes read.

Java Static Keyword

It can be either said that static declares the value to be the same, not only in the instance of a class but also as the whole. To declare a variable...

6 minutes read.