Tutorial

static keyword in java

Published on August 4, 2022
author

Pankaj

static keyword in java

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.

static keyword in java

java static, static keyword in java Java static keyword can be used in five cases as shown in below image. static keyword in java We will discuss four of them here, the fifth one was introduced in Java 8 and that has been discussed at Java 8 interface changes.

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

        //static variable example
        private static int count;
        public static String str;
        public static final String DB_USER = "myuser";
    
  2. 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.

        //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. For more details please read Java 8 interface changes.

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

        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);
        }
    
  4. 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

Let’s see all the static keyword in java usage in a sample program. StaticExample.java

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;
        
    }

}

Let’s see how to use static variable, method and static class in a test program. TestStatic.java

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 = 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

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.

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. Update: I have recently created a video to explain static keyword in java, you should watch it below. https://www.youtube.com/watch?v=2e-l1vb\_fwM

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Pankaj

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
February 8, 2013

Can you please explain me difference between singleton pattern and object created through Static keyword.What are the advantages of singleton pattern.

- Arya

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    May 16, 2013

    Pankaj Sir, your blog help me lot to understand the basic concept of JAVA. Thank you sir .

    - Sumit hazra

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      July 30, 2014

      Hello Pnakaj Sir, First i would like to thank you for very good blog in every concept in java. Here i have one question related static block and static variable. what is the load first static block else static variable. “My understanding is first static variable will be loaded”. But i am confused for below code please help me. In the below program i have declared static block first. public class StaticRud { static { a = 20; } private static int a = 10; public static void main(String[] args) { System.err.println(StaticRud.a); } } Out put is : 10 ============================= and in the below code i have declared static variable first public class StaticRud { private static int a = 10; static { a = 20; } public static void main(String[] args) { System.err.println(a); } } Out put is : 20 Is there any way to declare static variable before or after static block? Please help me sir.

      - Sahdev

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        July 9, 2015

        Is it possible to implement static methods in interface before Java 8 ? What is the improvement that would be brought in with this change in Java 8 static mehtods in interface.?

        - Davinder

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          August 30, 2015

          Why static block is needed , though we can intialize static variables at the time of declaring static variable

          - Gurpreet Singh

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            November 16, 2015

            Static Variable and Static Block are executed before Main method gets executed,but Static Variable and Static Block are executed based on the order we are declare from top to bottom

            - Sonia

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              December 23, 2015

              Hi, I know that, for the sake of your example, you created a StaticExample() object (se) to compare its .count with StaticExample class .count object . My question is: don’t you need a constructor to create an object? Thanks

              - Emanuele

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                April 28, 2017

                Hi, I need to ask you a question after reading How do you gain your knowledge as you answered from video tutorials and some e-books so If I depend on your blog to gain my knowledge it will be not enough to be a good java developer and crack java interviews, Thanks in Advance

                - mossama

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  July 20, 2017

                  this article is very useful. it clear all the doubts about static keyword in java. thank you

                  - Anurag Singh

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    August 2, 2017

                    hi Pankaj, thanks for great article T i have question please answer me if we have static gloabal object, where store in memory??? heap or …??? generaly static object different place stored than another object ??? please cleear me

                    - milad

                      Try DigitalOcean for free

                      Click below to sign up and get $200 of credit to try our products over 60 days!

                      Sign up

                      Join the Tech Talk
                      Success! Thank you! Please check your email for further details.

                      Please complete your information!

                      Become a contributor for community

                      Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                      DigitalOcean Documentation

                      Full documentation for every DigitalOcean product.

                      Resources for startups and SMBs

                      The Wave has everything you need to know about building a business, from raising funding to marketing your product.

                      Get our newsletter

                      Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

                      New accounts only. By submitting your email you agree to our Privacy Policy

                      The developer cloud

                      Scale up as you grow — whether you're running one virtual machine or ten thousand.

                      Get started for free

                      Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

                      *This promotional offer applies to new accounts only.