×

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

TreeSet in Java

Java TreeSet with Example Java TreeSet implements the Navigable Set interface. It stores the objects in ascending order. It contains unique elements. Access and retrieval time is fast. It does not...

8 minutes read.

Even Odd Program in Java

Even Odd Program in Java The number that are completely divisible by 2 are even and the number that leaves remainder are odd numbers. For example, the numbers 2, 0, 4,...

5 minutes read.

Client Server Program in Java

Client Server Program in Java The client and server are the two main components of socket programming. The client is a computer/node that request for the service and the server is...

7 minutes read.

Java float vs double

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

7 minutes read.

&& Operator in Java

“ && ” is the conditional - And operator in Java. In Java, it is an example of a logical operator. In Java, the “ & ” operator has two...

3 minutes read.

Java String split() method

Java String split() method split current String against given regular expression and returns a char array. Syntax: public String split(String regex)                 public String split(String regex, int...

2 minutes read.

Various operations on the Queue using Stack in Java

The Java Collections Framework's core data structures are the Stack and Queue. They are used to store and retrieve identical data in a presentation sequence. These two linear data structures...

7 minutes read.

Java ArraylistRemove() Time Complexity

In this tutorial, we will learn about how we can remove time complexity in Java ArrayList. But unless we will not learn what is ArrayList, we don’t understand this process....

7 minutes read.

Short Circuit Logical Operators in Java

When there are two or more relational expressions in a decision-making statement, logical operators are utilized to combine them. The logical operators short circuit and not-short circuit fall into two...

5 minutes read.

Composition in Java

Composition Java uses the composition method to implement a has-a connection. Composition allows us to reuse code in the same way that Java inheritance does. The "is-a" relationship is implemented using the...

3 minutes read.

Java Math tanh() Method

The tanh() method of Java Math class returns the hyperbolic tangent of the specified double value. Syntax: public static double tanh(double x) Parameters: The parameter ‘x’ represents the number whose hyperbolic tangent is to...

2 minutes read.

Java Math round() Method

The round() method of Java Math class returns a long or an int value that is closest to the argument and is rounded to positive infinity. Syntax: public static int round(float a)public...

2 minutes read.

JDK | Java Development Kit

Java Development Kit (JDK) The Java Development Kit is a software development environment used to create Java applications. The JDK includes JRE (Java Runtime Environment), an interpreter (java), a compiler (javac),...

3 minutes read.

Java String Concatenation

Java String Concatenation Java programming provide a way to combine multiple strings into a single string. It is called as String Concatenation. There are different ways to concatenate two or more...

4 minutes read.

Java String toCharArray() method

Java String toCharArray() method converts current String into character array. Syntax: public char[] toCharArray() Returns: It returns a character array Java String toCharArray() method example 1 import java.util.Arrays; public class JavaStringToCharArrayEx1 {           public static...

2 minutes read.

Structure of Java Program

Java is well-known as an object-oriented, secure, and platform-independent programming language. The Java programming language allows us to construct a wide variety of programs. Therefore, it is essential to fully...

6 minutes read.

Converting Roman to Integer Numerals in java

In this article, you will be acknowledged about the process of conversion of roman numbers to integers in java. The most important approaches are discussed and also the implementation of...

3 minutes read.

Difference Between replace() and replaceall() in Java

In this article, you will be acknowledged about the replace() and replaceall() methods in java. Also, most importantly you will be acknowledged the differences between them along with the example...

4 minutes read.

Switch Case Program in Java

Switch Case Program in Java The switch case program in Java controls which code snippet gets executed on the basis of the value of the expression mentioned in the switch statement....

22 minutes read.

For Loop Program in Java

For Loop Program in Java The for-loop program in Java is written when we want a particular set of statements to be executed repeatedly until the given criteria/ condition is met....

8 minutes read.