Thursday, 17 August 2017

Static Keyword in Java

The static keyword in Java defines that the variable or method is shared among all instances of that class as it belongs to the type, not the actual objects themselves.

The Static keyword can be applied to

  • Variable
  • Method
  • Block


Static Variable :

You have a variable: private static int iNum = 0; and you increment it ( iNum++ ) in one instance, the change will be replicate in all instances.

Static variables are initialized only once, when you start the execution. These variables will be initialized first, before the initialization of any instance variables

A static variable can be accessed directly by the class name and doesn’t require any object

Static method

If you apply static keyword with any method, it is known as static method.

A static method goes to the class rather than object of a class.

A static method called without the need for creating an instance of a class.

static method can access static data member and can change the value of it.

A static method can be accessed directly by the class name and doesn’t require any object.

A static method cannot refer to "this" or "super" keywords in anyway

Static block

Static block is generally used for changing the default values of static variables.

This block gets executed when the class is loaded in the memory.

A class may have multiple Static blocks, which will execute in the same series in which they have been written into the program.

Example of Static variable, method and block:

Example Code
class exam
{
   public static void show()
   {
                System.out.println("exam -> show method");
   }
   static
   {
                System.out.println("exam->static block");
   }
}

public class myclass
{
   static int iNum = 21;
   static
   {
                System.out.println("myclass->static block");
   }
   public static int add(int x,int y)
   {
                return(x+y);
   }
   public static void main(String args[])
   {
                int a,b,c;
                a = 5;
                b = 7;
                c = add(a,b);
                System.out.println("Addition : "+c);
                System.out.println("iNum : "+iNum);
                exam.show();
   }
}
Output:
myclass->static block
Addition : 12
iNum : 21
exam->static block
exam -> show method


In this post we learned about static variable,method and block.

0 comments:

Post a Comment