Fading Coder

An Old Coder’s Final Dance

You are here: Home > Tech > Content

Understanding Code Blocks in Java

Tech 3

Code blocks in Java are sections of code surrrounded by curly braces {}, used to group statements logically. Depending on their placement and how they are defined, they are categorized into four types: common blocks, instance blocks, static blocks, and synchronized blocks.

"1.1 Common Code Blocks" These are enclosed within a method and execute upon method invocation. They help structure logic within a method but are not frequently utilized.

public class Sample {
    public static void main(String[] args) {
        {
            int localVariable = 25; // Scoped within this block
            System.out.println("Value inside block: " + localVariable);
        }
        int localVariable = 50; // Separate declaration
        System.out.println("Value outside block: " + localVariable);
    }
}

Outputs:

Value inside block: 25
Value outside block: 50

"1.2 Instance Code Blocks" Also known as construction blocks, these reside within a class and are executed before constructors when an instance is created. They initialize instance variables.

class User {
    private String username;
    private int age;
    
    {
        username = "guest";
        age = 21;
        System.out.println("Initializing instance...");
    }

    public User() {
        System.out.println("Constructor executed.");
    }

    public void display() {
        System.out.println("Username: " + username + ", Age: " + age);
    }
}

public class Example {
    public static void main(String[] args) {
        User user = new User();
        user.display();
    }
}

Outputs:

Initializing instance...
Constructor executed.
Username: guest, Age: 21

"1.3 Static Code Blocks" These are defined with the static keyword inside a class and execute exactly once when the class is first loaded. Static blocks are primarily used to initialize static variables.

class Settings {
    private static int defaultTimeout;

    static {
        defaultTimeout = 30;
        System.out.println("Setting default timeout value...");
    }

    public static void showTimeout() {
        System.out.println("Default timeout: " + defaultTimeout);
    }
}

public class Example {
    public static void main(String[] args) {
        Settings.showTimeout();
    }
}

Outputs:

Setting default timeout value...
Default timeout: 30

Points to Note:

  1. Static blocks execute only once, regardless of the number of objects created.
  2. Static blocks run before instance blocks and constructors when a class is loaded.

"Static Block and Variable Initialization Order" If a static variable is modified both in the block and within the class directly, the order of execution determines the final value. Consider this:

class Config {
    private static int maxConnections;

    static {
        maxConnections = 100;
    }

    private static int maxConnections = 50;

    public static void showMaxConnections() {
        System.out.println(maxConnections);
    }
}

public class Example {
    public static void main(String[] args) {
        Config.showMaxConnections();
    }
}

If the class variable is reset after the static block, maxConnections will retain the value defined last (50). Conversely, if the static block appears after the variable, its assignment (100) will override.

Static variables can be accessed using a class reference directly, without requiring an instance. As a result, static blocks execute without involving instance-related code such as constructors and instance blocks.

Tags: Java

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.