Which variable allow you to create a single copy of it and to share the same among all the instance of the class?

What is a Static Variable in Java

Let’s start this article with a real life example. Consider a machine that produces different varieties of pens like blue, black, green, etc for two different companies.

All pens are different in their properties like some of them are blue having different body structure and some of them are black but one attribute is common among all the pens is its company name i.e ‘X’. All pens that are manufactured for a particular having the same company name i.e ‘X’.

After some time if we want to manufacture pens for a second company we simply update the company name variable to the name of the second company and after that, all pens that will be manufactured will be of the second company.

Now consider if we want to implement the above example in a programming way. We can simply implement the above example in a simple form of class.

class Pens{
    String pen_type; //Type of pen whether gel or another
    String color;  //Color of the pen
    int length;  //Length of the pen
    static String companyname;  //static variable
}

Now understand why the companyname variable is of static type because static variables are equally shared among all the objects of the class and also we are manufacturing pens symmetric procedure for first then second.

We can also initialize the companyname without static but this is not an efficient way the memory consumption is very much more in this case because for every object of this class a copy of companyname is initialized in the memory but if we initialized the companyname as static the memory allocation for this variable is different and also this variable is shared among all the instances of the class. In this article, we will discuss the static variables in java.

Static Variable in Java

The static variables are those variables that are common to all the instances of the class; only a single copy of the static variable is created and shared among all the instances of the class. Because it is a class-level variable, memory allocation of such variables only happens once when the class is loaded in the memory.

What is the Use of Static Keyword in Java

The main use of the static keyword in java is used to manage the memory management in java. Whenever we place a static keyword before the initialization of a particular class’s methods or variables, these static methods and variables belong to the class instead of their instances(Objects).

Syntax of Static Variable in Java

The syntax of the static variable is similar to the syntax declaration of the static variable in java but the static keyword is used before the declaration of the variable.

`Static Datatype Variablename= Value`
  1. static: static is the keyword in java.

  2. Datatype: Datatype is the type of data that we want to store in the given variable.

  3. Variable Name: Valid name of the variable.

  4. Value: Initial value of the variable.

Which variable allow you to create a single copy of it and to share the same among all the instance of the class?

Example: Country.java

class Country{
//static variable 
    static int countryCounter;
    String name;
    int dummyCounter;
    public static void main(String[] args) {
   //Creating first instance
    Country ob1=new Country();
    ob1.name="India";
    ob1.dummyCounter=1;
    ++countryCounter;
//Creating second instance of the class
    Country ob2=new Country();
    ob2.name="france";
    ob2.dummyCounter=1;
    ++countryCounter;
    }
}

In the above example, we have a user-defined class country.java that has two class variables and one static variable.

First, we create the first instance of this class and increase the static variable named as countryCounter by one then we create a second instance of the class and increase the countryCounter by 1.The resultant value of the countryCounter is 2 because countryCounter is a static variable in java and due to the property of the static variable. It is shared among all the instances of the objects.

Working on the above program diagrammatically.

During compilation of the country.java file, the java compiler binds the static variables with the class as in this case countryCounter variable is bind to the compiled class.

We can see in the below diagram that the static variable countryCounter is linked to the class and this variable is shared among all the class instances.

In this case, two instances of the country class are accessing the same static variable shown below in the diagram. When we increment the countryCounter variable one because this variable is a static variable and static variable is a class variable so any changes in these variables are reflected among all the instances of the class so after the first increment the value of countryCounter is 1 and after another increment, the final value is 2.

Which variable allow you to create a single copy of it and to share the same among all the instance of the class?

Storage Area of Static Variable in Java

Before the Java 8 version, static variables of the class were stored in the separate section of the non-heap memory name as a memory area created by the Java virtual machine after compilation of the class. Method area section was used to store static variables of the class, metadata of the class, etc. Whereas, non-static methods and variables were stored in the heap memory.

Which variable allow you to create a single copy of it and to share the same among all the instance of the class?

After the java 8 version, static variables are stored in the heap memory.

Properties of Static Variables in Java

Whenever we declare a variable in the program after initialization it acquires properties of the initialized data type and that’s how variables are designed. for eg:

