BIG
DATA

JAVA

STATIC KEYWORD IN JAVA

Read more about »
  • Java 9 features
  • Read about Hadoop
  • Read about Storm
  • Read about Storm
 

Quick Links within the page



'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:

  • variable(class variable)
  • method(class method)
  • block
  • nested class

Java static variable

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).

  • Static variables are initialized only once , at the start of the execution . These variables will be initialized first, before the initialization of any instance variables.
  • There would only be one copy of each class variable per class, regardless of how many objects are created from it. Static variable's value is same for all the object(or instances) of the class or in other words you can say that all instances(objects) of the same class share a single copy of static variables.
  • Visibility is similar to instance variables. However, most static variables are declared public since they must be available for users of the class.
  • A static variable can be accessed directly by the class name and doesn't need any object Syntax : [class-name].[variable-name]
  • Memory allocation for static variables happens only once when the class is loaded in the memory.Thus it makes your program memory efficient (i.e it saves memory).

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


Using the Static Keyword to Create Constants

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: static
[Note]: Constant variable name should be in Uppercase, you can use underscore(_) in between.



static variable initialization

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();
}


Java static method

Static methods are conceptually the same as static variables. It is a method which belongs to the class and not to the object(instance)

  • static method can access static data member and can change the value of it.
  • A static method can access only static data. It can not access non-static data (instance variables)
  • A static method can call only other static methods and can not call a non-static method from it.
  • A static method cannot refer to "this" or "super" keywords in anyway
  • Static Methods can access class variables without using object of the class. It can access non-static methods and non-static variables by using objects.
  • Static methods can be accessed directly in static and non-static methods.
  • A static method can be accessed directly by the class name and doesn't need any object Syntax : [class-name].[method-name]
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:

  • If you are writing utility classes and they are not supposed to be changed.
  • If a method is not using any instance variable.
  • If any operation is not dependent on instance creation.
  • If there is some code that can easily be shared by all the instance methods, extract that code into a static method.
  • If you are sure that the definition of the method will never be changed or overridden. As static methods can not be overridden.

[Note]: Restrictions

  • static methods can not use non static data member or call non-static method directly.
  • this and super cannot be used in static methods.


Java main() method

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.

Signature of main method in Java

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.



Java static block

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.

  • Static block will be executed when a class is first loaded in to the JVM.
  • Static block is used to initialize the static data member.
  • It is executed before main method at the time of classloading.
  • Static block can be used to check conditions before execution of main begins.
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.

Limitations for static blocks
  • You cannot throw Checked Exceptions.
  • You cannot use this keyword since there is no instance.
  • You shouldn't try to access super since there is no such a thing for static blocks.
  • You should not return anything from this block.
  • Static blocks make testing a nightmare.


Java static class

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.

  • Nested static class doesn't need reference of Outer class, but Non-static nested class or Inner class requires Outer class reference.
  • Inner class(or non-static nested class) can access both static and non-static members of Outer class. A static nested class cannot access non-static members of its Outer class. It can access only static members of Outer class.


Java static import

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;
Example for static import:
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");
Advantage of static import:
  • Less coding is required if you have access to any static member of a class oftenly.
  • Readability of the code may increase - Instead of writing name of static class, one can directly write the method or member variable name.
Disadvantage of static import:

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.

Difference between import and static import

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.

Overriding and Hiding Methods

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.