• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

Static Keyword in Java | Static Variable | Static Method | Static Class | Static Block

July 6, 2015 by javainterviewpoint Leave a Comment

The static keyword belongs to the class rather than instance of the class. We can simply say that the members belongs to the class itself. As a result, you can access the static member without creating the instance for the class. The static keyword can be applied to variables, methods, blocks and nested class. Lets see them one by one.

Java static variable

If we declare a variable with “static” keyword, then it is called as static variable. For example

static int y=0;

All the instance of the class share the same copy of the variable, a static variable can be accessed directly by calling “<<ClassName>>.<<VariableName>>” without need to create instance for the class.

For a better understading we will see an example without and with static variable.

Without Static Variable

public class StudentExample 
{
    String studentName;
    int age;
    
    public String getStudentName() {
        return studentName;
    }

    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public void disp()
    {
        System.out.println("Stundent Name : "+studentName+" Age : "+age);
    }
   
    public static void main(String args[])
    {
        StudentExample s1 = new StudentExample();
        s1.setStudentName("JavaInterviewPoint");
        s1.setAge(22);
        
        StudentExample s2 = new StudentExample();
        
        s1.disp();
        s2.disp();
    }
}

When we run the above code we will get the below output

Stundent Name : JavaInterviewPoint Age : 22
Stundent Name : null Age : 0

We have set values only with instance s1 and not with s2 so we are getting null and 0. Since the Non-static variable (Instance) variable are associated with each instance we are getting different values.

Lets make those variable static now

With Static Variable

public class StudentExample 
{
    static String studentName;
    static int age;
    
    public String getStudentName() {
        return studentName;
    }

    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public void disp()
    {
        System.out.println("Stundent Name : "+studentName+" Age : "+age);
    }
   
    public static void main(String args[])
    {
        StudentExample s1 = new StudentExample();
        s1.setStudentName("JavaInterviewPoint");
        s1.setAge(22);
        
        StudentExample s2 = new StudentExample();
        
        s1.disp();
        s2.disp();
    }
}

When we run the above code we will get the below output

Stundent Name : JavaInterviewPoint Age : 22
Stundent Name : JavaInterviewPoint Age : 22

Since we have changed variable into static, All instances share the same copy of the variable and hence we are getting the same values even though we have not set values using s2 instance.

Java static method

If we declare a method with “static” keyword, then the method is called as static method.

  • The static method belongs to class rather than object.
  • A static method can access static varaibles directly and it cannot access non-static variables.
  • A static method can only call a static method directly and it cannot call a non-static method from it.
  • super and this keyword cannot be used in a static method.
  • A static method can be directly called by using the class name <<ClassName>>.<<MethodName>> rather than object. This is the main reason we have declared our main() method as static. If not the JVM has to create object first and call the main() method which causes the problem of having extra memory allocation.

In the below example we can see that we are calling the displayStudentDetails() method directly with the classname and not with instance.

public class StudentExample 
{
    static String studentName;
    static int age;
    
    public static void displayStudentDetails()
    {
        StudentExample.studentName ="JavaInterviewPoint";
        StudentExample.age = 22;
        /*studentName ="JavaInterviewPoint";
        age = 22;*/
        System.out.println("Stundent Name : "+studentName+" Age : "+age);
    }
   
    public static void main(String args[])
    {
        StudentExample.displayStudentDetails();
    }
}

Java static block

The static block, is a block of code inside a Java class that will be executed when a class is first loaded in to the JVM. Mostly the static block will be used for initializing the variables.

Lets take a look into the below code.

public class Test 
{
    static int i;
    static 
    {
        System.out.println("Inside static block");
        i=10;
    }
    public static void main(String args[])
    {
        System.out.println(i);
    }
}

In the above code we can see that we are initializing the variable “i” to 10. This happens when the class is loaded by the JVM even before calling the main() method.

Can a static block exist without a main() method ?

The answer is Yes. You can have static block alone in the class without a main method. We all know dynamic loading of a class using Class.forName which we mostly use while loading our JDBC drivers. When we look into the Driver class it will have only the static block and nothing else.

Lets take a look into the Driver class of MySql.

public class Driver extends NonRegisteringDriver implements java.sql.Driver 
{
    static 
    {
        try 
        {
            java.sql.DriverManager.registerDriver(new Driver());
        } catch (SQLException E) 
        {
            throw new RuntimeException("Can't register driver!");
        }
    }
    public Driver() throws SQLException 
    {
        // Required for Class.forName().newInstance()
    }
}

As we all know that static block gets executed while loading of the class, so when the Driver class is loaded it actually passes its object to the registerDriver() method of DriverManager class.

Java static class

In Java only nested classes are allowed to be declared as static, if we declare a top level class as static then it will throw error. Even though static classes are nested inside a class, they doesn’t need the reference of the outer class they act like outer class only whereas on the other hand non-static nested class need reference of the outer class.

public class Users 
{
    static class VipUsers
    {
        public void displayVipUsers()
        {
            System.out.println("Welcome Vip User");
        }
    }
    class NormalUsers
    {
        public void displayNormalUsers()
        {
            System.out.println("Welcome Normal User");
        }
    }
    
    public static void main(String args[])
    {
        //Nested static class doesn't require instantiation of the outer class
        Users.VipUsers vip = new Users.VipUsers();
        vip.displayVipUsers();
        
        /*Below line will throw error as the non-static class require 
        instantiaion of the outer class
        Users.NormalUsers normal = new Users.NormalUsers();*/
        
        //Nested non-static class require instantiation of the outer class
        Users users = new Users();
        Users.NormalUsers normal = users.new NormalUsers();
        normal.displayNormalUsers();
    }
}

In our Users class we have two nested VipUser which is a static class and NormalUser which is a non-static class.

  • Nested static class doesn’t require the outer class to be instantiated and hence we can create instance for the inner static class directly. Like below
     Users.VipUsers vip = new Users.VipUsers();
  • Nested non-static class requires the outer class to be instantiated first, and inner class object is created on top of it.
    Users users = new Users();
    Users.NormalUsers normal = users.new NormalUsers();
  • When we try to a Non-static method just like a static method
 Users.NormalUsers normal = new Users.NormalUsers();

We will get this error. Must qualify the allocation with an enclosing instance of type Users (e.g. x.new A() where x is an instance of Users).

Other interesting articles which you may like …

  • JVM Architecture – Understanding JVM Internals
  • Object and Object Class in Java
  • Difference between JDK, JRE and JVM
  • Components of Java Development Kit (JDK)
  • What is a Class in Java with Example
  • How to open .class file in Java
  • How to Set Classpath for Java in Windows
  • ClassNotFoundException Vs NoClassDefFoundError
  • How HashMap works in Java
  • How to make a class Immutable in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of polymorphism in Java
  • Types of Inheritance in Java
  • Java does not supports Multiple Inheritance Diamond Problem?

Filed Under: Core Java, Java

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·