DEV Community

Mercy
Mercy

Posted on

3

Static variables in Java

Static vs Instance Variables

Whenever a variable is declared as static, this means there is only one copy of it for the entire class, rather than each instance having its own copy.

Static variable
When a static variable is declared, a single copy of the variable is created and shared among all objects at the class level. Static variables are, essentially, global variables. All instances of the class share the same static variable.

Important points to note on static variables
We can only create static variables at the class level.
static block and static variables are executed in the order they are present in a program.
Static variables can be called directly with the help of the class only, we do not need to create an object for the class in this.

// Java program to demonstrate execution
// of static blocks and variables

class Test {

    // static variable
    static int a = m1();

    // static block
    static
    {
        System.out.println("Inside static block");
    }

    // static method
    static int m1()
    {
        System.out.println("from m1");
        return 20;
    }

    // static method(main !!)
    public static void main(String[] args)
    {
        System.out.println("Value of a : " + a);
        System.out.println("from main");
    }
}
Enter fullscreen mode Exit fullscreen mode

The results from the above code:

from m1
Inside static block
Value of a : 20
from main
Enter fullscreen mode Exit fullscreen mode

Static methods can call another static methods or variables using the classname. They can not call an instance method or variable.

Instance methods can call static methods or variables using a className or reference variable. They can call another instance method or variable using instance variables.

The Final Keyword
When a final keyword is marked static, you can not override it. In Java, the final keyword is used to indicate that a variable, method, or class cannot be modified or extended.When a variable is declared as final, its value cannot be changed once it has been initialized.

Designing static methods and fields
Static methods do not require an instance of a class. They are shared among all users of the class. There is only one copy of the code for the instance methods. Each instance of a class can call it as many times as it would like.

when a class loads for the first time the static variables will be given memory. For static variable methods, we use the className instead of the object eg className.variable

Having static methods eliminates the need for the caller to instantiate the object just to call the method. You can also use an instance of an object to call a static method. The compiler will check for the type of the reference and use that instead of the object.

If you make a static reference to a non-static method, you will get a Compiler error.

Only instance methods can call other instance methods on the same class without using a reference variable. Instance methods do require an object.

Key takeaways:

  • An instance method can call a static method
  • A static method can not call an instance method
  • Static variables can not use instance variables
  • Constant variables (status variables) are meant to never change and use the final specifier to make sure the variable never changes.

Final variables can be reassigned when the statickeyword is the first assignment eg If we declare a static final variable, it means we can initialize it exactly once in a static block. If a final variable is declared and never initialised, we get a compiler error.

Feel free to add your knowledge about Static and Instance variables in the comments below.

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay