Q1. How are static variables, static methods and static blocks used in Java ? Explain with an example.
In Java, the static keyword is used for class-level members that are shared across all objects and are loaded once when the class is loaded into memory.
Each static component serves a specific purpose:
1. Static Variable
A static variable belongs to the class, not to individual objects.
Example use case:
Company name shared by all employees.
2. Static Block
A static block is used to execute code when the class is loaded, before any object is created.
3. Static Method
A static method belongs to the class and can be called without creating an object.
Complete Example
Each static component serves a specific purpose:
1. Static Variable
A static variable belongs to the class, not to individual objects.
- Only one copy exists in memory
- Shared by all instances of the class
- Ideal for values that are common for all objects
Example use case:
Company name shared by all employees.
static String company = "Tech Innovators";2. Static Block
A static block is used to execute code when the class is loaded, before any object is created.
- Executes only once
- Used for initialization or startup messages
- Runs before main() if the class is loaded
static { System.out.println("Welcome to the Employee Management System!");}3. Static Method
A static method belongs to the class and can be called without creating an object.
- Cannot access non-static variables directly
- Used for utility or helper operations
public static void displayCompany() { System.out.println("Company: " + company);}Complete Example
public class Employee {
int id; String name; static String company = "Tech Innovators";
// Static block static { System.out.println("Welcome to the Employee Management System!"); }
// Constructor public Employee(int id, String name) { this.id = id; this.name = name; }
// Static method public static void displayCompany() { System.out.println("Company: " + company); }
@Override public String toString() { return "Employee [id=" + id + ", name=" + name + ", company=" + company + "]"; }
public static void main(String[] args) {
Employee.displayCompany(); // Static method call
Employee e1 = new Employee(1, "Alice"); Employee e2 = new Employee(2, "Bob");
System.out.println(e1); System.out.println(e2); }}