# Insert Break Statements in For-loops

# Description

Finds the Enhanced For-loops whose sole purpose is to compute a boolean value without causing side effects and inserts a break statement immediately after the boolean value is computed. Thus, eliminating redundant loop iterations.

# Benefits

Improves performance by eliminating redundant cycles in Enhanced For-loops.

# Tags

# Code Changes

# Searching for a fixed value

Pre

    boolean found = false;
    for(String value : values) {
        if(value.equals("John")) {
            found = true;
        }
    }

Post

		boolean found = false;
		for(String value : values) {
			if(value.equals("John")) {
				found = true;
                break;
			}
		}

# Matching a value in another Collection

Pre

    boolean found = false;
    for(String value : values) {
        if(collection.contains(value)) {
            found = true;
        }
    }

Post

    boolean found = false;
    for(String value : values) {
        if(collection.contains(value)) {
            found = true;
            break;
        }
    }

# Wrapping body into a code block

Pre

    boolean empty = false;
    for(String value : values)
        if(value.isEmpty()) 
            empty = true;

Post

    boolean empty = false;
    for(String value : values)
        if(value.isEmpty()) {
            empty = true;
            break;
        }

# Limitations

This rule cannot be applied if the method invocations occurring in the if condition might cause side effects in the program execution.

Pre

    boolean found = false;
    for(String value : values) {
        if(consumeValue(value)) {
            found = true;
        }
    }

🛠️ Auto-refactor Available

You can auto-refactor this with jSparrow.
Drop this button to your Eclipse IDE workspace to install jSparrow for free:

Drag to your running Eclipse* workspace. *Requires Eclipse Marketplace Client

Need help? Check out our installation guide.

# Properties

Property Value
Rule ID InsertBreakStatementInLoops
First seen in jSparrow version 3.9.0
Minimum Java version 5
Remediation cost 2 min