public class StaticDemo {
// Static variable
static int staticCounter = 0;
// Instance variable
int instanceCounter = 0;
// Static block
static {
System.out.println(“Static block executed”);
// Initialize static variable
staticCounter = 10;
}
// Instance block
{
System.out.println(“Instance block executed”);
// Initialize instance variable
instanceCounter = 5;
}
// Static method
static void staticMethod() {
System.out.println(“Static method called”);
System.out.println(“Static counter: ” + staticCounter);
// Instance method and variables cannot be accessed directly
// System.out.println(“Instance counter: ” + instanceCounter); // This would be an error
}
// Instance method
void instanceMethod() {
System.out.println(“Instance method called”);
System.out.println(“Instance counter: ” + instanceCounter);
// Static methods and variables can be accessed directly
System.out.println(“Static counter: ” + staticCounter);
}
public static void main(String[] args) {
// Accessing static method and variable without creating an instance
StaticDemo.staticMethod();
// Creating instance of StaticDemo
StaticDemo obj1 = new StaticDemo();
StaticDemo obj2 = new StaticDemo();
// Accessing instance methods and variables
obj1.instanceMethod();
// Static variable and method are shared across all instances
System.out.println(“Static counter from obj1: ” + obj1.staticCounter);
System.out.println(“Static counter from obj2: ” + obj2.staticCounter);
// Modifying static variable
obj1.staticCounter = 20;
// Static variable is updated for all instances
System.out.println(“Static counter from obj1 after modification: ” + obj1.staticCounter);
System.out.println(“Static counter from obj2 after modification: ” + obj2.staticCounter);
}
}
Leave a Reply