Java – static keyword with example

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

  1. variable (referred as static-variable or class-variable)
  2. block (referred as static-blocks)
  3. method (also referred as static-method or class-method)
  4. 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 it
  • static-variables can be accessed from static and non-static method/blocks using class-name or interface-name
  • Memory allocation for static-variable happens at the time of class-loading by JVM i.e.; at the start of class-loading itself

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 parameterized constructor
	Employee(int employeeId, String employeeName) {
		this.employeeId = employeeId;
		this.employeeName = employeeName;
	}

	// display() method - to print all 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
		employee1.displayEmployeeInfo();
		employee2.displayEmployeeInfo();
	}
}

Output:

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

Explanation:

  • There are 2 instance variables and one common static-variable for organization-name
  • Static-field or static-variable ORGANIZATION_NAME is initialized with value “ABC Pvt. Ltd.”
  • 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 employees
  • We can access static-field using class-name (or interface-name)

1.1. 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-method can be accessed using class-name instead of creating an instance and then invoking using reference-variable
  • static-method 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 field/method, an object is required and this is different from accessing static field/method

Let us see an example on static methods

2.1. 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
	public static void main(String[] args) {

		// invoking static-method directly
		broadcastMessageToEmployee();
	}
}

Output:

Bonus announced !! Please check bonus letter !!

Explanation :

  • Here, static method broadcastMessageToEmployee() is accessed from main() method without creating an instance of a class
  • because from static main() method, we can access static field/method directly

2.2. 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 block
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

3.1. Key points about static-block :

  • static-block is used to initialize static data members or class-variables only
  • static-block are executed only once i.e.; at the time of class loading
  • Any number of static-block 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-method can be invoked from static-block i.e.; within {curly braces}
  • As static-block belongs to classes rather object, therefore this and super keyword cannot be used in the static-context
  • static-block can throw unchecked-exception only like RuntimeException, etc.
  • Note: static-block are executed even before main() method is executed

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

Explanation :

  • We executed the main() method, not even created object of class, still static-block got executed
  • Which proves static-blocks are executed at the class loading time

4. static-class :

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

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

4.2. static nested class :

  • 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

4.3. All static :

  • Nested static-class invoking outer class’ static-method
  • where it is accessing outer-class’ 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 of nested static-class
		// from Outer-class main() method w/o creating object
		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

4.4. Static and instance together

  • Instantiating nested static-class is different from normal-class
  • After creating object of nested static-class, we are invoking instance-method display() of nested-class, using newly created object
  • Inside instance-method of nested static-class, we are creating object of Outer-class and accessing member-variable ‘name’ to print/display it’s value

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

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

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java - this keyword with example
Java - Interview Question and Answers on final keyword