☰
'static' is a Java keyword. It can be applied to a field, a method or an inner class. A static field, method or class has a single instance for the whole class that defines it, even if there is no instance or n number of instances of this class in the program.
In Java, static is used mainly for memory management. The static keyword belongs to the class than its instances.
The static keyword denotes that a member variable, or method, can be accessed without requiring an instantiation of the class to which it belongs.In simple terms, it means that you can call a method, even if you've never created the object to which it belongs.
The static can be:
If you declare a variable as static then it becomes static variable. Static variables are also called as Class variables as it belongs to the class rather than objects(instances).
class Employee{
int empID;
String name;
String company="Oopguru";
}
Suppose there are 100 employees in Oopguru, each time when object is created all instance data members will get memory.Here company referring to 'Oopguru' is same for all objects.So lets make it static and make it get memory allocated only once.
class Employee{
int empID;
String name;
static String company="Oopguru";
Employee(int id, String empName){
empID = id;
name = empName;
}
void getInfo(){
System.out.println("Name: " + name + ", EmpID: " + empID + ", Company: " + company);
}
}
class Demo{
public static void main(String args[]){
Employee emp1 = new Employee(001, "Vivek");
Employee emp2 = new Employee(002, "Kavya");
emp1.getInfo();
emp2.getInfo();
}
}
Output:
Name: Vivek, EmpID:001, Company:Oopguru
Name: Kavya, EmpID:002, Company:Oopguru
Lets have one more classic example of counter to understand static better.
class Counter {
int count = 0; //instance variable, it gets memory allocated when instance is created
Counter() {
count++;
System.out.println(count);
}
}
class Demo {
public static void main(String args[]) {
Counter c1=new Counter();
Counter c2=new Counter();
}
}
Output:
1
1
Now lets have same program with static variable.
class Counter {
static int count = 0; //static variable, it gets memory allocated only once
Counter() {
count++;
System.out.println(count);
}
}
class Demo {
public static void main(String args[]) {
Counter c1=new Counter();
Counter c2=new Counter();
Counter c3=new Counter();
}
}
Output:
1
2
3
Static is used to create a constant value thats attached to a class.What is a constant? a value which does not change overtime.So how to make a constant in Java? By using keyword final along with static.
class Oopguru {
public final static String NAME = "Vivek";
public static final double PI = 3.141592653589793d;
}
class Demo {
public static void main(String args[]) {
System.out.println(Oopguru.NAME);
System.out.println(Oopguru.PI);
}
}
Output:
Vivek
3.141592653589793
If you try to change the value of constant then the compiler will warn you like this:

