Scientech Easy Static Variable in Java with Example & Advantage | Scientech Easy

Tuesday, September 11, 2018

Static Variable in Java with Example & Advantage

Generally, when we create a class, we are describing how objects of that class look and how will they behave. We don't know anything until we create an object of that class using the new keyword and at that time, data storage is created and methods become available but If we need a method that is not associated with any particular object of the class and can call even if no objects are created. So we can achieve both with the help of static keyword. That is when you say something is static, it means that the data or method is not tied to any particular object of that class rather than to individual object or instance. Let's discuss Static keyword in more details.

What is Static in Java?


➲ Static means single copy storage for variable or method. In other words, The members are not tied to a particular instance. i.e, the static members are shared across all the instances of the object.
➲ Static is a keyword which is used for memory management mainly.
➲ It can be applied with variable, methods, inner class, and block. In this tutorial, we will learn only static variable with the practical example and programs. 
➲ We cannot declare a class with static but the inner class can be declared as the static.
➲ It belongs to the class than the instance of the class.
➲ One basic rule of working with the static method is that we cannot directly access the instance(non-static) method or field from a static method. In other words, we cannot directly call instance members within the static area because the static members are linked with the class and they get memory once when the class is loaded but Instance members get the memory after the object creation of the class. Therefore, when we call any instance members within the static area, it means that when the class is loaded into the memory, the static members also loaded into the memory and it will look the instance members that are not in existence because we have not created any object till now. Hence, there is the ambiguity. 
For example:
  public class Teststatic{
     private int a=10; // an instance field.
    public static void main(String[] args) {
          int b=a; // error: won't compile.
      }
    }
   Here, main method is static. so we cann't access the instance variable a.
However, we can access the static methods or fields from the instance method. Let's take one simple example program.

What is the purpose/use of static in Java?


➲ The purpose of static keyword in Java is that we can access the data, method or block of the class without any object creation. Let's understand with a simple example. 
As you know that the main method is static in Java because the object is not required to call the static method. If it is non-static method then JVM will create an object first and then it will call the main() method which creates the problem of an extra memory location.
➲ It is used to make the programs more memory efficient.

Static Variable


➲ A Static variable is also known as a class variable.
If you declare any variable as static, it is known as a static variable.
For example: 
     private static int age;
If you declare an instance variable, a separate copy will be created for every object but in the case of a static variable, a single copy is created at the class level and shared by all objects of that class.
It can be accessed in any other class using the class name.
For example:
   A.x; // A is the class name and "x " is a static variable declared in that class.

A static variable can also be accessed by the object. 
For example:
I have a class name as Student. Now we can create the object of the Student class.
    Student s=new Student();
      s.x;
