Home / Programs / static block in java
🚀 Programming Example

static block in java

👁 1,159 Views
💻 Practical Program
📘 Step Learning
Learn this program step-by-step with algorithm, source code, output and detailed explanation.

💻 Program Code

 class StaticBlock{

  static{
	  System.out.println("i am inside of static block ");
	  }

  public static void main(String args[]){
   System.out.println("Hello in main");
  }
}

                        

🖥 Program Output

i am inside of static block
Hello in main
Press any key to continue . . .
                            

📘 Explanation

Why Use Static Blocks?

Static blocks are useful for initializing static variables or performing setup tasks that are required once per class loading. For example, you might use a static block to establish a database connection or to load a configuration file.

In this specific example, the static block is used simply to demonstrate that it executes before the main method.

Explanation

  1. Class Definition:

    • class StaticBlock defines a class named StaticBlock.
  2. Static Block:

    • The static block is a block of code that gets executed when the class is first loaded into the JVM (Java Virtual Machine). It runs only once, before the main method or any other methods in the class.
    • static { System.out.println("I am inside of static block"); } is the static block in this class. It contains a single statement that prints a message to the console.
  3. Main Method:

    • public static void main(String args[]) { System.out.println("Hello in main"); } is the main method, which serves as the entry point of the program. It prints "Hello in main" to the console.
📚 Learning Subject

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.

🔥 Practice suggestion

Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.