static Keyword in Java with Examples
In this article, we will discuss a lot about static keyword and it’s usage with respect to variables, methods, blocks and nested class.
The static keyword in Java is used a lot in java programming. We can apply java static keyword with variables, methods, blocks and nested class.
1. Java static Variable
We can use a static keyword with a class level variable. A static variable is a class variable and doesn’t belong to Object/instance of the class.
A class variable is any field declared with the static modifier; this tells the compiler that there is exactly one copy of this variable in existence, regardless of how many times the class has been instantiated.
static variable example
Consider these are 100 students in a college named “ABC”, each student have their own unique roll number and name but the college remains the same among all the 100 students. The college field is declared as static so it can occupy memory only once.
package net.javaguides.corejava.variables;
public class StaticVariableExample {
public static void main(String[] args) {
Student student = new Student(100, "Student 1");
Student student2 = new Student(101, "Student 2");
Student student3 = new Student(102, "Student 3");
Student student4 = new Student(103, "Student 4");
System.out.println(" ------------ Student 1 -------------");
System.out.println(student.toString());
System.out.println(student2.toString());
System.out.println(student3.toString());
System.out.println(student4.toString());
}
}
class Student {
private int rollNo;
private String name;
private static String college = "ABC"; // static variable
public Student(int rollNo, String name) {
super();
this.rollNo = rollNo;
this.name = name;
}
@Override
public String toString() {
return "Student [rollNo=" + rollNo + ", name=" + name + ", college=" + college + "]";
}
}
Output:
Student [rollNo=100, name=Student 1, college=ABC]
Student [rollNo=101, name=Student 2, college=ABC]
Student [rollNo=102, name=Student 3, college=ABC]
Student [rollNo=103, name=Student 4, college=ABC]
Note that, all the students have the same college “ABC”.
2. Java static methods
The static methods can access static variables without using an object(instance) of the class, however non-static methods and non-static variables can only be accessed using objects.
We cannot override static methods. Static methods belong to a class, not belongs to object. Inheritance will not be applicable to class members.
Key points
- A static method belongs to the class rather than the object of a class.
- A static method can be invoked without the need for creating an instance of a class.
- A static method can access static data member and can change the value of it.
- A static method can be accessed directly in static and non-static methods.
For example, the main() method that is the entry point of a java program itself is a static method.
They cannot refer to this or super in any way.
Java static method Example
Example 1: In this example, the static main() method is accessing static variables without object and also static main() method calling static add() and substract() methods without object:
package com.javaguides.corejava.keywords.statickeyword;
public class StaticMethodExample {
private static int a = 20;
private static int b = 10;
public static void main(String[] args) {
// static main() method calls static add() method
add();
substract();
}
private static int add() {
return (a + b);
}
private static int substract() {
return (a - b);
}
}
Usually, static methods are utility methods that we want to expose to be used by other classes without the need of creating an instance. For example the Collections class.
Let’s see few static methods from Collections and Arrays utility classes:
static swap() method
/**
* Swaps the two specified elements in the specified array.
*/
private static void swap(Object[] arr, int i, int j) {
Object tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
static fill() method
public static <T> void fill(List<? super T> list, T obj) {
int size = list.size();
if (size < FILL_THRESHOLD || list instanceof RandomAccess) {
for (int i=0; i<size; i++)
list.set(i, obj);
} else {
ListIterator<? super T> itr = list.listIterator();
for (int i=0; i<size; i++) {
itr.next();
itr.set(obj);
}
}
}
static copy() method
public static <T> void copy(List<? super T> dest, List<? extends T> src) {
int srcSize = src.size();
if (srcSize > dest.size())
throw new IndexOutOfBoundsException("Source does not fit in dest");
if (srcSize < COPY_THRESHOLD ||
(src instanceof RandomAccess && dest instanceof RandomAccess)) {
for (int i=0; i<srcSize; i++)
dest.set(i, src.get(i));
} else {
ListIterator<? super T> di=dest.listIterator();
ListIterator<? extends T> si=src.listIterator();
for (int i=0; i<srcSize; i++) {
di.next();
di.set(si.next());
}
}
}
3. Java static block
Java static block is the group of statements that gets executed when the class is loaded into memory by Java ClassLoader.
The basic use-case of a static block is used to initialize the static variables of the class. Mostly it’s used to create static resources when the class is loaded.
package com.javaguides.corejava.keywords.statickeyword;
public class StaticBlockExample {
private static String CONSTANT;
private static int CONSTANT_INT;
static {
CONSTANT = "some constant value";
CONSTANT_INT = 10;
System.out.println("Inside static block ");
System.out.println("static block initialized values :: " + CONSTANT);
}
public static void main(String[] args) {
System.out.println("Inside main() method");
System.out.println("Access constant inside main() method :: " + CONSTANT);
System.out.println("Access constant inside main() method :: " + CONSTANT_INT);
}
}
Output:
Inside static block
static block initialized values :: some constant value
Inside main() method
Access constant inside main() method :: some constant value
Access constant inside main() method :: 10
Key points about a static block
We can’t access non-static variables in the static block.
Static block code is executed only once when the class is loaded into memory.
The static block executes before the main method because a static block is executed during class loading.
4. Java static nested class
We can use the static keyword with nested classes. static keyword can’t be used with top-level classes.
And like static class methods, a static nested class cannot refer directly to instance variables or methods defined in its enclosing class: it can use them only through an object reference.
Static nested classes are accessed using the enclosing class name:
OuterClass.StaticNestedClass
For example, to create an object for the static nested class, use this syntax:
OuterClass.StaticNestedClass nestedObject =new OuterClass.StaticNestedClass();
Here is a complete example of a static nested class:
public class StaticNestedClasses {
public static void main(String[] args) {
final OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();
nestedObject.innerClassMethod();
}
}
class OuterClass {
public void outerClassMethod() {
System.out.println(" outerClassMethod ");
}
static class StaticNestedClass {
public void innerClassMethod() {
System.out.println("innerClassMethod ");
}
}
}
5. Java static methods in Interface (Java 8 onwards)
From Java 8 onwards, we can create static methods in interfaces as well. Generally, static methods are used to define utility methods.
Furthermore, static methods in interfaces make possible to group related utility methods, without having to create artificial utility classes that are simply placeholders for static methods.
Here is an example to demonstrate the creating and using static methods in interfaces:
public interface Vehicle {
String getBrand();
String speedUp();
String slowDown();
default String turnAlarmOn() {
return "Turning the vehice alarm on.";
}
default String turnAlarmOff() {
return "Turning the vehicle alarm off.";
}
static int getHorsePower(int rpm, int torque) {
return (rpm * torque) / 5252;
}
}
There is getHorsePower(int, int) static method in Vehicle interface.
Let’s see how the client uses this method :
public class TestJava8Interface {
public static void main(String[] args) {
Vehicle car = new Car("BMW");
System.out.println(car.getBrand());
System.out.println(car.speedUp());
System.out.println(car.slowDown());
System.out.println(car.turnAlarmOn());
System.out.println(car.turnAlarmOff());
System.out.println(Vehicle.getHorsePower(2500, 480));
}
}
Note that we used an interface name to call a static method.
6. Java static import
Java 5 introduced a new feature — static import — that can be used to import the static members of the imported package or class. You can use the static members of the imported package or class as if you have defined the static member in the current class.
Example:
import static java.lang.Math.PI;
// class declaration and other members
public double area() {
return PI * radius * radius;
}
You can also use wildcard character “*” to import all static members of a specified package of class.