static keyword

In this chapter you will learn:

  1. How to declare a static method and use it
  2. How to declare static variables and use them
  3. How to use static initialization block
  4. A demo for static variables and static methods

static method

A static method can be used by itself. Here shows how to declare static method.

static void aStaticMethod(){
}

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.

All instances of the class share the same static variable. You can declare a static block to initialize your static variables. The static block gets only called once when the class is first loaded.

The following example shows a class that has a static method

public class Main {
  static int a = 3;
  static int b;
// j  av a  2  s  .  c  o m
  static void meth(int x) {
    System.out.println("x = " + x);
    System.out.println("a = " + a);
    System.out.println("b = " + b);

  }

  public static void main(String args[]) {
    Main.meth(42);
  }
}

The output:

static variables

The following example shows a class that has the static variables.

public class Main { 
    static int a = 3; 
    static int b; 
}

We can reference the static variables defined above as follows:

Main.a

static initialization block

The following example shows a class that has a static initialization block.

public class Main {
//from   j  a  v a  2  s  .  c o  m
  static int a = 3;

  static int b;

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

A demo for static variables and static methods

To call a static method from outside its class, use the following general form:

ClassName.method( )

Here is an example. The static method callme() and the static variable b are accessed outside of their class.

class StaticDemo {
  static int a = 4;
  static int b = 9;
/*  ja v  a2 s . c o  m*/
  static void callme() {
    System.out.println("a = " + a);
  }
}
public class Main {
  public static void main(String args[]) {
    StaticDemo.callme();
    System.out.println("b = " + StaticDemo.b);
  }
}

Here is the output of this program:

Next chapter...

What you will learn in the next chapter:

  1. What is the general form of a method
  2. How to add a method to a class