String name; // name variable can store only string data value
int number;  //number variable can store only numeric data value

How to Declare a Static Variable in Java

Whenever we used static keywords before the initialization of the variable. The static keyword indicates to the JVM(java virtual Machine) that this variable should be loaded with the class whenever the class will be loaded during the compilation of the program.

If we don’t initialize the static variable the default value of the static variable data type will be automatically assigned to the static variable in java.

Declaration Examples

static int number=2 // valid declaration of the static variable
Static int number=2 //Invalid declaration of the static variable
static int number; //valid declaration of the static variable

Example:

public class Scaler {
//Creating two static members
static boolean check;
static int number;
    public static void main(String[] args) {
System.out.println(Scaler.check); //Default value is false
System.out.println(Scaler.number); //Default value is 0.
 
    }
}

Output:

If we don’t assign an initial value to any static variable the default value is automatically initialized to that particular variable. In the above example, there are static variables one of boolean type and the second is an integer type.

We didn’t initialize these variables so whenever we try to access these variables we will get the default values of these variables. False for boolean type variable and the 0 for integer. These are the default values for these data types.

Declaration Scope of the Static Variables in Java

We cannot declare static variables in the main method or any kind of method of the class. static variables must be declared like a class member in the class.

Because during compilation time JVM binds static variables to the class level that means they have to declare like we declare class members in the class. The static variables can be used only in the class scope where they are defined.

Example

class ABC{
    static int number; // valid declaration
   void hello(){
       static int number1; //invalid declaration
   }
    public static void main(String[] args) {
        static String name;  //Illegal modifier 
    }
}    

The static variables in java can be declared like class members of the class like static int number, is the valid declaration of the static variable but static variables cannot be declared in any kind of method.

If we try to declare static variables inside static or nonstatic methods, the compiler will show a syntax error. In the above example if we try to declare a static variable in the main method the compiler will show an illegal modifier syntax error. Because static variables are class variables rather than a particular method of the class, if we try to initialize the static variables inside the static methods, the compiler will show syntax error.

Initialization of Static Final Variables in Java

The static variables are also used as constants with the final keyword in java. Constants must be initialized and any kind of update is not allowed on them. Let’s understand this with an example.

class Scaler{
static final int a=23; //Creating static constant variable 
static final int b; //Compiler will show an error final variables
                    //Must be initialized.
 
    public static void main(String[] args) {
System.out.print(a);//23 will be printed
a++; //Any changes is not allowed on the final variables
     //Compiler will show an error 
 
    }
}

In the above example, if we don’t initialize the static variables compiler will show an error during compilation time in the above program final static variable b is not initialized here we have to initialize these final variables with the default value of the integer or any suitable integer value.

The final keyword restricts any changes in the variable so any kind of increment, decrement, or any other change will violate this restriction and that’s why the compiler will show an error in the above case “a++” line is not a valid statement.

Accessibility of the Static Variables in Java

Static variables can be accessed by calling the class name of the class. There is no need to create an instance of the class for accessing the static variables because static variables are the class variables and are shared among all the class instances.

The static variables can be accessed in the static methods only if we try to access the non-static variables in the static method compiler will show an error because non-static variables can only access by creating an instance of the class only but static methods can be called without creating an instance of the class and this leads to reference error for the non-static variable because non-static variables can be accessed only through the instance of the class that’s why static methods cannot access non-static variables.

public class Scaler {
int number;
static void check(){
    System.out.println(number); //Reference error cannot access non static 
}                               //variables
void check1(){
    System.out.println(number); //Valid accessing
}
    
}

In the above example, a non-static variable named “number” is called in two methods: one is a static method and the other is a non-static method i.e check1().

When the nonstatic variable is called inside the static methods, java compiler will show a reference error because we can only access the non-static variable only after creating an instance of the class but static methods can be called without creating an instance of the class that’s why during accessing the nonstatic variable in the static methods compiler will show reference error.

Syntax for Accessing

Classname.variablename(static variable).

  • Classname: Name of the class containing static variables:
  • (.) dot operator: Operator used to access static variables.
  • Variablename: Name of static variable that needs to be called.

    Which variable allow you to create a single copy of it and to share the same among all the instance of the class?

    Example

