×

Java Static Keyword

It can be either said that static declares the value to be the same, not only in the instance of a class but also as the whole.

To declare a variable or a method as static, we just need to use a static keyword before the variable or method name.

When static is declared, then the memory block for that instance is created only once throughout the program. This behaviour of static keywords makes it memory efficient.

Static keywords can be used with the following:

  1. Variable
  2. Block
  3. Class
  4. Method

Static variable:

The static variable can be used to refer to an attribute that is shared by all objects and is not specific to each object, such as the name of the employer for employees or the school for students.

Since static variables are part of a class, we can directly access them by class name. Therefore, an object reference is not required.

Only at the class level, static variables can be declared.

We don't need to initialize the object to access static fields.

Finally, we can use an object reference to access static fields. But since it becomes challenging to distinguish between instance and class variables, we should avoid doing this. Instead, we should always use the class name to refer to static variables.

Consider the following program to understand the difference between static and non-static variables or instance variables.

StaticDemo.java

class StaticDemo {
   public int count = 0;// non-static variable declaration
   public static int staticCount = 0; // static variable declaration
   StaticDemo() 
  {
      count++; 
      //count for Non -static variable
      staticCount++;
     //count for static variable
   }
   public static void main (String args[]) {
      StaticDemo test = new StaticDemo ();
      StaticDemo test1 = new StaticDemo ();
      StaticDemo test2 = new StaticDemo ();
      System.out.println ("Count: " + test2.count);
      System.out.println ("Static Count: " + test2.staticCount);
   }
}

Output:

Java Static Keyword

Consider the above program, which is defined with a static variable and a non-static variable. We are incrementing both the variable in the constructor and creating three objects for them.

But when coming to the output, you could see the different values for the count variable and static count variable even though we defined them with the same initial value.

This can be understood in simpler terms when every time we create the object for a non-static variable then new reference or location is created.

In the above case, you can observe three objects here. When we call the constructor with each method, a new reference or location is created. This is why we get the count value as 1 for the final output.

When we come across the static variable in the above program, it is being incremented with the previous incremented value. This means that the static keyword creates a single reference or location for a variable and is shared through all the objects.

This can also be said when a non-static variable is created. Then they are specific to the instance object created. In comparison, the static variable can be considered with the global variable, where the static variable is shared among all the object references.

Java Static Keyword

Why we need a static keyword?

The best uses for static variables are in programs that require counters. You might be aware that counters will produce inaccurate results if declared as a normal variable.

For instance, let's say that in an application that has a class called a car, you have a normal variable set as a counter. The standard counter variable will then be initialized each time we create a car object. However, if the counter variable is a static or class variable, it will only be initialised once when the class is formed.

Later, for each instance of the class, this counter will be raised by one. But in the case of a normal variable, the scenario is not the same. In this, the counter will always be at 1, and its value is not increased with each instance.

Therefore, even if you create 100 objects of the class "car," the counter, if it were a normal variable, would always have a value of 1, whereas, if it were a static variable, it would display the accurate count of 100.

Count.java

class StaticCount
{  
    static int count=0;//memory allocated only once and retains its value  
 
    StaticCount()
    {  
        count++;//increment the value of static variable 
        System.out.println(count);  
    }  
}
 
class Count
{
     public static void main(String args[])
    {  
        System.out.println("static count value :");  
        StaticCount sc1=new StaticCount();  
        StaticCount sc2=new StaticCount();  
        StaticCount sc3=new StaticCount();
    }  
}  

Output:

Java Static Keyword

The program mentioned above makes clear how the static variable functions. The static variable count has been declared with an initial value of 0. The static variable is then increased in the class.

We create three objects of the class counter in the main function. The static variable's value is displayed in the output each time the counter object is created. We can see that every time an object is created, the static variable's value is increased rather than reinitialized.

Static Method

In Java, a method is defined to be a static method if it is preceded with a static keyword in a method declaration.

In every java program, there will be a default static method defined, i.e., the main method.

Some important points about the static method:

You don't need a class object to call a static method.

The class's static method has access to the member’s static data. Even the static data member's values can be modified by the static method.

This or super member references are not permitted in static methods. Even if a static method tries to refer to them, a compiler error will result.

The static method may also invoke other static methods, just like static data.

A static method can neither call nor refer to non-static methods or non-static data members or variables.

StaticMethod.java

class StaticMethod
{
    // static variable declaration
    static int static_count = 5;
 
    // instance variable declaration 
   // instance variable cannot be accessed in a static method
   // you can understand it in this program 
    int inst_var = 10;
 
    // static method declaration 
    static void staticDemo()
    {
       static_count = 20;
       System.out.println("static method StaticDemo "+static_count);
 
       // inst_var = 20; // compilation error "error: non-static variable inst_var cannot be referenced from a static context"
 
        //instMethod ();  // compilation error "non-static method instMethod () cannot be referenced from a static context"
 
        //System.out.println (super.static_count); // compiler error "non-static variable super cannot be referenced from a static context"
     }
 
    // instance method declaration 
    void instMethod ()
    {     
           System.out.println ("instance method instance Method");
    }
 
    public static void main (String [] args)
    {
         staticDemo ();  
    }
}

Output:

Java Static Keyword

