Java: static keyword

In this article, we will discuss static keyword in Java. static keyword falls under non-access modifier category

 

Advantage: Use of static helps in efficient memory management in Java

 

static keyword can be used with

  • variable (referred as static variable or class variable)
  • block (referred as static blocks)
  • method (also referred as static method or class method)
  • class (only nested class or static class)

Note: All static related fields, blocks and methods belongs to class rather specific to any instance

We will discuss each one in detail

 

1) static variable

  • A variable declared with static modifier is known as static variable
  • Alternatively it is referred as class variable as it belongs to class rather to any specific instance
  • Static variable shared among every instance like for example organization name of the employee
  • It should be used whenever there is common property for all objects of that class
  • Static variables can be accessed directly by class name or interface name instead of creating an instance and then accessing
  • Static variables can be accessed from static and non-static methods/blocks using class name or interface name
  • Memory allocation for static variables happens at the time of class loading by JVM

 

Let us see few examples based on static variable

Employee.java

package in.bench.resources.staticexample;

public class Employee {

	// instance variables - unique for every objects
	int employeeId;
	String employeeName;

	// static variable - shared among every objects
	static String ORGANIZATION_NAME = "ABC Pvt. Ltd.";

	// 2-arg parametrized constructor 
	Employee(int employeeId, String employeeName) {
		this.employeeId = employeeId;
		this.employeeName = employeeName;
	}

	// display() method - to show organization name & other properties
	void displayEmployeeInfo() {
		System.out.println(employeeId + "\t" + employeeName + "\t" + ORGANIZATION_NAME);
	}

	// main() method - the entry point to JVM to begin execution
	public static void main(String[] args) {

		// create 2 objects for employee
		Employee employee1 = new Employee(1001, "Tom");
		Employee employee2 = new Employee(1002, "Harry");

		// invoke display method for each employees and see ORGANIZATION_NAME
		employee1.displayEmployeeInfo();
		employee2.displayEmployeeInfo();
	}
}

Output:

1001	Tom	ABC Pvt. Ltd.
1002	Harry	ABC Pvt. Ltd.

 

Explanation:

  • There are 2 instance variable and one common static variable for organization name
  • Static field ORGANIZATION_NAME is initialized with value
  • When we created employee objects, we are passing values for name and id
  • Which means, only id and name is different and org name is common for all employee
  • We can access the static field using class name (or interface name)

 

Accessing static variable using class name (or interface name)

TestStatic.java

package in.bench.resources.staticexample;

public class TestStatic {

	// user-defined class variable
	static String ORGANIZATION_NAME = "ABC Pvt. Ltd.";

	// main() method - the entry point to JVM to begin execution
	public static void main(String[] args) {

		System.out.println("Accessing user-defined static variable using class name");
		System.out.println("ORGANIZATION_NAME : " + TestStatic.ORGANIZATION_NAME);

		System.out.println("\nAccessing static variable from Java library");
		System.out.println("PI value from Math class : " + Math.PI);
		System.out.println("E value from Math class : " + Math.E);
	}
}

Output:

Accessing user-defined static variable using class name
ORGANIZATION_NAME : ABC Pvt. Ltd.

Accessing static variable from Java library
PI value from Math class : 3.141592653589793
E value from Math class : 2.718281828459045

 

Explanation:

  • Both user-defined and reserved static fields in Java can be accessed using class name
  • And corresponding value is printed in the console
  • No object creation steps required to access static fields or static variables

 

2) static method

  • A method declared with static modifier is known as static method
  • Alternatively it is referred as class method as it belongs to class rather than object of a class
  • Static methods can be accessed using class name instead of creating an instance and then invoking
  • Static methods can access static variables directly
  • Non-static methods can access static methods directly without creating an instance of class
  • And of course, a static method can access another static method directly
  • To access non-static fields/methods, an object is required and this is different from accessing static methods/fields

Let us see an example on static methods

Invoking static method directly

Employee.java

package in.bench.resources.staticexample;

public class Employee {

	// static method to broadcast message to employees
	static void broadcastMessageToEmployee() {
		System.out.println("Bonus announced !! Please check bonus letter !!");
	}

	// main() method - the entry point to JVM to begin execution
	public static void main(String[] args) {

		// invoking static method directly, without creating object
		broadcastMessageToEmployee();
	}
}

Output:

Bonus announced !! Please check bonus letter !!

 

Here, static method broadcastMessageToEmployee() is accessed from main() method without creating an instance of a class

 

Invoking static method using class name

Syntax: <Class_Name>.<static_method>

ParentClass.java

package in.bench.resources.staticexample;

public class ParentClass {

	static void display() {
		System.out.println("ParentClass : invoking static method using class name");
	}
}

ChildClass.java

package in.bench.resources.staticexample;

public class ChildClass {

	// main() method - the entry point to JVM to begin execution
	public static void main(String[] args) {

		// invoking parent's static method using class name
		ParentClass.display();
	}
}

Output:

ParentClass : invoking static method using class name

 

Explanation:

From child class, we are invoking parent class’s static method using class name and then printing simple message in the console

Note: There is no relation between parent class and child class, except both classes are in same package

 

