There are tons of reserved keywords in Java that cannot be used as names of variables or identifiers. One such frequently used keyword in Java is the “Static” keyword. The most important reason why static keywords are heavily used in Java is to efficiently manage memory. Generally, if you want to access variables or methods inside a class, you first need to create an instance or object of that class. However, there might be situations where you want to access only a couple of methods or variables of a class and you don’t want to create a new instance for that class just for accessing these members. This is where you can use the static keyword in Java.

Understanding static in Java is pivotal for grasping its role in creating class-level variables and methods. Dive into static concepts and more with a Java Course for comprehensive learning.

In Java, it is possible to use the static keyword with methods, blocks, variables, as well as nested classes. In simple words, if you use a static keyword with a variable or a method inside a class, then for every instance that you create for that class, these static members remain constant and you can’t change or modify them. In fact, you can access these members even without creating an instance of an object for those classes. You can access them simply using the class name. In fact, the main method of a class in Java usually has a static keyword associated with it. But, yes, it depends on the choice of the developer.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Static Keyword in Java

Static keyword in java in Java indicates that a particular member is not an instance, but rather part of a type. The static member will be shared among all instances of the class, so we will only create one instance of it.

If any member in a class is declared as static, it means that even before the class is initiated, all the static members can be accessed and become active. In contrast to this, non-static members of the same class will cease to exist when there is no object or the object goes out of scope. 

On a side note, if you consider the methods inside the “Math” class in Java, you will find that most of its methods are static. You can simply access them using the class name. For example, “Math.abs()”, “Math.pow()”, “Math.PI”, etc.

In this detailed and comprehensive guide on Static Keyword in Java, you will look into all 4 members along which you can use the static keyword with practical, hands-on examples on each of them. So without any further ado, let’s dive deep into the tutorial.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Static Variables in Java

When you create an object or instance for a class in Java, each object will have its own copy of the members such as variables and methods. 

For example, 

class Person{

   int age;

}

 class Main{

   public static void main(String args[]){

       Person p1 = new Person();

       Person p2 = new Person();

       p1.age = 31;

       p2.age = 32;

       System.out.println("P1\'s age is: " + p1.age);

       System.out.println("P2\'s age is: " + p2.age);

   }

}

StaticVariables

In the above example, both the person objects p1 and p2 have their own local copy of the non-static variable age. If you change them, they will store different values then.

However, if the same variable age would have been declared as a static variable, then all the objects declared for this class would share the same copy of the static variable. This is so because of static variables or for that matter, all the static members are not associated with instances, but with classes. Hence, you won’t even have to create an object to access static members. Consider the same example but with a static variable called age.

class Person{

   static int age;

}

class Main{

   public static void main(String args[]){

       Person p1 = new Person();

       Person p2 = new Person();

       p1.age = 30;

       p2.age = 31;

       Person.age = 32;

       System.out.println("P1\'s age is: " + p1.age);

       System.out.println("P2\'s age is: " + p2.age);

   }

}

StaticVariables_1

In the above example, you have declared a static variable called age inside the class called Person. There were also two objects called P1 and P2 for the same class. This example tried to assign two different values to the age static variable using these objects. And finally, it used the class name to access the static variable and changed it to another value. In the end, if you print P1’s and P2’s copies of the age variable, you will find that both the values have been changed to the final value which you specified by accessing the age variable by the class name.

Also, please note that static variables are not often used, however, in place of static variables, static constants are quite frequently used in Java. These are defined by static final and commonly declared in uppercase.

Mostly static variables are used to grab the common properties that are shared by the class objects such as the name of the department for a college class, etc. These variables are allocated memory only once when the class is loaded.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Let’s see another interesting example of the static variable in Java. Here, you will define a counter variable first as a non-static member and then as a static member.

class Test{

   int counter;

   Test(){

       counter++;

       System.out.println("Current Value of the Counter is: " + counter);

   }

}

 class Main{

   public static void main(String args[]){

       Test t1 = new Test();

       Test t2 = new Test();

       Test t3 = new Test();

   }

}

StaticVariables_2

As you can see, each of the Test class objects has its copy of the non-static counter variable and the same value has been assigned when they are initialized. Let’s try to define this variable as static.

class Test{

   static int counter;

   Test(){

       counter++;

       System.out.println("Current Value of the Counter is: " + counter);

   }

}

 class Main{

   public static void main(String args[]){

       Test t1 = new Test();

       Test t2 = new Test();

       Test t3 = new Test();

   }

}

StaticVariables_3

This time, the static counter variable is being shared by all the objects of the test class. Hence, whenever a new object is created, the constructor will increment the current global value of the counter value and print the updated value.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Static Methods in Java

It is common to often refer to static methods in Java as class methods. The reason being that the static members are associated with the classes and with their objects. Similar to static variables, static methods can also be invoked using the class name. There are some important points that you need to consider when you work with static methods in Java. These are - 

  1. The static methods of a particular class can only access the static variables and can change them.
  2. A static method can only call other static methods.
  3. Static methods can’t refer to non-static variables or methods.
  4. Static methods can’t refer to “super” or “this” members.

Also, often you will notice that the main method in Java is defined as static. This is so because you don’t need an object to call the main method in Java. If you have defined the main method in Java as non-static, then the Java Virtual Machine (JVM) would have first created an instance for the main class and then called the main method using that instance which would lead to unnecessary memory usage. Moreover, there are tons of static methods defined in the Wrapper Classes and Utility Classes in Java.

Next, consider the below example.

class Test{

   int counter;

   public static void increment(){

       counter++;

       System.out.println("Current value of Counter is: " + counter);

   }

}

 class Main{

   public static void main(String args[]){

       Test.increment();

   }

}

