static keyword in java

We are going to discuss about static keyword in java. The static keyword is a special keyword in java programming language. A static member belongs to a class and is not linked with an instance of a class. We can use static keyword, static method, static variable.

static keyword in java

static keyword in java

We are going to discuss about static keyword in java. The static keyword is a special keyword in java programming language. A static member belongs to a class and is not linked with an instance of a class. We can use static keyword, static method, static variable.

A static keyword points the following:

  • static methods.
  • static variable.

 static methods:-

static method are unique function in java program. In static method we call other static methods only and we do not call a non static method. In static method we can directly access the class name and do not need any object. Also in static method we can access only static information we can not access non static information.

Syntax of static method:-

<class-name>.<method-name>

static variable:-

A static variable is a special function in java programming language. We can create single copy of all instance of a class. In a static variable we can directly access the class name and do not need any object. We can only initialize it once at the start of the execution.

Syntax of static variable:-

static type varName = value;

Example of static method and static variable

class StaticTest {
int x; //initialized to zero.
static int y; 
 
  StaticTest(){
   //static variable y
   y++;
  }
 
   public void showData(){
      System.out.println("Value of x = "+x);
      System.out.println("Value of y = "+y);
   }

}
 
 public class Test{
   public static void main(String args[]){
     StaticTest s1 = new StaticTest();
     s1.showData();
     StaticTest s2 = new StaticTest();
     s2.showData();
     //Student.b++;
     //s1.showData();
  }
}

Download Source Code