Static

In this note, you will quickly know about the static modifier on variables, constants and methods.

Static Variables

  • Static variables are shared by all the instances of the class.
    • refer to the common property of all objects (which is not unique for each object)
  • Advantages of static variable: makes your program memory efficient (i.e., it saves memory).

Example - The use of Static variable:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//Java Program to illustrate the use of static variable which  
//is shared with all objects.
class Counter2 {
static int count = 0; //will get memory only once and retain its value

Counter2() {
count++; //incrementing the value of static variable
System.out.println(count);
}

public static void main(String args[]) {
//creating objects
Counter2 c1 = new Counter2();
Counter2 c2 = new Counter2();
Counter2 c3 = new Counter2();
}
}

//Output:
//1
//2
//3

Static Constants

  • Static constants are final variables shared by all the instances of the class.

Static Methods

  • Static methods are not tied to a specific object.
    • You can call the static methods without instantiating an object.
  • A static method belongs to the class rather than the object of a class
  • A static method can access static data member and can change the value of it.

Example - You can call the static methods without instantiating an object :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//Java Program to get the cube of a given number using the static method  

class Calculate {
static int cube(int x) {
return x * x * x;
}

public static void main(String args[]) {
//no object instantiated
int result = Calculate.cube(5);
System.out.println(result);
}
}
//Output:125

Restrictions for the static method

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

Why is the Java main method static?

It is because the object is not required to call a static method.

If it were a non-static method, JVM creates an object first then call main() method that will lead the problem of extra memory allocation.

Static Blocks

  • It is executed before the main method at the time of classloading.
  • Is used to initialize the static data member.
1
2
3
4
5
6
7
8
9
10
11
12
class A2{  
static{
System.out.println("static block is invoked");
}
public static void main(String args[]){
System.out.println("Hello main");
}
}

//output:
//static block is invoked
//Hello main

Reference

Javapoint

Geeksforgeeks