Core JAVA

static keyword in Java

The static is a keyword defined in the java programming language. Keywords are basically reserved words which have specific meaning relevant to a compiler in java programming language likewise the static keyword indicates the following :

  •  The static keyword is applicable to an inner class (a class defined within another class), method or field.
  •  In java language, a static keyword is used with a class (inner) needed to be instantiated, even this may be referenced by some other class indicating as if it – were a top−level class in the class hierarchy.
  • A static keyword can also be used with a  field of a class, such a field exists across all the instances of that particular class. 

The static keyword is used in java mainly for memory management. We may apply static keyword with variables, methods and blocks. The static keyword belongs to the class than instance of the class. The static can be:

  1. variable (also known as class variable)
  2. method (also known as class method)
  3. block

static variable

  • It is a variable which belongs to the class and not to object(instance)
  • Static variables are initialized only once , at the start of the execution . These variables will be initialized first, before the initialization of any instance variables
  • single copy to be shared by all instances of the class
  • A static variable can be accessed directly by the class name and doesn’t need any object

Syntax : <class-name>.<variable-name>

    Advantage of static variable:
    Understanding problem without static variable-

    class Employee{
         int empId;
         String empName;
         String compName="DAV JavaServices Ltd.";
    }
    

    Suppose there are 3000 employees in our company, now all instance data members will get memory each time when object is created.All employees have its unique empId and empName so instance data member is good. Here, company refers to the common property of all objects. If we make it static,this field will get memory only once.

    Note:static field is shared by all objects.

    Example of static variable:

    //Program of static variable
    
    class Employee{
       int empId;
       String empName;
       static String compName = "DAV JavaServices Ltd.";
       
       Employee(int empId, String empName){
          this.empId = empId;
          this.empName= empName;
       }
     void display (){
    
       System.out.println(empId+" "+empName+" "+compName );
      }
    
     public static void main(String args[]){
         Employee employee1 = new Employee(111,"Dinesh");
         Employee employee2 = new Employee(222,"Sweety");
     
        employee1.display();
        employee2.display();
     }
    }
    

    Output:
    111 Dinesh DAV JavaServices Ltd.
    222 Sweety DAV JavaServices Ltd.

    static method

    • It is a method which belongs to the class and not to the object(instance)
    • A static method can access only static data. It can not access non-static data (instance variables)
    • A static method can call only other static methods and can not call a non-static method from it.
    • A static method can be accessed directly by the class name and doesn’t need any object
    • Syntax : <class-name>.<method-name>
    • A static method cannot refer to “this” or “super” keywords in anyway

    Example of static method:

    //Program of changing the common property of all objects(static field).
    
    class Employee{
         int empId;
         String empName;
         static String compName = "DAV JavaServices Ltd.";
         
         static void change(){
            compName = "DOJ Ltd";
         }
    
         Student(int empId, String empName){
            this.empId = empId;
            this.empName = empName;
         }
    
         void display (){
    
         System.out.println(rollno+" "+name+" "+college);
         }
    
        public static void main(String args[]){
            Employee.change();
    
           Employee employee1 = new Employee(111,"Dinesh");
           Employee employee2 = new Employee(222,"Sweety");
           Employee employee3 = new Employee(333,"Anamika");
    
           employee1.display();
           employee2.display();
           employee3.display();
        }
    }
    

    Output:
    111 Dinesh DOJ Ltd.
    222 Sweety DOJ Ltd.
    333 Anamika DOJ Ltd.

    //Program of accessing non-static data member directly from static method main
    
    class A{
     int a=40;//non static
     
     public static void main(String args[]){
      System.out.println(a);
     }
    }   
    

    Output:
    Compile Time Error

    Que)why main method is static?
    Ans) because object is not required to call static method if it were non-static method, jvm creates object first then call main() method that will lead the problem of extra memory allocation.

    static block:

    • Is used to initialize the static data member.
    • It is executed before main method at the time of classloading.
    • static block helps to initialize the static data members, just like constructors help to initialize instance members

    Example of static block

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

    Output:
    static block is invoked
    Hello main

    Can we execute a program without main() method?
    — Yes, one of the way is static block but in previous version of JDK not in JDK 1.7.

    //Program of executing a program without main() method
    
    class A{
      static{
      System.out.println("static block is invoked");
      System.exit(0);
      }
    }
    
    

    Output:

    static block is invoked (if not JDK7)

    <<Previous <<   || Index ||   >>Next >>
    Previous
    Next
    Dinesh Rajput

    Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

    Share
    Published by
    Dinesh Rajput

    Recent Posts

    Strategy Design Patterns using Lambda

    Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…

    2 years ago

    Decorator Pattern using Lambda

    Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…

    2 years ago

    Delegating pattern using lambda

    Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…

    2 years ago

    Spring Vs Django- Know The Difference Between The Two

    Technology has emerged a lot in the last decade, and now we have artificial intelligence;…

    2 years ago

    TOP 20 MongoDB INTERVIEW QUESTIONS 2022

    Managing a database is becoming increasingly complex now due to the vast amount of data…

    2 years ago

    Scheduler @Scheduled Annotation Spring Boot

    Overview In this article, we will explore Spring Scheduler how we could use it by…

    3 years ago