There will be times when you will want to define a class member that will be used independently of any object of that class. To create such member, precede its declaration with keyword static.

When a member is declared static, it can be accessed before any objects of its class are created, and without reference to any object.

The most common example of a static member is main( ). main( ) is declared as static because it must be called before any objects exist.

Methods declared as static have several restrictions:
• They can only call other static methods.
• They must only access static data.
• They cannot refer to this or super in any way.

If you need to do computation in order to initialize your static variables, you can declare a static block that gets executed exactly once, when the class is first loaded.


//Demonstrate static variables, methods, and blocks.
class UseStatic {
 static int a = 3;
 static int b;

static void meth(int x) {

System.out.println("x = " + x);
 System.out.println("a = " + a);
 System.out.println("b = " + b);

static {
 System.out.println("Static block initialized.");
 b = a * 4;

public static void main(String args[]) {

Here is the output of the program:
Static block initialized.
x = 42
a = 3
b = 12

Next Steps...

This is should be a prospective customer's number one call to action, e.g., requesting a quote or perusing your product catalog.

Proudly powered by WordPress | Theme: Baskerville 2 by Anders Noren.

Up ↑