3) static block

Static blocks are bundle of valid Java statements within {curly braces} preceded/prefixed with “static” keyword

Syntax of Static blocks

static {
	// bundle of valid Java statements
	// for initialization for static data member
}

Note: Static blocks are also known as “static initializer” or “static initialization blocks

Key points about Static blocks:

  • Static blocks is used to initialize static data members or class variables only
  • Static blocks are executed only once i.e.; at the time of class loading
  • Any number of static blocks can be created inside class body
  • But if there are multiple static blocks, then these are executed in the order they are defined
  • Just lines of Java statements with no arguments or return values
  • Static methods can be invoked from static blocks i.e.; within {curly braces}
  • As static blocks are belongs to classes rather objects, therefore this and super keyword cannot be used
  • Static blocks can throw unchecked exception only like RuntimeException
  • Note: static blocks are executed even before main() method

 

StaticBlocks.java

package in.bench.resources.staticexample;

public class StaticBlocks {

	// static block - 1
	static {
		System.out.println("StaticBlocks : static block - 1");
	}

	// main() method - the entry point to JVM to begin execution
	public static void main(String[] args) {
		System.out.println("Printing message in console from main() method");
	}

	// static block - 2
	static {
		System.out.println("StaticBlocks : static block - 2");
	}
}

Output:

StaticBlocks : static block - 1
StaticBlocks : static block - 2
Printing message in console from main() method

 

Note: Just we executed the main() method, not even created object of class type still static blocks got executed

Which proves static blocks are executed at the class loading time

 

4) static class

Nested Class: A class containing another class is known as Nested class

Enclosing class is called top-level class or outer class and inside class is called as Inner class

Java allows only static nested class; which means top-level class or outer class can never be static

  • An Inner class with static modifier is known as static nested class or static class
  • Nested static class can be accessed without creating object of outer class
  • Or in simple terms, nested static class can be accessed using outer class name
  • Static inner class can access only static data members and static methods of the enclosing class (or outer class)
  • Which means only static data members and static methods of outer class can be accessed from nested inner class

Let us see an example on nested static class

All static

Nested static class invoking outer class’s static methods where it is accessing outer class’s static data members

OuterClass.java

package in.bench.resources.staticexample;

public class OuterClass {

	// static data members
	static int counter = 10235;
	static String counterName = "BenchResources.Net";

	// static inner class or nested static class
	static class NestedStaticClass {

		static void display() {
			System.out.println("Accessing static fields\n==========================");
			System.out.println("Site : " + counterName + "\nPage Views : " + counter);
		}
	}

	// main() method - the entry point to JVM to begin execution
	public static void main(String[] args) {

		// invoking static method : inside nested static class w/o creating objects
		OuterClass.NestedStaticClass.display();
	}
}

Output:

Accessing static fields
==========================
Site : BenchResources.Net
Page Views : 10235

 

Explanation:

In above example,

  • Outer class invoking static method of nested static class without creating instance
  • In similar way, we can access static method of nested static class from any other class (until there is no restriction w.r.t accessibility)
  • As we can see from example, static data members of outer class can be accessed directly

 

Let us move on see another example on how to access instance methods and instance variables

Static and instance together

Instantiating nested static class is different from normal class and after creating object, then invoking instance method using newly created object

Also, instance method of static nested class –> creates an object of outer class and access instance data members

OuterClass.java

package in.bench.resources.staticexample;

public class OuterClass {

	// instance data members
	String name;

	// 1-arg parametrized constructor
	OuterClass(String name) {
		this.name = name;
	}

	// static inner class or nested static class
	static class NestedStaticClass {

		// instance method inside inner class
		void display() {

			// instantiating outer class to access data members
			OuterClass outerClass = new OuterClass("Warner");
			System.out.println("Name : " + outerClass.name);
		}
	}

	// main() method - the entry point to JVM to begin execution
	public static void main(String[] args) {

		// instantiating static nested class in outer class
		OuterClass.NestedStaticClass obj = new OuterClass.NestedStaticClass();
		obj.display();
	}
}

Output:

Name : Warner

 

Explanation:

Self-explanatory from above source code

 

Point to remember about static keyword:

  • Static keyword can be applied with variables, methods, blocks or classes
  • Anything related to static belongs to class rather to any specific instances
  • Static keyword with field is known as static field or static variable or class variables
  • Static keyword with method is known as static method or class methods
  • Static keyword with blocks is known as static blocks
  • Static keyword with classes is known as static classes or nested static classes
  • Instantiating nested static class is different from normal class
  • Static variables can be accessed using class name or interface name
  • Variables declared inside interface are implicitly static
  • Even static methods can be accessed using class name
  • Non-static methods can access static methods directly without creating an instance of class
  • Static blocks are executed only once at class loading time
  • Static blocks can access only static data members and static methods
  • Java allows only static nested class; which means top-level class or outer class can never be static

That’s all about static keyword in Java

 

References:

https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html
https://docs.oracle.com/javase/tutorial/java/javaOO/initial.html
https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html

 

Read Also:

Happy Coding !!
Happy Learning !!

Java: this keyword
Interview Question and Answers on final keyword in Java