This Tutorial Explains Static Keyword in Java and its Usage in Variables, Methods, Blocks & Classes. Also States the Difference Between Static & Non-static Members:
Java supports various types of declarations to indicate the scope and behavior of its variables, methods, classes, etc. For Example, the keyword final, sealed, static, etc. All these declarations have some specific meaning when they are used in the Java program.
We will explore all these keywords as we proceed with this tutorial. Here, we will discuss the details of one of the most important keywords in Java i.e. “static”.
Table of Contents:
Static Keyword In Java
A member in a Java program can be declared as static using the keyword “static” preceding its declaration/definition. When a member is declared static, then it essentially means that the member is shared by all the instances of a class without making copies of per instance.
Thus static is a non-class modifier used in Java and can be applied to the following members:
- Variables
- Methods
- Blocks
- Classes (more specifically, nested classes)
When a member is declared static, then it can be accessed without using an object. This means that before a class is instantiated, the static member is active and accessible. Unlike other non-static class members that cease to exist when the object of the class goes out of scope, the static member is still obviously active.
Static Variable in Java
A member variable of a class that is declared as static is called the Static Variable. It is also called as the “Class variable”. Once the variable is declared as static, memory is allocated only once and not every time when a class is instantiated. Hence you can access the static variable without a reference to an object.
The following Java program depicts the usage of Static variables:
class Main { // static variables a and b static int a = 10; static int b; static void printStatic() { a = a /2; b = a; System.out.println("printStatic::Value of a : "+a + " Value of b : "+b); } public static void main(String[] args) { printStatic(); b = a*5; a++; System.out.println("main::Value of a : "+a + " Value of b : "+b); } }
Output:
In the above program, we have two static variables i.e. a and b. We modify these variables in a function “printStatic” as well as in “main”. Note that the values of these static variables are preserved across the functions even when the scope of the function ends. The output shows the values of variables in two functions.
Why Do We Need Static Variables And Where Are They Useful?
Static variables are most useful in applications that need counters. As you know, counters will give wrong values if declared as normal variables.
For instance, if you have a normal variable set as a counter in an application that has a class say car. Then, whenever we create a car object, the normal counter variable will be initialized with every instance. But if we have a counter variable as a static or class variable then it will initialize only once when the class is created.
Later, with every instance of the class, this counter will be incremented by one. This is unlike the normal variable wherein with each instance the counter will be incremented but the value of the counter will always be 1.
Hence even if you create a hundred objects of the class car, then the counter as a normal variable will always have the value as 1 whereas, with a static variable, it will show the correct count of 100.
Given below is another example of Static counters in Java:
class Counter { static int count=0;//will get memory only once and retain its value Counter() { count++;//incrementing the value of static variable System.out.println(count); } } class Main { public static void main(String args[]) { System.out.println("Values of static counter:"); Counter c1=new Counter(); Counter c2=new Counter(); Counter c3=new Counter(); } }
Output:
The working of the static variable is evident in the above program. We have declared the static variable count with initial value = 0. Then in the constructor of the class, we increment the static variable.
In the main function, we create three objects of the class counter. The output shows the value of the static variable each time when the counter object is created. We see that with every object created the existing static variable value is incremented and not reinitialized.
Java Static Method
A method in Java is static when it is preceded by the keyword “static”.
Some points that you need to remember about the static method include:
- A static method belongs to the class as against other non-static methods that are invoked using the instance of a class.
- To invoke a static method, you don’t need a class object.
- The static data members of the class are accessible to the static method. The static method can even change the values of the static data member.
- A static method cannot have a reference to ‘this’ or ‘super’ members. Even if a static method tries to refer them, it will be a compiler error.
- Just like static data, the static method can also call other static methods.
- A static method cannot refer to non-static data members or variables and cannot call non-static methods too.
The following program shows the implementation of the static method in Java:
class Main { // static method static void static_method() { System.out.println("Static method in Java...called without any object"); } public static void main(String[] args) { static_method(); } }
Output:
This is a simple illustration. We define a static method that simply prints a message. Then in the main function, the static method is called without any object or instance of a class.
Another Example of Static keyword Implementation in Java.
class Main { // static variable static int count_static = 5; // instance variable int b = 10; // static method static void printStatic() { count_static = 20; System.out.println("static method printStatic"); // b = 20; // compilation error "error: non-static variable b cannot be referenced from a static context" //inst_print(); // compilation error "non-static method inst_print() cannot be referenced from a static //context" //System.out.println(super.count_static); // compiler error "non-static variable super cannot be //referenced from a static context" } // instance method void inst_print() { System.out.println("instance method inst_print"); } public static void main(String[] args) { printStatic(); } }
In the above program, as you can see we have two methods. The method printStaticis a static method while inst_print is an instance method. We also have two variables, static_count is a static variable and b is an instance variable.
In the static method – printStatic, first, we display a message and then we try to change the value of the instance variable b and also call the non-static method.
Next, we try to use the ‘super’ keyword.
b = 20;
inst_print();
System.out.println(super.count_static);
When we execute the program with the above lines, we get compilation errors for using instance variables, calling non-static methods and referring super in a static context. These are the limitations of the static method.
When we comment on the above three lines, only then the above program works fine and produces the following output.
Output:
Overloading And Overriding Of Static Method
As you all know, both Overloading and Overriding are the features of OOPS and they aid in polymorphism. Overloading can be classified as compile-time polymorphism wherein you can have methods with the same name but different parameter lists.
Overriding is a feature of run time polymorphism and in this, the base class method is overridden in the derived class so that the method signature or prototype is the same but the definition differs.
Let us discuss how Overloading and Overriding affect the static class in Java.
Overloading
You can overload a static method in Java with different parameter lists but with the same name.
The following program shows Overloading:
public class Main { public static void static_method() { System.out.println("static_method called "); } public static void static_method(String msg) { System.out.println("static_method(string) called with " + msg); } public static void main(String args[]) { static_method(); static_method("Hello, World!!"); } }
Output:
This program has two static methods with the same name ‘static_method’ but a different argument list. The first method does not take any argument and the second method takes a string argument.
One point to note is that you cannot overload the method merely depending on the ‘static’ keyword. For Example, if you have an instance method ‘sum’ and if you define another method “sum” and declare it as static, then it is not going to work. This attempt to overload based on a “static” keyword is going to result in a compilation failure.
Overriding
As static methods are invoked without any object of the class, even if you have a static method with the same signature in the derived class, it will not be overriding. This is because there is no run-time polymorphism without an instance.
Hence you cannot override a static method. But if at all there is a static method with the same signature in the derived class, then the method to call doesn’t depend on the objects at run time but it depends on the compiler.
You have to note that though static methods cannot be overridden, the Java language does not give any compiler errors when you have a method in the derived class with the same signature as a base class method.
The following implementation proves this point.
classBase_Class { // Static method in base class which will be hidden in substatic_displayclass public static void static_display() { System.out.println("Base_Class::static_display"); } } classDerived_Class extends Base_Class { public static void static_display() { System.out.println("Derived_Class::static_display"); } } public class Main { public static void main(String args[ ]) { Base_Class obj1 = new Base_Class(); Base_Class obj2 = new Derived_Class(); Derived_Class obj3 = new Derived_Class(); obj1.static_display(); obj2.static_display(); obj3.static_display(); } }
Output:
In the above program, you can see that the static method that is called does not depend on which object the pointer points to. This is because objects are not at all used with static methods.
Static Block In Java
Just as you have function blocks in programming languages like C++, C#, etc. in Java also, there is a special block called “static” block that usually includes a block of code related to static data.
This static block is executed at the moment when the first object of the class is created (precisely at the time of classloading) or when the static member inside the block is used.
The following program shows the usage of a static block.
class Main { static int sum = 0; static int val1 = 5; static int val2; // static block static { sum = val1 + val2; System.out.println("In static block, val1: " + val1 + " val2: "+ val2 + " sum:" + sum); val2 = val1 * 3; sum = val1 + val2; } public static void main(String[] args) { System.out.println("In main function, val1: " + val1 + " val2: "+ val2 + " sum:" + sum); } }
Output:
Note the order of execution of statements in the above program. The contents of the static block are executed first followed by the main program. The static variables sum and val1 have initial values while val2 is not initialized (it defaults to 0). Then in the static block val2 is still not assigned a value and hence its value is displayed as 0.
The variable val2 is assigned value after printing in the static block and the sum is recalculated. Therefore, in the main function, we get different values of sum and val2.
If you specify a constructor, then the contents of the static block are executed even before the constructor. The static blocks are mostly used to initialize static members of the class and other initialization related to static members.
Java Static Class
In Java, you have static blocks, static methods, and even static variables. Hence it’s obvious that you can also have static classes. In Java, it is possible to have a class inside another class and this is called a Nested class. The class that encloses the nested class is called the Outer class.
In Java, although you can declare a nested class as Static it is not possible to have the outer class as Static.
Let’s now explore the static nested classes in Java.
Static Nested Class In Java
As already mentioned, you can have a nested class in Java declared as static. The static nested class differs from the non-static nested class(inner class) in certain aspects as listed below.
Unlike the non-static nested class, the nested static class doesn’t need an outer class reference.
A static nested class can access only static members of the outer class as against the non-static classes that can access static as well as non-static members of the outer class.
An example of a static nested class is given below.
class Main{ private static String str = "SoftwareTestingHelp"; //Static nested class static class NestedClass{ //non-static method public void display() { System.out.println("Static string in OuterClass: " + str); } } public static void main(String args[]) { Main.NestedClassobj = new Main.NestedClass(); obj.display(); } }
Output:
In the above program, you see that the static nested class can access the static variable (string) from the outer class.
Static Import In Java
As you know, we usually include various packages and predefined functionality in the Java program by using the “import” directive. Using the word static with the import directive allows you to use the class functionality without using the class name.
Example:
import static java.lang.System.*; class Main { public static void main(String[] args) { //here we import System class using static, hence we can directly use functionality out.println("demonstrating static import"); } }
Output:
In this program, we use static import for java.lang.System class.
Note: In the main function, we have just used out.println to display the message.
Although the static import feature makes code more concise and readable, it sometimes creates ambiguity especially when some packages have the same functions. Hence static import should be used only when extremely needed.
Static vs Non-Static
Let us discuss the major differences between Static and Non-Static members of Java.
Enlisted below are the differences between Static and Non-Static variables.
Static Variables | Non-static Variables |
---|---|
It can be accessed using class name only. | Requires objects of a class to access. |
Are accessible to both static as well as non-static methods. | Are accessible to non-static methods only. |
A memory for static variable is allocated only once per class. | A memory for non-static variables is allocated per object. |
Shared by all the objects of the class. | A copy of variable per object is made. |
Has global scope and is available to all the methods and blocks. | Has local scope and is visible to objects of the class. |
Given below is the difference between Static and Non-Static methods.
Static Methods | Non-static Methods |
---|---|
A method that is preceded by a static keyword and is available at the class level. | A method not preceded by static keyword and available for each of the instances of the class. |
Supports compile-time or early binding. | Supports run-time or dynamic binding. |
Can access only static data members of its class and any other class. | Can access static as well as non-static members of the class and other classes. |
Static methods cannot be overridden. | Can be overridden. |
Memory is allocated only once. Hence memory used is less. | Memory consumption is more since memory is allocated every time the method is invoked. |
Static vs Final
Static and Final are two keywords in Java that can give special meaning to the entity that it is used with. For Example, when a variable is declared as static, it becomes a class variable that can be accessed without a reference to the object.
Similarly, when a variable is declared as final, it becomes immutable i.e. a constant.
Let’s tabularize some of the major differences between Static and Final keywords in Java.
Static | Final |
---|---|
A static data member (nested class, variable or method) is a data member preceded by static keyword and can be accessed without an object. | The final keyword can be applied to a variable, method, class,etc. and imposes restrictions on the entities. |
Not mandatory to initialize the static variable with value during declaration. | It is required that the final variable be initialized to a value at the time of declaration |
You can reinitialize the static variables. | Not possible to reinitialize final variables. |
Static methods are those that can only access static members. | Final methods are the methods that cannot be inherited/overridden. |
Static classes are classes whose objects cannot be created. | Final classes are classes that cannot be inherited. |
Frequently Asked Questions
Q #1) Can Java Class be Static?
Answer: Yes, a class in Java can be static, provided it is not the outer class. This means that only nested classes in Java can be static.
Q #2) When should I use Static in Java?
Answer: Whenever you want a data member in your program that should keep its value across the objects, then you should use static. For Example, a counter. A method can be declared as static when you do not want to invoke it using an object.
Q #3) Can a Static Class have a Constructor?
Answer: Yes, a static class can have a constructor and its purpose is solely to initialize static data members. It will be invoked only for the first time when the data members are accessed. It will not be invoked for subsequent access.
Q #4) What is the use of Static Constructor?
Answer: In general, the constructor is used to initialize static data members. It is also used to perform operations/actions that need to be carried out only once.
Q #5) Are static methods inherited in Java?
Answer: Yes, static methods in Java are inherited but are not overridden.
Conclusion
In this tutorial, we discussed the static keyword of Java in detail along with its usage in data members, methods, blocks and classes. The static keyword is a keyword that is used to indicate the class level or global scope.
You don’t need to access static members using instances of the class. You can directly access the static data members using the class name. We also discussed the major differences between static and non-static members as well as static and final keywords.
In our subsequent topics, we will explore more keywords and their significance in Java language.