Static Keyword in Java

Static Keyword in Java with Examples

In this article, I am going to discuss the Static Keyword in Java with Examples. Please read our previous where we discussed the Final Keyword in Java with Examples. At the end of this article, you will understand the following pointers in detail which are related to Java Static Keyword.

  1. Java Static Keyword
  2. Static Block in Java
  3. Static Variable in Java
  4. When and why we need to use a static variable in Java?
  5. Static Methods in Java
  6. Why is the Java main method static?
  7. Why it is not required to create an instance of a class?
  8. When to create static methods in Java?
  9. Static Class in Java
  10. What is static import in Java?
  11. What is the need for static import?
  12. Why two static members of the same name cannot be imported?
  13. Difference between static and final keyword
Java Static Keyword

The static keyword in Java is used for memory management mainly. It is a keyword that is used to share the same variable or method of a given class. Basically, static is used for a constant variable or a method that is the same for every instance of a class. The static keyword can be used with class, variable, method, and block. Static members belong to the class instead of a specific instance, this means if you make a member static, you can access it without an object. If we want to access class members without creating an instance of the class, we need to declare the class members static.

In Java programming language, static keyword is a non-access modifier and can be used for the following:

  1. Static Block
  2. Static Variable (also known as class variable)
  3. Static Method (also known as class method)
  4. Static Classes (Nested Classes)
Static Block in Java

It is used to initialize the static data member. It is executed before the main method at the time of class loading. If you need to do the computation in order to initialize your static variables, you can declare a static block that gets executed exactly once, when the class is first loaded. We can’t access non-static variables in the static block.  A class can have multiple Static blocks, which will execute in the same sequence in which they have been written into the program.

Syntax:
static{
      //variable initialization
}

Sample Program to demonstrate the use of Static Block in Java:
package Demo;
import java.util.*;
public class StaticBlockDemo
{
  //static variable
  static int j = 10;
  static int n;

  //static block
  static
  {
    System.out.println ("Static block initialized.");
    n = j * 8;
  }

  public static void main (String[]args)
  {
    System.out.println ("Inside main method");
    System.out.println ("Value of j : " + j);
    System.out.println ("Value of n : " + n);
  }
}

Output :

Static Block in Java

Static Variable in Java

If you declare any variable as static, it is known as a static variable. When a variable is declared as static, then a single copy of the variable is created and shared among all objects at the class level. It doesn’t matter how many times we initialize a class; there will always be only one copy of a static field belonging to it. The value of this static field will be shared across all objects of either same of any different classes. Static variables are, essentially, global variables. A static variable is common to all the instances (or objects) of the class because it is a class-level variable. Local variables cannot be declared static. If the static variable is not private, we can access it with ClassName.variableName

Syntax: static datatype variable-name

Sample Program to demonstrate the use of Static Variables in Java:
package Demo;

class Counter {
    static int count = 0;
    Counter(){
        count ++;
    }
    public void getCount() {
        System.out.printf("Value of counter: %d \n", count);
    }
    public static void main( String args[] ) {
        Counter c1 = new Counter(); //count incremented to 1
        c1.getCount();
        Counter c2 = new Counter(); //count incremented to 2
        c2.getCount();
        Counter c3 = new Counter(); //count incremented to 3
        c3.getCount();
    }
}

Output:

Static Variable in Java

Note:

  • We can create static variables at class-level only.
  • static block and static variables are executed in the order they are present in a program.
  • It makes your program memory efficient (i.e., it saves memory).
When and why we need to use a static variable in Java?

Suppose we want to a store record of all employees of any company, in this case, employee id is unique for every employee but the company name is common for all. When we create a static variable as a company name then only once memory is allocated otherwise it allocates a memory space each time for every employee.

Static Methods in Java

A method declared with the static keyword. A static method can access only static variables of class and invoke only static methods of the class. Usually, static methods are utility methods that we want to expose to be used by other classes without the need of creating an instance. One of the basic rules of working with static methods is that you can’t access a non-static method or field from a static method because static methods do not use any instance variables of any object of the class they are defined in. Static methods take all the data from parameters and compute something from those parameters, with no reference to variables.

Note: The best-known static method is the main, which is called by the Java runtime to start an application. The main method must be static, which means that applications run in a static context by default.

Syntax : static return_type method_name();

Sample Program for demonstrating the use of Static Method:
package Demo;

class StaticTest {

    // non-static method
    int multiply(int a, int b){
        return a * b;
    }

    // static method
    static int add(int a, int b){
        return a + b;
    }
}

public class StaticMethodDemo {

   public static void main( String[] args ) {

        // create an instance of the StaticTest class
        StaticTest st = new StaticTest();

        // call the nonstatic method
        System.out.println(" 5 * 5 = " + st.multiply(5,5));

        // call the static method
        System.out.println(" 5 + 3 = " + StaticTest.add(5,3));
   }
}

Output:

Static Methods in Java

Restrictions for the static method in Java

There are two main restrictions for the static method. They are:

  1. The static method can not use non-static data member or call the non-static method directly.
  2. this and super cannot be used in static context.
Why is the Java main method static?

