static keyword in Java

Static:

     static is a keyword, the main use for the static keyword is "Memory Management".

We can use static keyword in
Variables
Method
Block
Nested Class

Static keyword in Java

  • Static is used to used to refer the common property of the object. Ex. Employee's company name, Student's college name.

  • The Static variable get memory only once in class area at the time of class loading.
What happen if we don't use Static variable in program ??

class Without_Static
 {
    int id;
    String name;
    String company="Company_Name";
 }
    Without_Static(int a, String b)
      {
          id=a;
          name=b;
          System.out.println(+id+ " "+name+" " +company);
      }
public static void main(String args[])
  {
      Without_Static obj=new Without_Static(333, "Emp_Name");

   }
}
   
Output:
333 Emp_Name Company_Name

From this example each time, while entering 500 Employee name and Id, compiler allocate the separate memory(500 times) for String company. So, It's increase the Memory.

Use of static variable in same program

class Without_Static
 {
    int id;
    String name;
    static String company="Company_Name";
 }
    Without_Static(int a, String b)
      {
          id=a;
          name=b;
          System.out.println(+id+ " "+name+" " +company);
      }
public static void main(String args[])
  {
      Without_Static obj=new Without_Static(333, "Emp_Name");

   }
}
Output:
333 Emp_Name Company_Name

While using static keyword, only time only memory allocated for the variable company so, 499 times of memory was saved that's the point here.

 




No comments:

Post a Comment