×

Html & Html5

The World's best Software Development Study Portal

Java Static keyword

Static keyword is used for memory management purpose.Static keyword belongs to class rather than instance of class(i.e object).By applying Static keyword with variables,method,block,nested class we can make available them for entire class rather than instance of class.So,Static can be:-

  1. Method
  2. Variable
  3. Block
  4. Nested class

Static Variable

If you declare variable as static,its known as static variable and static variable value remain constant throughout class ,it will not vary for class and instance of class.

  • It can be used to refer common property to all objects.
  • Gets memory only once in class area at the time of class loading.
  • Makes program more efficient.

Count program without static variable in which counts get incremented every time separately when we invoke object.

class College{

int count=0;

College(){

count++;

//incrementing value

System.out.println(count);

}

public static void main(String args[]){

//Creating objects

College c1=new College();

College c2=new College();

College c3=new College();

}

};

Output

Count program with static variable which makes variable available for entire class.

class College{

Static int count=0;

College(){

count++;

//incrementing value

System.out.println(count);

}

public static void main(String args[]){

//Creating objects

College c1=new College();

College c2=new College();

College c3=new College();

}

};

Output



Static Method

Method with static keyword is known as Static method.

  • Belong to the class rather than object of class.
  • Can be invoked directly i.e without creating instance of class.
  • Can access static data member and can change value of it.

Restrictions of static method

  • Static method can't use non-static data member or call non-static method directly.
  • this and super can't be used in static context.

Static method program:

class Calculate{

static int cube(int x){

return x*x*x;

}

public static void main(String args[]){

int result=Calculate.cube(5);

System.out.println(result);

}

};

Output:



Static Block

Used to initialize static data member. It is executed before main method at time of classloading.

Static block program:

class A2{

static{System.out.println("static block");}

public static void main(String args[]){

System.out.println("Hello main");

}

}

Output: