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
2
3
4
5
6
7
8
9
10
11
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);
    }
}
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
2
Student.college="Oxford";
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
2
3
4
Student student = new Student();
student.name="John";
student.id="1234";
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
2
3
4
public class Library{
    static class Book{
    }
}
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

Karibasappa G C (KB)
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