BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Java – static variable with example

Last Updated: September 11, 2022 by Chaitanya Singh | Filed Under: java

A static variable is common to all the instances (or objects) of the class because it is a class level variable. In other words you can say that only a single copy of static variable is created and shared among all the instances of the class. Memory allocation for such variables only happens once when the class is loaded in the memory.
Like variables we can have static block, static method and static class, to read about them refer: static keyword in java.

Static variable Syntax

static keyword followed by data type, followed by variable name.

static data_type variable_name;

As I mentioned above that the static variables are shared among all the instances of the class, they are useful when we need to do memory management. In some cases we want to have a common value for all the instances like global variable then it is much better to declare them static as this can save memory (because only single copy is created for static variables).

lets understand this with an example:

Static variable example in Java

class VariableDemo
{
   static int count=0;
   public void increment()
   {
       count++;
   }
   public static void main(String args[])
   {
       VariableDemo obj1=new VariableDemo();
       VariableDemo obj2=new VariableDemo();
       obj1.increment();
       obj2.increment();
       System.out.println("Obj1: count is="+obj1.count);
       System.out.println("Obj2: count is="+obj2.count);
   }
}

Output:

Obj1: count is=2
Obj2: count is=2

As you can see in the above example that both the objects are sharing a same copy of static variable that’s why they displayed the same value of count.

Example 2: Static Variable can be accessed directly in a static method

class JavaExample{
  static int age;
  static String name;
  //This is a Static Method
  static void disp(){
      System.out.println("Age is: "+age);
      System.out.println("Name is: "+name);
  }
  // This is also a static method
  public static void main(String args[]) 
  {
	  age = 30;
	  name = "Steve";
      disp();
  }
}

Output:

Age is: 30
Name is: Steve

Static variable initialization

  1. Static variables are initialized when class is loaded.
  2. Static variables are initialized before any object of that class is created.
  3. Static variables are initialized before any static method of the class executes.

Default values for static and non-static variables are same.
primitive integers(long, short etc): 0
primitive floating points(float, double): 0.0
boolean: false
object references: null

Static final variables

The static final variables are constants. Lets have a look at the code below:

public class MyClass{
   public static final int MY_VAR=27;
}

Note: Constant variable name should be in Caps! you can use underscore(_) between.
1) The above code will execute as soon as the class MyClass is loaded, before static method is called and even before any static variable can be accessed.
2) The variable MY_VAR is public which means any class can use it. It is a static variable so you won’t need any object of class in order to access it. It’s final so the value of this variable can never be changed in the current or in any class.

Key points:
final variable always needs initialization, if you don’t initialize it would throw a compilation error. have a look at below example-

public class MyClass{
    public static final int MY_VAR;
}

Error: variable MY_VAR might not have been initialized

Top Related Articles:

  1. Static and dynamic binding in java
  2. How to check if a File is hidden in Java
  3. OOPs in Java: Encapsulation, Inheritance, Polymorphism, Abstraction
  4. Constructor Overloading in Java with examples
  5. Java – Static Class, Block, Methods and Variables

Tags: Java-OOPs

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Comments

  1. Poonam Marathe says

    January 19, 2015 at 5:46 PM

    where static variables are get stored?and how they work?

    Reply
    • Kiran says

      October 5, 2015 at 7:53 AM

      Heap memory

      Reply
    • subhani says

      July 1, 2016 at 2:25 PM

      Static variables stored in static memory . If you write 2 static methods in your code, while executing java program class loader first load the class and then look for how many static methods in program ,let us assume in our program we have 2 , so it’s create memory for those in static area. These all process running under JRE. Class loader and JVM helps to storing and allocated memory to static variable. After that garbage collector check the any wastage memory in code or not.

      Reply
  2. Niru says

    April 9, 2015 at 3:07 PM

    in the first example,we have to call the variable in a static way since it
    is a static variable…

    Reply
  3. swetha says

    November 9, 2016 at 7:35 PM

    Can we access static variables through objects?

    Reply
    • Moe says

      December 2, 2016 at 3:25 AM

      Yes we can access. All objects will get same copy of static variable

      Reply
    • fayaz says

      December 20, 2016 at 4:24 PM

      Hi Swetha,

      Yes we can access static variable through objects or by directly using class name.Please correct me if i am wrong.

      Reply
  4. Sri says

    January 24, 2017 at 11:35 AM

    when you have three variable like
    int rollNumber;
    String SchoolName
    String StudentName
    Which one we have to make static and final. Why?
    Can anyone explain me this?

    Reply
  5. Govardhan Matkar says

    February 8, 2017 at 2:24 AM

    Hi Siri

    We gives static keyword to those variables who initialise only once
    but here we can give static final keyword to school name
    It will not change coz of final and
    It will accessible in whole program becoz of static keyword

    Pls correct me if I am wrong

    Thanks
    Govardhan

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap