1. Introduction
In Java, both static blocks and static methods are associated with a class rather than with instances of the class. A static block, also known as a static initialization block, is a group of statements that gets executed when the class is loaded into memory. A static method, on the other hand, is a method that belongs to the class and not to any individual object. Static methods can be called without creating an instance of the class.
2. Key Points
1. Static blocks are executed automatically when the class is loaded and cannot be called directly.
2. Static methods must be called explicitly using the class name and can be called any time after the class is loaded.
3. Static blocks are typically used for initializing static variables.
4. Static methods can have return types and can accept arguments, allowing more flexibility in their use.
3. Differences
Static Block | Static Method |
---|---|
Executed automatically when the class is loaded. | Can be called explicitly using the class name. |
Cannot accept arguments or return values. | Can accept arguments and return values. |
Ideal for initializing static variables. | Can be used for any static purpose, including utility or helper methods. |
4. Example
public class StaticExample {
static int num;
static String myStr;
// Static block
static {
num = 97;
myStr = "Block";
System.out.println("Static Block initialized.");
}
// Static method
static void myStaticMethod() {
System.out.println("Static Method invoked.");
num = 123;
myStr = "Method";
}
public static void main(String args[]) {
System.out.println("Main method invoked.");
System.out.println("Value of num: " + num);
System.out.println("Value of myStr: " + myStr);
// Static method call
StaticExample.myStaticMethod();
System.out.println("Value of num after calling myStaticMethod: " + num);
System.out.println("Value of myStr after calling myStaticMethod: " + myStr);
}
}
Output:
Static Block initialized. Main method invoked. Value of num: 97 Value of myStr: Block Static Method invoked. Value of num after calling myStaticMethod: 123 Value of myStr after calling myStaticMethod: Method
Explanation:
1. The static block initializes num and myStr when StaticExample class is loaded.
2. The main method is called and it prints the values of num and myStr initialized by the static block.
3. The myStaticMethod is explicitly called in the main method, which updates the values of num and myStr and prints them out.
5. When to use?
- Use static blocks when you need to initialize static variables when the class is loaded.
- Use static methods when you need to perform operations that do not require data from an instance of the class.
Comments
Post a Comment
Leave Comment