It is because the object is not required to call a static method. If it were a non-static method, JVM creates an object first then call the main() method that will lead the problem of extra memory allocation.

Why it is not required to create an instance of a class?

Usually, static methods are utility methods that we want to expose to be used by other classes without the need of creating an instance. The static keyword is used to create methods that will exist independently of any instances created for the class. As static methods take all the data from parameters and compute something from those parameters, with no reference to variables. And Class variables and methods can be accessed using the class name followed by a dot and the name of the variable or method. Therefore, the Static Method doesn’t require instance creation, so it’s generally faster and provides better performance. That’s why utility class methods in Wrapper classes, System class, Collections class are all static methods.

Note: The best-known static method is the main, which is called by the Java runtime to start an application. The main method must be static, which means that applications run in a static context by default.

When to create static methods in Java?

It’s possible to write fluent code when static imports are used. When your method only depends on its parameters, the object state has no effect on the method behavior. Then you can create the method as static.

Static Class in Java

A class can be made static only if it is a nested class. Java programming language allows us to create a class within a class. It provides a compelling way of grouping elements that are only going to be used in one place, this helps to keep our code more organized and readable.

Basically, nested class are of two types:

  1. Static Nested Classes: nested classes that are declared static are called static nested classes
  2. Not-static Nested Classes: nested classes that are non-static are called inner classes or non-static nested classes

Syntax :
class OuterClass {
          static class InnerClass {
                 //code
          }
}

Sample Program for demonstrating the use of Static Class:
package Demo;
class StaticClassDemo {//Outer Class
    static String message = "Hello World!";
    static class InnerClass {//Inner Class
      static void getMessage(){
        System.out.println( message );
      }
    }
    public static void main( String args[] ) {
    	StaticClassDemo.InnerClass.getMessage();
    }
}

Output: Hello World!

Points to Remember:
  • A static inner class cannot access instance variables and methods of the outer class without the object’s reference
  • A static inner class can access all static variables and methods of the outer class
  • In Java, the outer class cannot be static
  • Nested static class doesn’t need a reference of Outer class
  • A static class cannot access non-static members of the Outer class
What is static import in Java?

Static import is a feature introduced in the Java programming language that allows members (fields and methods) which have been scoped within their container class as public static, to be used in Java code without specifying the class in which the field has been defined. This feature was introduced into the language in version 5.0. The static import construct allows unqualified access to static members without inheriting from the type containing the static members.

What is the need for static import?

The feature provides a type-safe mechanism to include constants into code without having to reference the class that originally defined the field. It also helps to deprecate the practice of creating a constant interface (an interface that only defines constants then writing a class implementing that interface, which is considered inappropriate use of interfaces).

The mechanism can be used to reference individual members of a class: import static java.lang.Math.PI;
or, all the static members of a class: import static java.lang.Math.*;
Once the static members have been imported, they may be used without qualification: double r = cos(PI * theta);

Sample Program to demonstrate the use of Static Import in Java:
package Demo;

import static java.lang.Math.*;
import static java.lang.System.out;

public class StaticImport {
    public static void main(String[] args) {
        out.println("Hello World!");
        out.println("Considering a circle with a diameter of 5 cm, it has");
        out.println("a circumference of " + (PI * 5) + " cm");
        out.println("and an area of " + (PI * pow(2.5, 2)) + " sq. cm");
    }
}

Output:

What is the need of Static Import in Java

Why two static members of the same name cannot be imported?

If two static members of the same name are imported from multiple different classes, the compiler will throw an error, as it will not be able to determine which member to use in the absence of class name qualification. For example, the following code will fail to compile:

package Demo;

import static java.lang.Integer.*;
import static java.lang.Long.*;

public class StaticImport {
    public static void main(String[] args) {
        System.out.println(MAX_VALUE);
    }
}

Output: Compilation Error

In this case, MAX_VALUE is ambiguous, as the MAX_VALUE field is an attribute of both java.lang.Integer and java.lang.Long. Prefixing the field with its class name will disambiguate the class from which MAX_VALUE is derived, but doing so makes the use of a static import redundant.

Pointers to remember about static import in java:
  • Use static import when you require frequent access to static members from one or two classes.
  • If you overuse the static import feature, it can make your program unreadable and unmaintainable, polluting its namespace with all the static members you import.
  • Importing all of the static members from a class can be particularly harmful to readability; if you need only one or two members, import them individually.
  • static import can make your program more readable, by removing the boilerplate of repetition of class names.
  • The use of static import can reduce code size and allow you to freely use the static field of external class without prefixing class names on that.
Difference between static and final keyword

static keyword always fixed the memory that means that it will be located only once in the program whereas the final keyword always fixed the value that means it makes variable values constant.

Note: As for as real-time statement there concern every final variable should be declared the static but there is no compulsion that every static variable declared as final.

In the next article, I am going to discuss Exception Handling in Java with Examples. Here, in this article, I try to explain the Static Keyword in Java with examples. I hope you enjoy this Static Keyword in Java with Examples article. I would like to have your feedback. Please post your feedback, question, or comments about this Static Keyword in Java with Examples article.

Leave a Reply

Your email address will not be published. Required fields are marked *