Static in Java

Static In Java

The static keyword in Java is used to share the same variable or method of a given class. You can use static keywords with variables, methods, blocks, nested classes, etc. The static keyword belongs to the class. In Java, a static keyword is used for memory management.

Demo Example

class Database{
    static String host = "localhost";
}
public class Main {
    public static void main(String[] args) {
        // We can get static properties by Classname.propertiesName
        System.out.println("Database host is "+Database.host);
    }
}
Show Output

Static Methods

When the method is declared with a static keyword, then that method is called a static method.

class Database{
    // static method
    static String getInfo(){
        return  "localhost";
    }
}
public class Main {
    public static void main(String[] args) {
        // We can get static method by Classname.methodName
        System.out.println("Database host is "+Database.getInfo());
    }
}
Show Output

When to use static variables and methods?

You can use a static keyword that is common for all use cases. E.g., In database host, database name, username, password, etc. We can store it on a static keyword.

Other Example Of Static

Here in this example, school is shared between all objects. We don’t need to set school for every student.



public class Main {
    public static void main(String[] args) {
        //  we can access static value by Classname.propertyname. It can be shared to all objects.
Student.school = "Hiway School";

        Student s1 = new Student();
        
        s1.name = "Bikash";
        s1.address = "USA";
        s1.email = "[email protected]";


        Student s2 = new Student();
        s2.name = "Menuka";
        s2.address = "USA";
        s2.email = "[email protected]";

        // we don't need to set the school
        System.out.println("School of "+s1.name +" : "+s1.school);
         System.out.println("School of "+s2.name +" : "+s2.school);
        
    }
}

class Student{
    String name;
    String address;
    String email;
    // here school is declared as static.
    static String school;

}
Show Output