static keyword in java

The "static" keyword can be applied to an inner class (a class defined within another class), method or field (a member variable of a class).

Static methods and variables are shared among all instances of a class. They can be invoked and accessed without creating new instances of the class.

Example

  1. public class Student{
  2. String name;
  3. String id;
  4. static String college;
  5.      
  6.     static void displayCollege() {
  7.        System.out.println("College name is "+college);
  8.     }
  9.      
  10.     void displayStudentDetails() {
  11.         System.out.println("Name is "+name+" id is "+id);
  12.     }
  13. }
public class Student{
String name;
String id;
static String college;
     
    static void displayCollege() {
       System.out.println("College name is "+college);
    }
     
    void displayStudentDetails() {
        System.out.println("Name is "+name+" id is "+id);
    }
}


The static members can be accessed using class name directly, We don’t need to create an object for the same.

static variable college and static method displayCollege() can be accessed as below

  1. Student.college="Oxford";
  2. Student.displayCollege();
Student.college="Oxford";
Student.displayCollege();


whereas the non static method displayStudentDetails() can be called using an object of Student class as below

  1. Student student = new Student();
  2. student.name="John";
  3. student.id="1234";
  4. student.displayStudentDetails();
Student student = new Student();
student.name="John";
student.id="1234";
student.displayStudentDetails();


The outer class cannot be static, only inner class can be static as shown below

  1. public class Library{
  2.     static class Book{
  3.     }
  4. }
public class Library{
    static class Book{
    }
}


The inner class Book can be instantiated without creating an instance of the enclosing class Library.

Example
  1. Library.Book book = new Library.Book();
Library.Book book = new Library.Book();

About the Author

Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on