public class Main {
static int ans=0;
public static void main(String[] args) {
++ans;
System.out.println(Main.ans++); //value of ans is 1
Main ob=new Main();
System.out.print(ob.ans); //warning here but this line will print 1
 
    }
}

In the above example, the static variable named “ans” is accessed in two ways. One way is without creating an instance of the class using the class reference only and the second way is using the instance of the class.

While accessing the static variable in java using the instance of the class, the compiler will show a message “The static field main.a should be accessed in a static way”. Because there is no need to create an instance of accessing the static members of the class.

1. Common for all instances

static variables are common for all the instances. A single copy of the static variables is shared among all the instances of the class instances that means any changes on the static variables by an instance of the class changed its original value.

Example

public class Scaler {
    static int number;
    
    public static void main(String args[]){
        Scaler ob=new Scaler();
        Ob.number++; //Increment the value of static variable number is 1
        System.out.println(Scaler.number); //printing the static variable1
        Scaler ob1=new Scaler();
        ob1.number++; //Increment the value of static variable number is 2
        System.out.print(Scaler.number);//Printing the static variable  //value 2
    } 
}

In the above example, a single copy of the static variable in java, i.e,number is shared among all the two instances of the class first instance named as ob increment the value by 1 and the second instances named as ob1 increment the value of a static variable number by 1 and the final value of the number is 2,

Class containing static members and non-static members:

main.java

public class Scaler {
//static variable
    static int count_clicks;

    String name;
    void insert(String name){
        //increment count_clicks
        ++count_clicks;
        this.name=name;
    }
    public static void main(String[] args) {
        Scaler object=new Scaler();
        object.insert("hello");
        Scaler object1=new Scaler();
        object1.insert("bye");
        scaler object2=new Scaler();
        object2.insert("thankyou");
       System.out.println("total clicks "+count_clicks);
    }
}

Output:

In the above program, static variable count_clicks is called by every new instance of the class and the class function insert the name for every new instance and increment the count_clicks due to the property of the static variable that is a static variable is shared among all the instances of the classes any changes done due to any instance automatically update its original state. In the above program, we call static members three times. Hence the output is 3.

Memory Management of the above program:

Which variable allow you to create a single copy of it and to share the same among all the instance of the class?

Whenever we create an instance of the class, a separate copy of all the class methods and variables except static members is created for all respective instances of the class in the heap memory. In the above example the method name as insert() is called by the three instances of the class and each time insert() method is called the value of count_clicks is increment by one and also count_clicks is a static variable and this is equally shared among all the instances of the class so any changes on this variable are reflected among all the instances of the class.

A Real-Life Example of Static Variables in Java

The simplest real-life example of a static variable is supposed to have a class named as a student that is used to define the details of the particular student that took admission in the school. Now we have to count how many students took admission in the school.

In this case, the concept of static variable in java is used we simply create a static variable named count_student in the constructor of the student class and whenever we create a new instance of the class for a new student count_student will automatically increase by 1.In this way we can count the total number of new students took admission in the school.

Conclusion

This article discussed static variable in java, Properties, Applications, memory management of static variables. The most common application of the static variables in java is to store any path pretext, specification, and versioning of the project because path pretext is the same for all the files created in a particular project and if we want to transfer all files from another directory. We simply update the path of all files which are stored in a static variable that is common for all the files of a particular project.

Happy coding…

Which variable allow you to create a single copy of it and to share the same among all the instances of the class?

A static variable is shared by all instances of a class. Only one variable created for the class.

What kind of variable do you use if you need to share a variable from one instance of a class to the?

You need to make the variables in class aaa as class variables, and then you can use these variables of class aaa in class bbb by using object of class aaa. e.g.

What is a variable associated with a class or with an instance of a class?

They are associated with the class, rather than with any object. Every instance of the class shares a class variable, which is in one fixed location in memory. Any object can change the value of a class variable, but class variables can also be manipulated without creating an instance of the class.

What is static and global variable?

A global variable can be accessed from anywhere inside the program while a static variable only has a block scope. So, the benefit of using a static variable as a global variable is that it can be accessed from anywhere inside the program since it is declared globally.