Java: static Keyword


In Java, static keyword is used for memory management mainly. Static elements below to the class. It can apply with:

  • Static Variable (also known as a class variable)
  • Static Method (also known as a class method)
  • Static Block
  • Static Nested class
  • Static Import

Note: These static variables and method access by class name it doesn’t require any class instance.

Java Static Variable

A variable declares as static is known as static variable or class variable. This variable value would be common among all the instances of class because these variables take memory in the class area only once when the class first loaded.
Advantage: The static variable makes program memory efficient because of saves memory.

static variable.png

static Variable Example

public class Employee {

	int id;
	String name;
	static String organization = "Facing Issues On IT";

	public Employee(int id, String name) {
		this.id = id;
		this.name = name;
	}

	public String display() {
		return "Id:" + id + " Name:" + name + " Organization:" + organization;
	}
}
public class StaticVariableTest {

	public static void main(String[] args) {
		Employee e1=new Employee(1,"Saurabh Gupta");
		Employee e2=new Employee(2,"Gaurav Kumar");

		System.out.println(e1.display());
        System.out.println(e2.display());
        //Change Static value
        Employee.organization="Learn from Others Experience";//Print before change
        System.out.println(e1.display());
        System.out.println(e2.display());
	}

}

Output


Id:1 Name:Saurabh Gupta Organization:Facing Issues On IT
Id:2 Name:Gaurav Kumar Organization:Facing Issues On IT
Id:1 Name:Saurabh Gupta Organization:Learn from Others Experience
Id:2 Name:Gaurav Kumar Organization:Learn from Others Experience

Counter Example with instance and static Variable

public class Counter {
	// instance variable count get memory each time when instance get created
	int count = 0;
	// class variable count will get memory once once when class loaded
	static int staticCount;

	public Counter() {
	//increase the value of each count
     count++;
     staticCount++;
     System.out.println("Count :"+count +" Static Count :"+staticCount);
	}
}
public class CounterExample {

	public static void main(String[] args) {
		new Counter();
		new Counter();
		new Counter();
	}

}

Output


Count :1 Static Count :1
Count :1 Static Count :2
Count :1 Static Count :3

Java Static Method

a static keyword with any method is known as a static method or class method.

  • A static method belongs to the class rather than the instance of a class.
  • A static method can be invoked by class names without the need for creating an instance of a class.
  • A static method can access static data variables only change the value of it.

Restrictions for the static method

There are mainly two restrictions for the static method:

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

Why Java main() method is static?

The static method doesn’t require an object to call because it’s called my Class Name. If the main() method were a non-static method, JVM creates an object first then call a main() method that would be the problem of extra memory allocation.

Java Static Method Example

public class Employee {

	int id;
	String name;
	static String organization = "Facing Issues On IT";

	public Employee(int id, String name) {
		this.id = id;
		this.name = name;
	}

	public String display() {
		return "Id:" + id + " Name:" + name + " Organization:" + organization;
	}
	//static method static member only
	public static void change(String org)
	{
		organization=org;
		//these non static member will throw compile time issues.
		//id=5;
		//name="Rajesh";
	}
}

public class StaticMethodTest {

	public static void main(String[] args) {
		Employee e1=new Employee(1,"Saurabh Gupta");
		Employee e2=new Employee(2,"Gaurav Kumar");

		System.out.println(e1.display());
        System.out.println(e2.display());
        //Change Static value by calling static method
        Employee.change("Learn from Others Experience");
        System.out.println(e1.display());
        System.out.println(e2.display());
	}

}

Output


Id:1 Name:Saurabh Gupta Organization:Facing Issues On IT
Id:2 Name:Gaurav Kumar Organization:Facing Issues On IT
Id:1 Name:Saurabh Gupta Organization:Learn from Others Experience
Id:2 Name:Gaurav Kumar Organization:Learn from Others Experience

Java Static Block

  • A static block is executed before the main method at the time of classloading.
  • A static block is used to initialize the static data variables and members.
public class StaticBlockExample {

	static {
		System.out.println("Static block is executed");
	}

	public static void main(String args[]) {
		System.out.println("Main method executed");
	}

}

Output


Static block is executed
Main method executed

Can we execute a program without main() method?

It was possible till JDK 1.6. by executing the static block. Since JDK 1.7, it is not possible to execute a java class without the main method.

class Test{
  static{
  System.out.println("Static block is executed");
  System.exit(0);
  }
}

JDK 1.6


Static block is executed

JDK 1.7


Error: Main method not found in class Test, please define the main method as:
   public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application

Java Static Import

The static import feature introduced in Java 5 to access any static member of a class directly. There is no need to qualify class name.

Static Import Advantage

Less coding is required: if need to use some static member frequently.

Static import Disadvantage

If you overuse the static import statement, then it creates problem to understand and maintain code.

Example of Static Import

import static java.lang.System.*;

public class StaticImportExample {
	public static void main(String args[]) {
		// Now no need of write System.out
		out.println("Facing Issues on IT");
		out.println("Learn from Other Experinces");

	}
}

Output


Facing Issues on IT
Learn from Other Experinces

What is the difference between import and static import?

import static import
The import statement allows the java programmer to access classes of a package without package qualification. The static import statement allows to access the static members of a class without the class qualification.
The import statement provides accessibility to classes and interface. The static import statement provides accessibility to static members of the class.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s