Tutorials  /  Linux Basics

A Guide to static keyword in java

Ccentron Redaktion · January 2024 ·5 min read ·Linux Basics, Tutorial

The static keyword in Java is used a lot in java programming. Java static keyword is used to create a Class level variable in java. static variables and methods are part of the class, not the instances of the class.

Usage of Static Keyword in Java

Java static, static keyword in javaJava static keyword can be used in five.

  1. static variables

    static int count;

  2. static methods

    stativ void foo() {}

  3. static block

    static{

    //some code

    }

  4. static inner class

    class Test {

    static class InnerStatic{}

    }

  5. Interface static method (Java 8 onwards)

We will discuss four of them here.

VM

Matching infrastructure at centron

No hardware needed to follow along: ccloud³ VMs with full root access start at €3.12 per month, billed by the hour and ready in seconds. Rent a cloud server →

Java Static Variable

We can use static keyword with a class level variable. A static variable is a class variable and doesn’t belong to Object/instance of the class. Since static variables are shared across all the instances of Object, they are not thread safe. Usually, static variables are used with the final keyword for common resources or constants that can be used by all the objects. If the static variable is not private, we can access it with ClassName.variableName

Code
//static variable example
private static int count;
public static String str;
public static final String DB_USER = "myuser";

Java Static Method

Same as static variable, static method belong to class and not to class instances. 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. For example Collections class. Java Wrapper classes and utility classes contains a lot of static methods. The main() method that is the entry point of a java program itself is a static method.

Code
//static method example
public static void setCount(int count) {
    if(count > 0)
    StaticExample.count = count;
}

//static util method
public static int addInts(int i, int...js){
    int sum=i;
    for(int x : js) sum+=x;
    return sum;
}

From Java 8 onwards, we can have static methods in interfaces too.

Java Static Block

Java static block is the group of statements that gets executed when the class is loaded into memory by Java ClassLoader. Static block is used to initialize the static variables of the class. Mostly it’s used to create static resources when the class is loaded. We can’t access non-static variables in the static block. We can have multiple static blocks in a class, although it doesn’t make much sense. Static block code is executed only once when the class is loaded into memory.

Code
static{
    //can be used to initialize resources when class is loaded
    System.out.println("StaticExample static block");
    //can access only static variables and methods
    str="Test";
    setCount(2);
}

Java Static Class

We can use static keyword with nested classes. static keyword can’t be used with top-level classes. A static nested class is same as any other top-level class and is nested for only packaging convenience. Read: Java Nested Classes

Example Program: StaticExample.java

Go
package com.journaldev.misc;

public class StaticExample {

    //static block
    static{
        //can be used to initialize resources when class is loaded
        System.out.println("StaticExample static block");
        //can access only static variables and methods
        str="Test";
        setCount(2);
    }
    
    //multiple static blocks in same class
    static{
        System.out.println("StaticExample static block2");
    }
    
    //static variable example
    private static int count; //kept private to control its value through setter
    public static String str;
    
    public int getCount() {
        return count;
    }

    //static method example
    public static void setCount(int count) {
        if(count > 0)
        StaticExample.count = count;
    }
    
    //static util method
    public static int addInts(int i, int...js){
        int sum=i;
        for(int x : js) sum+=x;
        return sum;
    }

    //static class example - used for packaging convenience only
    public static class MyStaticClass{
        public int count;
        
    }

}

Example Test Program: TestStatic.java

Go
package com.journaldev.misc;

public class TestStatic {

    public static void main(String[] args) {
        StaticExample.setCount(5);
        
        //non-private static variables can be accessed with class name
        StaticExample.str = "abc";
        StaticExample se = new StaticExample();
        System.out.println(se.getCount());
        //class and instance static variables are same
        System.out.println(StaticExample.str +" is same as "+se.str);
        System.out.println(StaticExample.str == se.str);
        
        //static nested classes are like normal top-level classes
        StaticExample.MyStaticClass myStaticClass = new StaticExample.MyStaticClass();
        myStaticClass.count=10;
        
        StaticExample.MyStaticClass myStaticClass1 = a new StaticExample.MyStaticClass();
        myStaticClass1.count=20;
        
        System.out.println(myStaticClass.count);
        System.out.println(myStaticClass1.count);
    }
    
}

The output of the above static keyword in java example program is:

StaticExample static block

StaticExample static block2

5

abc is same as abc

true

10

20

</pre>

Notice that static block code is executed first and only once as soon as class is loaded into memory. Other outputs are self-explanatory.

Java Static Import

Normally we access static members using Class reference, from Java 1.5 we can use java static import to avoid class reference. Below is a simple example of Java static import.

Go
package com.journaldev.test;

public class A {

    public static int MAX = 1000;
    
    public static void foo(){
        System.out.println("foo static method");
    }
}
package com.journaldev.test;

import static com.journaldev.test.A.MAX;
import static com.journaldev.test.A.foo;

public class B {

    public static void main(String args[]){
        System.out.println(MAX); //normally A.MAX
        foo(); // normally A.foo()
    }
}

Notice the import statements, for static import we have to use import static followed by the fully classified static member of a class. For importing all the static members of a class, we can use * as in import static com.journaldev.test.A.*;. We should use it only when we are using the static variable of a class multiple times, it’s not good for readability. A Guide to Static Keyword in Java

Jetzt 200 € Guthaben sichern

Testen Sie Ihr Setup auf ccloud³

Registrieren Sie sich in der ccloud³ und erhalten Sie 200 € Startguthaben für Ihr Projekt – z. B. für eine PostgreSQL-VM mit automatischen Backups.

centron Redaktion Technische Redaktion

Das Redaktionsteam von centron schreibt Anleitungen aus dem Betriebsalltag: getestet auf unserer eigenen Plattform, betrieben im Rechenzentrum in Hallstadt bei Bamberg.

Kategorie Linux Basics
Teilen
Noch offene Fragen?

Our team will help you with your specific setup - in German or English, by people who run the platform themselves.

War dieses Tutorial hilfreich?

Your answer is stored anonymously and helps us improve our tutorials.

Kommentare

No comments yet - be the first to ask a question about this tutorial.

Sign in to comment

Comments are open to centron customers. Sign in to your account to ask a question about this tutorial.

Weiterlesen

Das könnte Sie auch interessieren

Jetzt kostenlos anfangen

Melden Sie sich an und erhalten Sie in den ersten 60 Tagen ein Guthaben von 200 € bei centron.

Dieses Werbeangebot gilt nur für neue Konten. Angebot ausschließlich für Gewerbetreibende.

Jetzt loslegen Sales kontaktieren