×

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

Calculator Program in Java

Calculator Program in Java A calculator performs the basic mathematical operations such as addition, subtraction, multiplication, etc. In this section, we will create a calculator program in Java using switch case...

5 minutes read.

Find next greater number with same set of digits in Java

It contains a number (num). Finding the smallest number that has the same number of elements as num that is also larger than num is the task at hand. If...

8 minutes read.

Different Ways to Take Input from User in Java

Any information provided to a system for use is known as user input. Any responsive software or application must include user input. In Java, there are 4 different ways to...

5 minutes read.

Best Practices to use String Class in Java

Use String Builder or String Buffer for String concatenation in place of + operator.Compare two strings by equals( ) method instead == operator.Call .equals( ) method on a known String...

3 minutes read.

Java Solid Principles

Java implements the object-oriented SOLID principles for the design of software architecture. Solid Principles Java implements the object-oriented SOLID principles for the design of software architecture.   Five guiding principles transformed...

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

AES 256 Encryption in Java

Now a days, security has grown in importance. Java programming supports a variety of encryption and hashing methods, which offers security for data transport and communication among various nodes. In...

4 minutes read.

Java Interface Keyword

An interface is also known as the blueprint in Java. It has constants of static values and methods of abstraction. The interface is a mechanism used by Java to declare...

3 minutes read.

Difference between = = and equals ( ) in java

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

6 minutes read.

Java Integer class

The Integer class wraps a primitive int type value in an object. Its object contains only a single field whose type is int. Methods: The java.lang.Integer class provides several different methods for...

4 minutes read.

How to Create a Package in Java?

For the most part, how to create a package in Java generally, a package is defined as a collection of relevant or irrelevant items together in a very major way....

7 minutes read.

Addition Program in Java

Addition Program in Java We can perform the addition (sum) of two or more numbers by using the arithmetic operator (+). To write an addition program in Java, one must understand...

3 minutes read.

Display Unique Rows in a Binary Matrix in Java

To solve this problem, we must first locate and display the distinct rows of a supplied binary matrix afterward. We will go through how to show distinct rows inside a...

12 minutes read.

How Many Ways to Create Objects in Java

Introduction Java comes under the category of object-oriented programming languages. Since it is object-oriented, everything in Java is considered an object. Java is a diverse programming language that is designed to...

6 minutes read.

Java Subtract Days from Current Date

Dealing with date and time in Java is not a particularly challenging operation because Java has an API for date and time that simplifies duties for developers. There are two...

3 minutes read.

Deque in Java

Deque in java collections with Example Deque is short for “double-ended queue.” It is a linear collection that extends the Queue interface and supports insertion and deletion of the element at both the...

3 minutes read.

Zebra Puzzle Problem in Java

Complex puzzles like the zebra puzzle demand a lot of work and mental training to complete. Because it was created by renowned German scientist Albert Einstein, it is also sometimes...

10 minutes read.

Heart Pattern in Java

Heart Pattern is yet another intricate pattern program, however, due to its complexity, interviewers hardly ever inquire about it. Method for Printing the Heart Number Pattern Put the value of the total row...

2 minutes read.

Java vs Go

Java: Java is an object oriented programming language. It is also known as multi threaded language. It was designed by James gosling in the year 1995. We can also say that...

4 minutes read.

Java Enum vs Class

Enumerations are used in programming languages to represent collections of named constants. For instance, the four suits in a deck of playing cards might represent four integrators named Club, Diamond,...

7 minutes read.