Java static keyword

 Java static keyword

The static keyword in Java is used for memory management mainly. We can apply static keyword with variables, methods, blocks and nested class

The static keyword belongs to the class than an instance of the class

The static can be:

  1. Variable (also known as a class variable)
  2. Method (also known as a class method)
  3. Block
  4. Nested class

1) Java static variable:-

If you declare any variable as static, it is known as a static variable.

  • The static variable can be used to refer to the common property of all objects (which is not unique for each object), for example, the company name of employees, college name of students, etc.

  • The static variable gets memory only once in the class area at the time of class loading.

Advantages of static variable

It makes your program memory efficient (i.e., it saves memory).

Example:-

class Student

{  

   int rollno;

   String name;  

   static String college ="ITS";   

   Student(int r, String n)

  {  rollno = r;  

   name = n;  

   }  

   void display ()

   {

System.out.println(rollno+" "+name+" "+college);}  

   }  

   class Test

{  

  public static void main(String args[]){  

  Student s1 = new Student(111,"Karan");  

  Student s2 = new Student(222,"Aryan");  

   s1.display();  

 s2.display();  

 }  

}  

2) Java static method:-

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

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

  • A static method can be invoked without the need for creating an instance of a class.

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

Example:-

class Test

{


    static int a = m1();

      static

{

        System.out.println("Inside static block");

     }

      

  static int m1()

{

        System.out.println("from m1");

        return 20;

     }

      

  public static void main(String[] args)

     {

        System.out.println("Value of a : "+a);

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

     }

  

  }

3) Java static block:-

  • Is used to initialize the static data member.

  • It is executed before the main method at the time of classloading.

Example:-

class A2
{  
  static
{
System.out.println("static block is invoked");
}  
  public static void main(String args[])
{  
   System.out.println("Hello main");  
   }  
}  

Comments

Popular posts from this blog

Inheritance in Java

Type Conversions

Life cycle of a Thread and creating thread class