StaticMethods_1

The above program will generate an error. This is so because it has tried to access a non-static variable called counter inside a static method called increment().

Let’s try to use the same example but this time, you will specify the counter variable as a static variable.

class Test{

   static int counter;

   public static void increment(){

       counter++;

       System.out.println("Current value of Counter is: " + counter);

   }

}

 class Main{

   public static void main(String args[]){

       Test.increment();

       Test.increment();

       Test.increment();

   }

}

StaticMethods_2

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Static vs Non-Static

Before moving ahead with this Static in Java tutorial to discuss static blocks and classes in Java, let’s discuss a few differences between static and non-static variables and methods in Java.

Static Variables

Non-Static Variables

They can access them using class names.

They can be accessed only using objects.

They can access them with static methods as well as non-static methods.

They can be accessed only using non-static methods.

They are allocated memory only once while loading the class. 

A memory per object is allocated.

These variables are shared by all the objects or instances of the class.

Each object has its own copy of the non-static variables.

Static variables have global scope.

They have local scope.

Static Methods

Non-Static Methodsnon-Static Methods

These methods support early or compile-time binding.

They support late, run-time, or dynamic binding.

These methods can only access static variables of other classes as well as their own class.

They can access both static as well as non-static members.

You can’t override static methods.

They can be overridden.

Less memory consumption since they are allocated memory only once when the class is being loaded.

Memories are allocated for each object.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Static Blocks in Java

Generally, static blocks in Java are used to initialize static variables. They are executed only once when the class is loaded and hence, are perfect for this job. Also, you can include more than one static block in the class. Static blocks can only access static variables. Let’s understand static blocks using the below example.

class Test{

   static int i = 10;

   static int j;

   static{

       System.out.println("Initializing the Static Variable using Static Block ...");

       j = i * 5;

   }

}

 class Main{

   public static void main(String args[]){

       System.out.println("Value of i is: " + Test.i);

       System.out.println("Value of j is: " + Test.j);

   }

}

StaticBlocks_1

Here, you saw the creation of two static variables called i and j inside the Test class. It went on to initialize variable j using a static block. In the main method, you must use the class name to print the values of i and j static variables. You can see that the static block gets executed before the execution of the main method. When the static block is executed, it prints the first line regarding the initialization and then initializes the variable j. Then, the main method gets executed which prints the values of both the variables.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Static Nested Classes in Java

In Java, you can use static keywords for nested classes as well. However, it isn’t possible to use the static keyword for outer classes or top-level classes. Please note that when you use nested classes, they don’t need any sort of reference for outer classes in Java. Also, a nested static class cannot access the members of the outer class that are non-static. Let’s consider the below example for better understanding.

class Test{

   static int i = 10;

   static class NestedTest{

       public void printer(){

           System.out.println("The value of i is: " + i);

       }

   }

}

 class Main{

   public static void main(String args[]){

       Test.NestedTest t = new Test.NestedTest();

       t.printer();

   }

}

StaticNested

Here, you saw the creation of a simple static nested class and tried to access a static member of the top-level class. 

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Final Example

Let’s consider a final example that uses all the types of static members that were discussed above.

class Test{

   //Static variable

   static int i;

   static int j;

   //Multiple Static Blocks

   static{

       System.out.println("Initializing the value of i");

       i = 20;

   }

   static{

       System.out.println("Initializing the value of j");

       j = i * 30;

   }

   //Static Method

   public static void display(){

       System.out.println("The value of i is: " + i);

       System.out.println("The value of j is: " + j);

   }

   //Static Nested Class

   static class NestedTest{

       public void changer(){

           i = i + 10;

           j = j + 10;

           System.out.println("The updated value of i is: " + i);

           System.out.println("The updated value of j is: " + j);

       }

   }

}

 class Main{

   public static void main(String args[]){

       Test.display();

       Test.NestedTest t = new Test.NestedTest();

       t.changer();

   }

}

FinalExample

Here, you saw the creation of two static variables called i and j inside a test class. You have then used two static blocks to initialize these variables. After that, you must use a static method to display the values of these variables. Post that, you have used a nested static class and defined a method inside it that updates the values of these static variables and displays them. Before loading the main method, the static block gets executed and prints the message for initialization. After that, the values of i and j are printed when you use the class name to invoke the static display method. Lastly, you saw the creation of an object for the nested static class and invoked the changer method on it to modify the variables and print the updated values.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Wrapping Up!

To conclude, in this comprehensive guide, you have walked through a basic introduction to static keywords and members in Java. This tutorial then explained static variables, methods, blocks, and nested classes in Java with practical examples for each of them. You also explored the differences between static and non-static variables and methods in Java. Lastly, you saw a final example that includes all the static members. 

We certainly hope that this guide will help you to get hands-on with the static keyword in Java and get started with the advanced concepts in Java. You can check out the Complete Java Programming Guide as well or enroll in our Full Stack Java Developer Job Guarantee Program. Have any questions for us? Leave them in the comments section of this page, and our experts will get back to you on the same, ASAP!

Happy Learning

Our Software Development Courses Duration And Fees

Software Development Course typically range from a few weeks to several months, with fees varying based on program and institution.

Program NameDurationFees
Caltech Coding Bootcamp

Cohort Starts: 17 Jun, 2024

6 Months$ 8,000
Full Stack Developer - MERN Stack

Cohort Starts: 30 Apr, 2024

6 Months$ 1,449
Automation Test Engineer

Cohort Starts: 1 May, 2024

11 Months$ 1,499
Full Stack Java Developer

Cohort Starts: 14 May, 2024

6 Months$ 1,449