Skip to content

Static keyword in Java | Method, Variable, Block, Nested Class with Examples

  • by

What is Static Keyword in java?

A Static keyword is used in java for application memory management. You can apply static keywords in variables, methods, blocks, and nested classes. Static means that you don’t have to create an instance of the class to use the methods or variables associated with the class. 

So static keyword can be in java:-

  • Variable (also known as a class variable)
  • Method (also known as a class method)
  • Block
  • Nested class

We will look at one by how to use static keywords with all of it.

Static keyword in Java Method, Variable, Block, Nested Class

To create any static member in java, precede its declaration with the keyword static. A Static member can access without creating a class object.

Java static Variable Example | Field

A declaration of static variables is very easy in java. Use “static keyword” before the variable name. A static variable only creates one copy and is shared among all objects at the class level.  It doesn’t matter how many times the class is initialized. Only one copy of the static field belonging to it

For example, the company has many many employees so in a data all employe has the same company name.

  • The static variable gets memory only once in the class scope at the time of class loading.
  • static members belong to the class instead of a specific instance. So it can be accessed directly using the class name without any object reference.

It means that only one instance of a static field exists even if you create a million instances of the class or you don’t create any. It will be shared by all instances. (Source – https://stackoverflow.com/)

Complete static variable Example

In Example, the company name will be a static data member. So it will get the memory only once.

Diagram:-

Java static Variable Example Field

Code:-

class Employee {
    int id;//instance variable
    String name;
    static String company = "ISG";//static variable

    //constructor
    Employee(int i, String n) {
        id = i;
        name = n;
    }

    //method to display the values
    void display() {
        System.out.println(id + " " + name + " " + company);
    }
}

//Test class to show the values of objects
public class Example {
    public static void main(String args[]) {

        Employee e1 = new Employee(111, "John");
        Employee e2 = new Employee(222, "Kemi");

        e1.display();
        e2.display();
    }
}  

Output:

111 John ISG
222 Kemi ISG

Q: What are the Advantages of static variables?

Answer: The program will be more memory efficient.

Q: What is a problem without a static variable in java.

Suppose there is one company “ISG”, where 1000 employe is working. So all instance data members will use memory each time the object is created.

class Employee{  
     int id;  
     String name;  
     String company="ISG";  
}  

If you noticed then id and name is unique for every employee but the Company will be the same. Creating “company” data member static will get the memory only once. Because it’s now an instance data member.

static String company="ISG";

Java static Method Example

Declaring a method with a static keyword called a “Static Method” in java. Some important factors of it:-

  • A static method belongs to the class rather than the object of a class.
  • It can be invoked without creating an instance of a class.
  • Access static data members and do change the value of it can be done by Static method.

The Static Methods have several restrictions:-

  • Static methods only call others static methods.
  • Static data members can only access by Static methods. And the static method can not have a non-static data member.
  • It can’t refer to this or super in any way.

Q: Why is the Java main method static?

Answer: Static methods not required a class instance to call it. So the nonstatic method can call direct. If the main method will be not static then  JVM needs to create an object first then call a main() method, which will require extra memory allocation.

Complete static method example

Have you notice the java main methods are also static.

The example “AddNumber” is a static method with the return addition of numbers. At the main method calling an AddNumebr method with parameter.


public class Example {
    static int AddNumber(int a, int b) {
        return a + b;
    }

    public static void main(String args[]) {
        int result = AddNumber(5, 10);
        System.out.println(result);
    }
}  

Output: 15

Java Static Block Example

A Java static initializer block is defined only used static words with open and close curly braces.

Why static block used:-

  • To initialize the static data members.
  • Executed before the java main method at the time of classloading.

See the below Java static block example code:-

It looks like a default constructor without a class name. But it’s not.

public class Example {
    static {
        System.out.println("Hello static block");
    }

    public static void main(String args[]) {
        System.out.println("Main Method");
    }
}  

Output:

Hello static block
Main Method

Q: Can java program (code) execute without main() method?

Answer: It’s was possible on an earlier version of Java JDK 1.6. Since JDK 1.7, but not it’s not possible to execute a java class (program) without a main method.

Let’s give it a try without the main method:-


public class Example {
    static {
        System.out.println("Hello static block");
    }

}  

Output:

Error: Main method not found in class Example, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application

Java static class | Nested class

The only nested class can be static, declaration of top-level class with a static modifier in java is not possible. Which nested class declared with static keyword is called a static nested class.

Let’s see a simple example code on how to create a nested class.


public class Example {
    // Top level class
    
    static class Test{
        // nested class
    }
}  

Do comment if you have any doubts and suggestions on this tutorial.

Note: This example (Project) is developed in IntelliJ IDEA 2018.2.6 (Community Edition)
JRE: 11.0.1
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.14.1
Java version 11
All Java static keyword examples are in Java 11, so it may change on different from Java 9 or 10 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading