[java] In laymans terms, what does 'static' mean in Java?

I have been told several definitions for it, looked on Wikipedia, but as a beginner to Java I'm still not sure what it means. Anybody fluent in Java?

This question is related to java static reference

The answer is


The static keyword can be used in several different ways in Java and in almost all cases it is a modifier which means the thing it is modifying is usable without an enclosing object instance.

Java is an object oriented language and by default most code that you write requires an instance of the object to be used.

public class SomeObject {
    public int someField;
    public void someMethod() { };
    public Class SomeInnerClass { };
}

In order to use someField, someMethod, or SomeInnerClass I have to first create an instance of SomeObject.

public class SomeOtherObject {
    public void doSomeStuff() {
        SomeObject anInstance = new SomeObject();
        anInstance.someField = 7;
        anInstance.someMethod();
        //Non-static inner classes are usually not created outside of the
        //class instance so you don't normally see this syntax
        SomeInnerClass blah = anInstance.new SomeInnerClass();
    }
}

If I declare those things static then they do not require an enclosing instance.

public class SomeObjectWithStaticStuff {
    public static int someField;
    public static void someMethod() { };
    public static Class SomeInnerClass { };
}

public class SomeOtherObject {
    public void doSomeStuff() {
        SomeObjectWithStaticStuff.someField = 7;
        SomeObjectWithStaticStuff.someMethod();
        SomeObjectWithStaticStuff.SomeInnerClass blah = new SomeObjectWithStaticStuff.SomeInnerClass();
        //Or you can also do this if your imports are correct
        SomeInnerClass blah2 = new SomeInnerClass();
    }
}

Declaring something static has several implications.

First, there can only ever one value of a static field throughout your entire application.

public class SomeOtherObject {
    public void doSomeStuff() {
        //Two objects, two different values
        SomeObject instanceOne = new SomeObject();
        SomeObject instanceTwo = new SomeObject();
        instanceOne.someField = 7;
        instanceTwo.someField = 10;
        //Static object, only ever one value
        SomeObjectWithStaticStuff.someField = 7;
        SomeObjectWithStaticStuff.someField = 10; //Redefines the above set
    }
}

The second issue is that static methods and inner classes cannot access fields in the enclosing object (since there isn't one).

public class SomeObjectWithStaticStuff {
    private int nonStaticField;
    private void nonStaticMethod() { };

    public static void someStaticMethod() {
        nonStaticField = 7; //Not allowed
        this.nonStaticField = 7; //Not allowed, can never use *this* in static
        nonStaticMethod(); //Not allowed
        super.someSuperMethod(); //Not allowed, can never use *super* in static
    }

    public static class SomeStaticInnerClass {

        public void doStuff() {
            someStaticField = 7; //Not allowed
            nonStaticMethod(); //Not allowed
            someStaticMethod(); //This is ok
        }

    }
}

The static keyword can also be applied to inner interfaces, annotations, and enums.

public class SomeObject {
    public static interface SomeInterface { };
    public static @interface SomeAnnotation { };
    public static enum SomeEnum { };
}

In all of these cases the keyword is redundant and has no effect. Interfaces, annotations, and enums are static by default because they never have a relationship to an inner class.

This just describes what they keyword does. It does not describe whether the use of the keyword is a bad idea or not. That can be covered in more detail in other questions such as Is using a lot of static methods a bad thing?

There are also a few less common uses of the keyword static. There are static imports which allow you to use static types (including interfaces, annotations, and enums not redundantly marked static) unqualified.

//SomeStaticThing.java
public class SomeStaticThing {
    public static int StaticCounterOne = 0;
}

//SomeOtherStaticThing.java
public class SomeOtherStaticThing {
    public static int StaticCounterTwo = 0;
}

//SomeOtherClass.java
import static some.package.SomeStaticThing.*;
import some.package.SomeOtherStaticThing.*;

public class SomeOtherClass {
    public void doStuff() {
        StaticCounterOne++; //Ok
        StaticCounterTwo++; //Not ok
        SomeOtherStaticThing.StaticCounterTwo++; //Ok
    }
}

Lastly, there are static initializers which are blocks of code that are run when the class is first loaded (which is usually just before a class is instantiated for the first time in an application) and (like static methods) cannot access non-static fields or methods.

public class SomeObject {

    private static int x;

    static {
        x = 7;
    }
}

In very laymen terms the class is a mold and the object is the copy made with that mold. Static belong to the mold and can be accessed directly without making any copies, hence the example above


Above points are correct and I want to add some more important points about Static keyword.

Internally what happening when you are using static keyword is it will store in permanent memory(that is in heap memory),we know that there are two types of memory they are stack memory(temporary memory) and heap memory(permanent memory),so if you are not using static key word then will store in temporary memory that is in stack memory(or you can call it as volatile memory).

so you will get a doubt that what is the use of this right???

example: static int a=10;(1 program)

just now I told if you use static keyword for variables or for method it will store in permanent memory right.

so I declared same variable with keyword static in other program with different value.

example: static int a=20;(2 program)

the variable 'a' is stored in heap memory by program 1.the same static variable 'a' is found in program 2 at that time it won`t create once again 'a' variable in heap memory instead of that it just replace value of a from 10 to 20.

In general it will create once again variable 'a' in stack memory(temporary memory) if you won`t declare 'a' as static variable.

overall i can say that,if we use static keyword
  1.we can save memory
  2.we can avoid duplicates
  3.No need of creating object in-order to access static variable with the help of class name you can access it.


In addition to what @inkedmn has pointed out, a static member is at the class level. Therefore, the said member is loaded into memory by the JVM once for that class (when the class is loaded). That is, there aren't n instances of a static member loaded for n instances of the class to which it belongs.


Another great example of when static attributes and operations are used when you want to apply the Singleton design pattern. In a nutshell, the Singleton design pattern ensures that one and only one object of a particular class is ever constructeed during the lifetime of your system. to ensure that only one object is ever constructed, typical implemenations of the Singleton pattern keep an internal static reference to the single allowed object instance, and access to that instance is controlled using a static operation


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to static

What is the equivalent of Java static methods in Kotlin? Creating a static class with no instances Static vs class functions/variables in Swift classes? Call static methods from regular ES6 class methods What is the difference between static func and class func in Swift? An object reference is required to access a non-static member Mocking static methods with Mockito @Autowired and static method The static keyword and its various uses in C++ Non-Static method cannot be referenced from a static context with methods and variables

Examples related to reference

Method Call Chaining; returning a pointer vs a reference? When to create variables (memory management) Reference to non-static member function must be called Cannot find reference 'xxx' in __init__.py - Python / Pycharm c++ "Incomplete type not allowed" error accessing class reference information (Circular dependency with forward declaration) C++ initial value of reference to non-const must be an lvalue Dependent DLL is not getting copied to the build output folder in Visual Studio How to write to error log file in PHP How to reference Microsoft.Office.Interop.Excel dll? Linker Error C++ "undefined reference "