You can see that there are two methods in the above program. While instMethod is an instance method, StaticDemo is a static method. Additionally, there are two variables: inst_var is an instance variable, and static_count is a static variable.

Instance variables, calling non-static methods, and referring to super in a static context all result in compilation errors when the program with the above lines is executed. These represent the static method's drawbacks.

The program above only runs smoothly and generates the output shown below when we comment on the three lines.

Static Block

In Java, there is a special block called a "static" block that typically contains a block of code related to static data, much like function blocks in programming languages like C++, C#, etc.

When the static member inside the block is used or when the first object of the class is created (exactly during classloading), this static block is executed.

StaticBlock.java

class StaticBlock
{
static int a=10;
int b;
static
{
b=a*4; // compilation error  non-static variable b cannot be referenced from a static context
System.out.println("Static Block execution");
}
  public static void main(String args[])

{
System.out.println(a+"  " +b);
}
}

Output:

Java Static Keyword

You get the above error when you execute the above code because you are trying to use a non-static variable inside a static block. To resolve this, you need to declare the non-static variable as static.

You can check this in the below program.

class StaticBlock
{
static int m=10;
static int s;
static
{
s=m*4; 
System.out.println("Static Block execution");
}
  public static void main(String args[])

{
System.out.println(m+"  " +s);
}
}

Output:

Java Static Keyword

Related Topics

Interface in Java

  Interface in Java In Java, the interface is just like a class that has only static constants and abstract methods. It is used to achieve polymorphism so that it can also...

6 minutes read.

Java Socket Programming

Java Socket Programming Socket programming is used for the communication between the applications, i.e., client and server running on different JRE may be connection-oriented or connectionless. The client program can be designed using the...

8 minutes read.

How to achieve Multiple Inheritance in Java

Multiple Inheritance is the type of inheritance where one class inherits the properties of more than one super class. For example, class Child inherits (extends) the classes Father and Mother....

4 minutes read.

Collections in Java

Collection framework is one of Java's most powerful subsystems. It is a set of classes and interfaces that is all-the-rage technology for superintending objects and a group of objects. In...

6 minutes read.

Java calculate age

In this section, we will create a Java program that calculates age from the given date of birth or current date. In order to get the date of birth from the current...

6 minutes read.

How to Convert Decimal to Binary in Java

How to Convert Decimal to Binary in Java There are two methods to convert Decimal to Binary. Using toBinaryString() method Using user-defined logic Using Integer.toBinaryString() The toBinaryString() is a static method of Integer...

2 minutes read.

Differences between Lock and Monitor in Java Concurrency

In this tutorial, we will discuss the overview of Lock and Monitor and the differences between them. Introduction Java Concurrency is the ability to perform specific tasks at a time parallelly. The...

4 minutes read.

Java Tokens

Classes and methods are included in the Java program. The procedures also provide the expressions and statements required to finish a specific operation. Tokens make up the sentences and expressions...

4 minutes read.

How to Import Packages in Java

To know about the importing the packages of Java, we need to understand about how to packages work. Packages The package in Java is a collection of Classes and Interfaces. The packages...

3 minutes read.

Tribonacci series in Java

The Fibonacci series and the Tribonacci sequence are linked. The Fibonacci sequence, each element summates the three preceding terms, is expanded into the Tribonacci series in Java. Through specific examples,...

3 minutes read.

Java Subtract Days from Current Date

Dealing with date and time in Java is not a particularly challenging operation because Java has an API for date and time that simplifies duties for developers. There are two...

3 minutes read.

XNOR operator in Java

The opposite of the binary equivalent of XOR is given by XNOR. Truth table: XYXNOR001010100111 If the bits are the same, it returns 1, else it returns 0. Examples:  Input: 10 20 Output : 1 A Binary...

3 minutes read.

Difference between Static and Instance Methods in Java

Static Method in Java The static technique has a place with the class as opposed to the object of the course. These are intended to be divided between every one of...

10 minutes read.

Java Swing Time Picker

Prerequisites In this tutorial, we will learn the time picker in java swing. Before learn time picker, we should learn about java swing. Java Swing Introduction The Java Foundation Classes include Java Swing....

5 minutes read.

How to download and install Eclipse in Windows?

Download and Install Eclipse on Windows Eclipse is an open source IDE (Integrated Development Environment) which is used to help the programmers to provide a platform to write and run the...

1 minute read.

Creating a Custom Generic Class in Java

To indicate parameter types when creating generic classes, we utilize the <> symbol. The syntax used to generate objects of a generic class is as follows. // To create an instance...

4 minutes read.

Null Pointer Exception in Java

It is a runtime error exception. The null value is allocated to the object reference in this exception. We will explicitly throw this null pointer exception when the program wants...

3 minutes read.

Series Program in Java

Series Program in Java The series program in Java is written to print the mathematical series such as the Fibonacci series, Pell series, etc. A few of the renowned series are...

12 minutes read.

How to Run Applet Program in Java

An applet is a new type of program which is put in a webpage. By inserting applet into a webpage dynamic content can be created. Characteristics of an Applet The applet is...

11 minutes read.

Array Slicing in Java

Array slicing is a method in Java for obtaining a subarray of a specified array. Assume a[] is an array. It contains eight items indexed from a[0] to a[7].a[] =...

3 minutes read.