Java Development Essentials: Loops, Exception Handling, and API Documentation

The enhanced for-loop, also known as the "for-each" loop, provides a simplified syntax for iterating over arrays and collections. Unlike the traditional for-loop which requires manual management of an index counter, the enhanced version automatically iterates through each element.

Traditional vs. Enhanced Syntax

Consider an array of integers. The traditional approach requires initializing an index, checking the length, and incrementing the index:

int[] scores = {90, 85, 75, 95, 80};
for (int index = 0; index < scores.length; index++) {
    System.out.println("Score: " + scores[index]);
}

Using the enhanced for-loop, the syntax is more concise and readable:

int[] scores = {90, 85, 75, 95, 80};
for (int score : scores) {
    System.out.println("Score: " + score);
}

This construct is also highly effective when iterating over arrays of objects, allowing direct access to object attributes:

public void displayUsers(User[] userList) {
    for (User currentUser : userList) {
        System.out.println("Username: " + currentUser.getName() + ", Age: " + currentUser.getAge());
    }
}

Documenting APIs with Swagger

The @ApiOperation annotation is a key component of the Swagger (OpenAPI) specification, used to describe the behavior of a RESTful API endpoint. It helps ganerate documentation that is both human-readable and machine-processable. By applying this annotation to a controller method, developers can specify metadata such as the API's purpose, response types, and notes.

@ApiOperation(value = "Find user by ID", notes = "Returns a single user details based on the path variable ID")
@GetMapping("/users/{id}")
public ResponseEntity<User> getUserById(@PathVariable Long id) {
    // implementation logic
}

Exception Handling and Return Flow

Understanding the interaction between try, catch, finally blocks and return statements is critical for controlling program flow.

Execution Without Exceptions

If the code inside the try block executes successfully without throwing an exception, any return statement inside the try block is executed, and the method terminates immediately. The catch block is skipped entirely.

public int calculate() {
    try {
        processData();
        return 1; // Success path
    } catch (Exception e) {
        return 0; // Skipped
    }
}

Execution When Exceptions Occur

If an exception occurs within the try block, the control flow immediate transfers to the corresponding catch block. If the catch block contains a return statement, that value is returned.

public int calculate() {
    try {
        throw new RuntimeException("Calculation failed");
        // return 1; // Unreachable code
    } catch (Exception e) {
        return -1; // Exception path
    }
}

Multiple Catch Blocks

When multiple catch blocks are defined, the first block matching the exception type is executed. Subsequent catch blocks are ignored.

public int handleFile() {
    try {
        throw new IOException("File missing");
    } catch (IOException e) {
        return 1; // Handles IOException
    } catch (Exception e) {
        return 0; // Skipped because IOException was already caught
    }
}

The Finally Block Behavior

The finally block executes regardless of whether an exception occurred or a return statement was hit in the try or catch blocks. However, it is important to note that finally generally does not override the return value already determined by the try or catch block (unless the finally block explicitly returns a new value).

public int process() {
    int status;
    try {
        status = 100;
        return status; // Value 100 is staged for return
    } catch (Exception e) {
        status = 200;
        return status;
    } finally {
        System.out.println("Cleanup complete"); // This always prints
        // If we put a 'return' here, it would override previous returns.
        // Best practice is to avoid returning in finally.
    }
}

Dynamic SQL in MyBatis

MyBatis provides powerful dynamic SQL capabilities using tags like <if> and <foreach>. This allows for conditional SQL generation based on input parameters.

<select id="findProjects" resultType="Project">
    SELECT * FROM projects
    WHERE 1=1
    <if test="filter.typeList != null and filter.typeList.size() > 0">
        AND project_type IN
        <foreach collection="filter.typeList" item="type" open="(" close=")" separator=",">
            #{type}
        </foreach>
    </if>
</select>

In this example, the SQL clause is only appended if the typeList is not empty. The foreach tag iterates over the collection to generate an IN clause.

Data Transfer Architecture

Retrieving data from a database and delivering it to the frontend typically involves a layered architecture:

  • Controller Layer: Handles HTTP requests and responses.
  • Service Layer: Contains business logic and transaction management.
  • Mapper/DAO Layer: Interacts directly with the database via XML or annotations.
  • DTO/VO: Data Trensfer Objects or Value Objects used to shape the data sent to the client, decoupling the internal database model from the external API contract.

IDE Package View Settings

When navigating project structures in IDEs like IntelliJ IDEA, developers may notice that empty middle packages are often hidden (flattened). This is due to the "Compact Middle Packages" setting. To view the full hierarchical directory structure, disable this option in the project view settings (usually accessed via the gear icon in the Project tool window).

Tags: java swagger MyBatis Exception Handling For-Loop

Posted on Sun, 02 Aug 2026 16:31:38 +0000 by ace01