Let's see a simple program.
Program source code 1: 
    package staticvariable; public class Student { // Declare an static variable id with data type int and assign it the value 1468. static int id=20; public static void main(String[] args) { // Create the object of the class Student Student s=new Student(); // Call the S.V. using object reference variable s and store it by x variable with data type int. int x=s.id; // Print on the console. System.out.println(x); // Now Call the S.V. using the class name. System.out.println(Student.id); } }
    Output: 20 20

➲ It is used to refer to the common property of all objects. e.g Company name of employees, School name of students etc.
Program source code 2:
    package com.scientecheasy; public class Employee { // Declare instance variable String name; int id; // Declare S.V. companyName with data type String and assign value IBM which is common for all the objects. static String companyName="IBM"; // Declare a two-parameter constructor with parameters named n and i. Employee(String n, int i){ name=n; id=i; } // Declare an instance method display and print the output on the console. void display(){ System.out.println("Name: "+name+ " " +"Id= "+id+ " " +"Company Name:"+ " " +companyName); } public static void main(String[] args) { // Create the first object of the class and pass the two arguments with type string and int. Employee e=new Employee("Shubh", 123); // Call the display method using reference variable e. e.display(); // Similarly, create the second object of the class and pass the two arguments. Employee e1=new Employee("Deep", 321); e1.display(); } }

    Output: Name: Shubh Id= 123 Company Name: IBM Name: Deep Id= 321 Company Name: IBM .

In this example, companyName refers to the "common property" of all the objects because companyName is a static variable and it will get memory only once

How to increment a static variable in Java?


When a class is loaded into the memory, the static variable is created and initialized into the memory only once. That is, the static variable gets loaded into the memory at the time of class loading. If any object changes the value of the static variable, it will retain its value and increments by 1 for every object creation.  Let's see an example to understand the concept.
Program source code 3:
    package com.scientecheasy; public class Counter { static int x=0; // It will get memory only once and retain its value. Counter(){ x++; // It will increment the static variable by 1 for each object creation. } void display(){ System.out.println(x); } public static void main(String[] args) { Counter c1=new Counter(); c1.display(); Counter c2=new Counter(); c2.display(); Counter c3=new Counter(); c3.display(); } }
You can see the below image to understand the concept.
static variable in java with example and advantage, static keyword in java, java static,non static variable in java,why we use static variable in java, How to increment a static variable?
How to increment a Static variable in Java?


    Output: 1 2 3

➲ A local variable cannot be declared as static. JVM will display modifier error at compile time.

Can we access the instance member from the static area directly?


➲ Instance member(non-static member) can be accessed only from instance area directly and we cannot access the static area directly. That is we cannot call instance member from the static member because static variable stores into the memory before the object creation and instance variable stores into the memory after the object creation. For more detail, Read the concept in the method tutorial.
So when we access instance member by static member as they are not present in the memory, it will give the compile-time error.

➲ The Static member can be accessed from both instance and the static area directly using the class name or without the class name but outside the class, we can call only using the class name. 
Program source code 4:
    package com.scientecheasy; public class Test { // Instance area int a=10; //Instance variables. static int b=30; // Static variable // Declare an instance method. void m1(){ // We can call instance variable directly from instance area without any object reference variable. System.out.println(a); // Call the static variable directly from instance area. System.out.println(b); } static void m2(){ // Static area. // We cannot call instance member from static area. System.out.println(a); // here compile time error. because at this time, the object of the class is not created. so we cannot call the instance variable using object reference variable. } public static void main(String[] args){ // Static area. Test t=new Test(); t.m1(); // Here we can call instance member using object reference variable t in the static area. System.out.println(t.a); m2(); } }
    Output: 10 30 10 Compile time error.
Program source code 5: In this example, we will declare the static variables in a class Calculation and will call in another class CalculationTest using the class name. After that, we will perform a simple addition and subtraction operation and print output on the console. 

    package com.scientecheasy; public class Calculation { static int x=20; static int y=30; }
    package com.scientecheasy; public class CalculationTest { void addition(){ // Call S.V. using class name. int a=Calculation.x; int b=Calculation.y; int c=a+b; System.out.println(c); } void subtraction(){ int p=Calculation.x; int q=Calculation.y; int r=p-q; System.out.println(r); } public static void main(String[] args) { CalculationTest ct=new CalculationTest(); ct.addition(); ct.subtraction(); } }
    Output: 50 -10

Advantage of Static variable

It makes program memory efficient. i.e It saves memory. All the static variables are stored in PermGen space of the heap memory.

Difference between Static variable and Instance variable

1. A static variable is also known as class variable whereas Instance variable is also known as non-static variable.
2. Static variable can be accessed inside the static block, instance block, static method, instance method, and method of the inner class whereas Instance variable can be accessed inside the instance block, instance method, and method of the inner class.
3. It is always resolved during compile time whereas Instance variable is resolved during the runtime.
4. Static variables are not serialized in Java whereas Instance variables are serialized in Java.


Final words:
We hope that this article will help you to understand the concept of Static Variable with example and programs. In this article, we have covered almost all the important topics with practical concepts. In the next tutorial, we will see the static method.



Hot Post

Java Collections Framework | Need & Advantages