javatutelearn.com

Easy Learning


Home

Search Javatutelearn.com :



Java Static block

  • Static block is used to initialize the static variable.
  • It is executed only once , when the class is loaded first time.

Example: Static Block

class staticblock {
	static int k = 6;
	static int n;
	static void display() {
			System.out.println("k = " + k);
			System.out.println("n = " + n);
	}
// static block
	static {
			n = k * 2;  // initializing n static variable
	}
	public static void main(String args[]) {
			display();
	}
}

Output of the program
k = 6
n = 12

Explanation of the program

  • A class named staticblock has been created which has two static variables k and n
  • Static variable k is initialized immediately with the value 6 .
  • Static variable n is initialized in the static block which is defined using static keyword .
  • When the above the program is executed then following sequence of execution follows:
  • When the class staticblock is loaded, first static variable k is initialized.
  • Then static block is executed which initializes the static variable n .
  • Then main() method is called which executes the static method display() .
  • Static method display() displays values of static variables.


© Copyright 2016-2024 by javatutelearn.com. All Rights Reserved.