Static Keyword

Static is a keyword in java and it is a non-access modifier in java.

We use static keyword with:

  • Variable: only use with class-level variables. We don’t use with local variable
  • Method
  • Block
  • Inner class or nested class don’t use with the outer class

Why we use Static keyword:

The static keyword mainly uses for memory management and to make programs fast and memory-efficient

Understand one by one:

Static variables:

Any variables in java which has static keyword is called static variable

For example: static int force = 25;

Here force is a static keyword

Full example:

public class Test{
    static int force = 25; //static  variable 
      void main(){
          static int force = 25; //static inside the methods throw error 
     }
}

When we make any  variable static then a single copy of variable created  and  it will be shared between all object at class level

Understand with an example:

public class Student {
    int rollno;
    String name;
    String collage = "DU";
    
    Student (int rollno,String name){
        this.rollno = rollno;
        this.name = name;
    }
    
    void display(){
        
        System.out.println(rollno+" "+name+" "+collage);
    }
         
     public static void main(String []args){
         Student s1 = new Student(52,"Rahul");
         s1.display();
         
         Student s2 = new Student(44,"vanshika");
         s2.display();
        
     }
}
52 Rahul DU
44 vanshika DU

In this example collage i.e. DU shared among objects s1 and s2.
We saved memory.

Static method:

When we create a method by using static keyword is called Static method

Syntax:

public class Student{
   
    static void display(){
        
        System.out.println("static method");
    }
} 

Some important point about the static method:

  • We don’t have to create an object to calling a static method. Because the static method belongs to class, not object
  • A static method can be called directly by class name
    example: Class Name method name ();
  • Creating object occupy memory by static it manages memory
  • We can only access static data by a static method. It cannot access non-static data (instance data)
  • By static method, we can only call another static method in java
  • A static method doesn’t use this or super keyword.

Static block:

If we use static keyword with any block is called a block.

Example:

public class Student{
   
    static{
        
        System.out.println("static block");
     }
       
    public static void main(String []args){
        System.out.println("main method");
     }  
     
}
static block
main method

Static block execute automatically when the class is loaded in the memory

If any class has static methods it will be first executed before the main method.



SHARE THIS PAGE





Important Link