The static keyword in Java is used to declare members that belong to the class rather than individual objects. Static members are created only once and shared by all instances of the class.
Key Points: • Static variables are shared among all objects of a class and have a single copy in memory. • Static methods can be called without creating an object of the class. • Static methods can directly access only static members of the class. • Static blocks are executed once when the class is loaded into memory. • The main() method is declared static so that the JVM can invoke it without creating an object.
Example: If a class contains a static variable named companyName, all objects of that class share the same value instead of maintaining separate copies.
Code Example:
class Employee {
static String company = "ABC Ltd";
static void displayCompany() {
System.out.println(company);
}
}
public class Main {
public static void main(String[] args) {
Employee.displayCompany();
}
}Interview Tip: A concise interview answer is:
"The static keyword is used for class-level members. Static variables, methods, and blocks belong to the class rather than objects, and they can be accessed without creating an instance of the class."