Java – Static keyword

The static keyword is used in Java mainly for memory management.
Static keyword can be used with class, variable, method and block. Static members belong to the class, if you make a member static, you can access it without an object.

Static variable:

The static variable can be used to refer to the common property of all objects.
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 of static variable.

    class Student {
    int rollno;
    String name;
    static String college ="ITS";//static variable

    Student(int r,String n){
    rollno=r;
    name = n;
    }
    void display ()
    {
    System.out.println(rollno+" "+name+" "+college);
    }

    public static void main(String args[]) {
    Student s1 = new Student(111, “Pradeep”);
    Student s2 = new Student(222, “kumar”);
    s1.display();
    s2.display()}
    }

     output: 111 Pradeep ITS
    222 kumar ITS

Static Block in Java

  • Is used to initialize the static data member.
  • It is executed before the main method at the time of classloading.

Example of Static Block


class StaticDemo
{
static
{
System.out.println("Hello how r u?");
}
public static void main(String args[])
{
System.out.println("main");
}
}