*static
in Java *
In Java, the static
keyword is used to define class-level members (variables, methods, blocks, and nested classes) that belong to the class itself rather than to individual instances (objects). This means they can be accessed without creating an object of the class.
Key Concepts of static
in Java
1. Static Variables (Class Variables)
- Shared among all instances of the class.
- Stored in class memory (not in object memory).
- Initialized only once when the class is loaded.
Example:
class Counter {
static int count = 0; // Static variable
Counter() {
count++; // Incremented for every new object
}
}
public class Main {
public static void main(String[] args) {
Counter c1 = new Counter();
Counter c2 = new Counter();
System.out.println(Counter.count); // Output: 2 (shared across objects)
}
}
-
Output:
2
(sincecount
is shared by all objects).
2. Static Methods
- Belong to the class, not instances.
- Can be called without creating an object.
- Cannot access non-static members (since they depend on object state).
Example:
class MathUtils {
static int add(int a, int b) { // Static method
return a + b;
}
}
public class Main {
public static void main(String[] args) {
int sum = MathUtils.add(5, 3); // No object needed
System.out.println(sum); // Output: 8
}
}
-
Output:
8
(static method called directly using class name).
3. Static Block (Static Initialization Block)
- Runs when the class is loaded (before
main()
). - Used to initialize static variables or perform one-time setup.
Example:
class Database {
static String driver;
static { // Static block runs first
driver = "com.mysql.jdbc.Driver";
System.out.println("Driver loaded: " + driver);
}
}
public class Main {
public static void main(String[] args) {
System.out.println("Main method starts.");
}
}
- Output:
Driver loaded: com.mysql.jdbc.Driver
Main method starts.
4. Static Nested Class
- A static inner class that does not need an instance of the outer class.
- Can access only static members of the outer class.
Example:
class Outer {
static int x = 10;
static class Inner { // Static nested class
void display() {
System.out.println("x = " + x); // Can access static x
}
}
}
public class Main {
public static void main(String[] args) {
Outer.Inner inner = new Outer.Inner(); // No outer object needed
inner.display(); // Output: x = 10
}
}
-
Output:
x = 10
When to Use static
?
Scenario | Example |
---|---|
Shared variables (counters, constants) | static int count = 0; |
Utility methods (Math operations) | Math.sqrt() |
One-time initialization (DB setup, configs) | static { ... } |
Nested helper classes (independent of outer class) | static class Helper { ... } |
Key Differences: Static vs. Non-Static
Feature | Static | Non-Static (Instance) |
---|---|---|
Belongs to | Class | Object |
Memory allocation | Once (class level) | Per object |
Access | ClassName.member |
object.member |
Can access static members? | ✅ Yes | ✅ Yes |
Can access non-static members? | ❌ No | ✅ Yes |
Lifecycle | Until program ends | Until object is garbage collected |
Summary
-
static
means class-level (not instance-level). - Static variables → Shared across all objects.
- Static methods → Can be called without an object.
- Static block → Runs when class loads (for initialization).
- Static nested class → Does not need an outer class instance.
Final Example (Combining All Concepts)
class Company {
static String name = "TechCorp"; // Static variable
static { // Static block
System.out.println("Company registered: " + name);
}
static class Employee { // Static nested class
void display() {
System.out.println("Works at: " + name);
}
}
}
public class Main {
public static void main(String[] args) {
Company.Employee emp = new Company.Employee();
emp.display();
}
}
Output:
Company registered: TechCorp
Works at: TechCorp
Would you like a deeper dive into any specific static
concept? 😊
Static Block in Java
A static block (also called a static initialization block) is a block of code inside a Java class that runs when the class is loaded into memory (before the main()
method or any object creation). It is used to initialize static variables or perform one-time setup tasks for the class.
Key Features:
- Executes only once when the class is first loaded by the JVM.
-
Runs before
main()
or any instance creation. - Can have multiple static blocks (they execute in the order they appear).
- Cannot access non-static (instance) members (since no object exists yet).
Syntax
static {
// Code to be executed when the class loads
}
Why Use a Static Block?
- Initialize static variables (especially if computation is needed).
- Load native libraries (e.g.,
System.loadLibrary()
). - Perform one-time setup (e.g., database connection setup).
Example 1: Basic Static Block
class Test {
static int x;
// Static block runs when class loads
static {
x = 10;
System.out.println("Static block executed. x = " + x);
}
}
public class Main {
public static void main(String[] args) {
System.out.println("Main method starts.");
System.out.println("Test.x = " + Test.x); // x already initialized
}
}
Output:
Static block executed. x = 10
Main method starts.
Test.x = 10
- The static block runs before
main()
.
Example 2: Multiple Static Blocks
class Test {
static int a;
static int b;
static {
a = 5;
System.out.println("First static block: a = " + a);
}
static {
b = a * 2;
System.out.println("Second static block: b = " + b);
}
}
public class Main {
public static void main(String[] args) {
System.out.println("a = " + Test.a + ", b = " + Test.b);
}
}
Output:
First static block: a = 5
Second static block: b = 10
a = 5, b = 10
- Static blocks execute in the order they are defined.
Example 3: Static Block for Loading Libraries
class Database {
static {
System.out.println("Loading database driver...");
// Simulate loading a JDBC driver
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
static void connect() {
System.out.println("Connected to database.");
}
}
public class Main {
public static void main(String[] args) {
Database.connect(); // Static block runs first
}
}
Output:
Loading database driver...
Connected to database.
- The static block ensures the driver is loaded before any database operation.
When to Use Static Block?
Scenario | Example |
---|---|
Initialize static variables with complex logic | static { PI = 3.14159; } |
Load external libraries | System.loadLibrary("nativeLib"); |
One-time setup before any instance is created | Database driver setup |
Key Takeaways
- Runs only once when the class is loaded.
-
Executes before
main()
and instance creation. - Cannot access instance variables/methods (since no object exists).
- Useful for static initializations (e.g., constants, resources).
Would you like an example with static blocks in inheritance? Let me know! 🚀