[Note]: Constant variable name should be in Uppercase, you can use underscore(_) in between.
How to initialize a private static member of a class in java?
The preferred ways to initialize static members are either:
private static final A a = new A();
or for more complex initialization code you could use a static initializer block:
private static final A a;
static {
a = new A();
}
Static methods are conceptually the same as static variables. It is a method which belongs to the class and not to the object(instance)
class Oopguru {
static void display(){
System.out.println("Company:Oopguru");
System.out.println("Author:Vivek");
}
void getInfo(){
System.out.println("getInfo");
System.out.println("Company:Oopguru");
System.out.println("Author:Vivek");
}
}
class Demo {
public static void main(String args[]){
Oopguru.display();
//Oopguru.getInfo();
System.out.println("-----------------");
Oopguru guru = new Oopguru();
guru.getInfo();
}
}
Output:
Company:Oopguru
Author:Vivek
-----------------
getInfo
Company:Oopguru
Author:Vivek
As you can see display method can be accessed without instantiating Oopguru class where as to call non-static getinfo method, you need to create object of Oopguru class and call method.
In above code, we saw both methods can get same result. Then why use static methods? When to use static methods?
A simple answer is 'whenever it makes sense". If a method needs to be in a class, but not associated to an object or does it make sense to call this method, even if no Object has been constructed yet?, if so then it makes sense to make it a static. If the method is more logically part of an object, then it shouldn't be a static.
you could define static methods in the below scenarios:
[Note]: Restrictions
Main method in Java is the first method a Java programmer writes when he starts learning Java programming language. Applications always must have one class that contains a main method. Main method is entry point for any Core Java program. Execution starts from main method.
Have you ever considered why main method in Java is public, static and void. Lets understand the java main method.
If we skip writing main method, there will be no compilation error from compiler, but at runtime JVM is responsible to check for main method and if not found it throws runtime exception saying NoSuchMethodError:main.
Main method in Java can be overloaded but JVM will only call main method with specified signature specified below.
Main method has strict syntax; if not followed JVM will not be able to locate it and your program will not run. Below is the exact signature of main method.
public static void main(String args[])
Example:
public class Demo {
public static void main(String args[]){
System.out.println("Hi I am main method");
}
}
Output:
Hi I am main method
Why main method is public
As you know any method which is declared public in Java can be accessed from outside of that class as well as outside its package. Thus main method is public so that JVM can easily access and execute it.
main method is called by JVM to run the method which is outside the scope of project therefore the access specifier has to be public to permit call from anywhere outside the application
Why main method is static
By now you know about static methods. They can be called without creating any instance of class containing that method.Thus main method is static so that JVM interpreter can call the program's main method without creating an instance of class which contains main method.
If main method were not declared static than JVM interpreter has to create instance of main Class and since constructor can be overloaded and can have arguments there would be ambiguity: which constructor should be called? That's why main is static.
Why main method is void
main method is not supposed to return any value because any value returned is of no use for JVM who actually invokes this method. It simply doesn't need any reaturning value.. Hence main method is made void.
Why method name is main
Because this is the name configured inside JVM. But why 'main'? because it had to be something, and main() is what they did in the old days of C and I assume most java developers were from C and C++ language and they were already comfortable with this name. Thus 'main'.
What is String args[]
these are command line arguements.
A static block also called static initialization block is a normal block of code enclosed in braces, { }, and preceded by the static keyword. Here is an example:
static {
// whatever code is needed for initialization goes here
}
A class can have any number of static initialization blocks, and they can appear anywhere in the class body. The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code.
public class Demo {
static {
System.out.println("This block is executed first!");
}
public static void main(String args[]) {
System.out.println("Hi I am main method");
}
}
Output:
This block is executed first!
Hi I am main method
There is an alternative to static blocks, you can write a private static method:
class Demo {
public static int myVar = initializeClassVariable();
private static int initializeClassVariable() {
// initialization code goes here
}
}
The advantage of private static methods is that they can be reused later if you need to reinitialize the class variable.
[Note]: Static initializer block is executed even before JVM calls main method. They are executed when a Class is loaded into Memory by JVM.
Can a class be static in Java ? The answer is YES, we can have static class in java.In java, we can't make Top level class static. Only nested classes can be static.
[Note]:Java allows us to define a class within another class. Such a class is called a nested class. The class which enclosed nested class is known as Outer class or top-level class.
To understand the static nested class, we will learn the differences between static and non-static nested classes.
class OuterClass{
private static String msg1 = "message no 1";
private String msg2 = "message no 2";
public static class NestedStaticClass{
// Only static members of Outer class is directly accessible
public void print() {
System.out.println("Nested static class: " + msg1);
//non-static variable cannot be accessed here
//System.out.println("Nested static class: " + msg2);
}
}
public class InnerClass{
// Both static and non-static members of Outer class are accessible
public void display(){
System.out.println("Non-static nested class: "+ msg1);
System.out.println("Non-static nested class: "+ msg2);
}
}
}
class StaticClassDemo {
public static void main(String[] args) {
OuterClass.NestedStaticClass nestedClass = new OuterClass.NestedStaticClass();
nestedClass.print();
// We need an Outer class instance to create instance of Inner class
OuterClass outer = new OuterClass();
OuterClass.InnerClass inner = outer.new InnerClass();
inner.display();
}
}
Output:
Nested static class: message no 1
Non-static nested class: message no 1
Non-static nested class: message no 2
In the above code, we have declared a class named OuterClass which is an outer class (top level class). Also, we have declared two more nested classes enclosed in the outer class, one of which is static and the other one is non-static. We can see that the method in the nested static class can be accessed without creating an object of the OuterClass, whereas the method in the inner class needs instantiation of the OuterClass in order to get accessed.
Following are major differences between static nested class and non-static nested class which is also called as Inner Class.
Static import in Java allows to import static members of class e.g. static fields and static methods. Static import is introduced in Java 5.
Lets understand what import does to our program before getting into static import.
Any class from the same package can be called without importing it. But, if the class is not part of the same package, we need to provide the import statement to access the class. Consider the java import statement:
import package.ClassCar;
Above java statement allows you to use ClassCar inside your program without the package reference. That is you can use like:
ClassCar obj = new ClassCar();
And then if you have many classes in that package and you want to use all of them, then you can import all classes belonging to that package by like this:
import package.*;
Similarly we can access any static fields or methods with reference to the class name.
ClassCar.getStaticMethod();
But here comes the use of static imports. Static imports allow us to import all static fields and methods into a class and you can access them without the class name reference.
Like instead of ClassCar.getStaticMethod(); directly you can use getStaticMethod(); without class name reference.
Syntax for static imports:
// access all static members of a class
import static package-name.class-name.*;
// access specific static variable of a class
import static package-name.class-name.static-variable;
// access specific static method of a class
import static package-name.class-name.static-method;
double c = 2 * Math.PI * r;
System.out.println("Hi I am a printer");
Once the static members have been imported, they may be used without qualification.
import static java.lang.Math.PI;
import static java.lang.System.*;
...
double c = 2 * PI * r;
out.println("Hi I am a printer");
If you overuse the static import feature, it makes the program unreadable and unmaintainable because over a 1000 lines of code you may not understand which static method or static attribute belongs to which class inside the java program.
Static import has another drawback in terms of conflicts, once you static import Integer.MAX_VALUE you can not use MAX_VALUE as variable in your programmer, compiler will throw error. Similarly if you static import both Integer.MAX_VALUE and Long.MAX_VALUE and refer them in code as MAX_VALUE, you will get following compile time error : java.lang.ExceptionInInitializerError
Static import doesn't improve readability as expected, as many Java programmer prefer Integer.MAX_VALUE which is clear that which MAX_VALUE are you referring.
The import allows to access classes of a package without that package reference whereas the static import allows to access the static members of a class without that class reference. The normal import provides accessibility to classes and interface whereas static import provides accessibility to static members of the class.
[Note]: Static variables are not serialized. Meanining, if you store any data in static field then after de-serialization, new object will have its default value e.g. if static field was int then it will contain zero and if object then it will contain null. So make sure not to store key state data of an object in static field.
When an instance method is written in a child class with the same signature and return type as an instance method in the parent class, it overrides the parent class's method. This is called as method Overriding.
class Car {
public void nonStaticMethod() {
System.out.println("Car: non-Static method");
}
}
class BMW extends Car {
public void nonStaticMethod() {
System.out.println("BMW: non-Static method");
}
}
public class Demo {
public static void main(String[] args) {
Car carObject = new BMW();
carObject.nonStaticMethod();
}
}
Output:
BMW: non-Static method
Here eventhough, carObject's method is being called in source code, in runtime BMW's method is called. This is called as run-time polymorphism achieved by method overriding.
Now, if a child class defines a static method(class method) with the same signature as a static method in the parent class, the method in the child class hides the one in the parent class. This is called as method Hiding.
class Car {
public static void staticMethod() {
System.out.println("Car: Static method");
}
public void nonStaticMethod() {
System.out.println("Car: non-Static method");
}
}
class BMW extends Car {
public static void staticMethod() {
System.out.println("BMW: Overridden Static method");
}
public void nonStaticMethod() {
System.out.println("BMW: non-Static method");
}
}
public class Demo {
public static void main(String args[]){
Car carObject = new BMW();
// eclipse will give a warning for the below line
// saying it should be accessed in a static way
// but it will compile and execute
carObject.staticMethod();
carObject.nonStaticMethod();
}
}
The main method in the above class creates an instance of Car, and references it to BMW object. and then calls both the static and the non-static methods on the instance.Below is the Output:
Car: Static method
BMW: non-Static method
For static or class methods, the runtime system invokes the method defined in the compile-time type of the reference on which the method is called. In the above example, the compile-time type of carObject is Car. Thus, the runtime system invokes the staticMethod defined in Car. For instance or non-static methods, the runtime system invokes the method defined in the runtime type of the reference on which the method is called. In the above example, the runtime type of carObject is BMW. Thus, the runtime system invokes the override method defined in BMW.
[Note]: An non-static method cannot override a static method, and a static method cannot hide an non-static method.Follow the below table to define a Method with the same signature as a parent class's method.
| Non-static Method [Parent class] |
Static Method [Parent class] |
|
|---|---|---|
| Non-static Method [Child class] |
Overrides | compile-time error |
| Static Method [Child class] |
compile-time error | Hides |
That is all about static, next we will dig into classes. Till then keep coding.