Logo

dev-resources.site

for different kinds of informations.

Static variables in Java

Published at
1/13/2025
Categories
java
springboot
tutorial
beginners
Author
devmercy
Author
8 person written this
devmercy
open
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.

springboot Article's
30 articles in total
Favicon
Launched a Web version of my Project using Java Spring Framework, Spring Boot Web
Favicon
Understanding Spring Security and OAuth 2.0
Favicon
Spring Oauth2 - App-Token based Hybrid Token Verification Methods
Favicon
Static variables in Java
Favicon
What is Spring AI ? Example of a chat API with multiple LLMs
Favicon
Quando usar ResponseEntity?
Favicon
App-Token based easy OAuth2 implementation built to grow with Spring Boot
Favicon
[Boost]
Favicon
Spring Boot 3 application on AWS Lambda - Part 14 Measuring cold and warm starts with GraalVM Native Image and memory settings
Favicon
SpringBoot Web Service - Part 5 - Github Action
Favicon
Apache wicket with spring boot example application: notice board
Favicon
OTP Authentication: The Passwordless Superhero of Your App! πŸ¦Έβ€β™‚οΈβœ¨
Favicon
SpringBoot Web Service - Part 1 - Create Repository
Favicon
SpringBoot Web Service - Part 2 - Preparing Using Spring Initializr
Favicon
Zero Config Spring Batch: Just Write Business Logic
Favicon
Generate a REST API Using Java and Spring Boot for your Postgres database
Favicon
How to optimize SpringBoot startup
Favicon
Spring Boot: About @SpringBootApplication
Favicon
Introduction to Spring Boot: A Complete Guide
Favicon
Wednesday Links - Edition 2025-01-01πŸŽ‰
Favicon
SpringBoot Web Service - Part 4 - Initial Configuration
Favicon
How to implement detekt in Spring Boot + Kotlin + Gradle project
Favicon
Building Resilient APIs: Mistakes I Made and How I Overcame Them
Favicon
Web Scraping Summarization with Vite React TypeScript and Spring Boot
Favicon
Handling NullPointerException with Optional
Favicon
Overview of Lock API in java
Favicon
Optimizing Serverless Lambda with GraalVM Native Image
Favicon
With Spring can I make an optional path variable?
Favicon
Building a Vue CRUD App with a Spring Boot API
Favicon
Hexagonal Architecture β€” A Favorite Lyrics Spring Boot β€” Java Example

Featured ones: