01. What is the Non-Static block?
The non-static block will be executed every time an object of the class is created, before the constructor is called as non static block.
02. How to use the non-static block?
-Non-static blocks are not marked by any keyword.
-simply appear as { /* code */ } inside the class.
-Each time an instance (object) of the class is created, the non-static block executes, allowing for instance-level logic.
Example:
public class Example {
{ // Non-static block
System.out.println("Non-static block executed.");
}
public Example() {
System.out.println("Constructor executed.");
}
}
Output
// Non-static block executed.
// Constructor executed.
Workflow:
*1. Static block: *
-The class is loaded, and static blocks execute (only once per class).
-Static is a class.
-Static blocks are written using static { ... } inside the class body.
2. Non-static block:
An object is created. Non-static blocks execute in sequence.
*3. Constructor: *
-The constructor executes after non-static blocks.
-The constructor name must match the class name.
-It has no return type.
-It is called automatically during object creation.
-It initialises the object's state
4. Instance block:
-It runs automatically whenever an instance (object) of the class is created.
-It executes before the constructor code.
-It is used for code or logic common to all constructors to avoid duplication.
-It cannot accept parameters (unlike constructors).
5. Main method:
Executed after class loading and static block execution.
Top comments (0)