x

Java – Static keyword

Prev     Next

  • Generally, a member declared in a class can only be accessed through the object of that class. But, declaring a member as static means that it can be accessed without creating object and it belongs to the class and not to the instance.
  • The keyword ‘static’ can be applied to variable, method, block and nested class.

Static Variable (class variable):

  • Static variable is initialized only once.
  • A single copy is created and shared by all the instances of the class.  It can be accessed without using object.
  • A static variable can be accessed outside of the class using the following

syntax:


Classname.static_variable

Static Method:

A static method belongs to the class rather than the instances of the class. There are some restrictions over static methods. They are,


  • A static method can directly call only static methods
  • It can directly access only static fields
  • It cannot use ‘this’ and ‘super’ (since these keywords (this and super) are used to access a particular object, they cannot be used for static contents as they are class specific, not object specific)

Static method can be invoked  using the following syntax

Classname.static_method();

Static Block:

Static blocks are executed when the class gets loaded even before any other method in the class. Initializations of variables and other startup procedures can be defined in a static block since it is first block executed when a class gets loaded.

That’s why the main method is declared as ‘static’ as mentioned in previous chapters.

Syntax:

static {
//statements
}

Example:

Output:

Hello
a=5         b=10

Prev     Next



Like it? Please Spread the word!