user3007165
user3007165

Reputation: 479

What's Java standard for single line if statement?

Which of the below format is JAVA standard for a single line IF-Statement? Please provide me the JAVA reference as well to support the argument. Thanks.

Syntax-01:

if (counter == 10) response.redirect("www.google.com");

Syntax-02:

if (counter == 10) {
    response.redirect("www.google.com");
}

Upvotes: 4

Views: 2689

Answers (2)

Kris Scheibe
Kris Scheibe

Reputation: 361

As per the Java Code Conventions (http://www.oracle.com/technetwork/java/codeconventions-150003.pdf, Chapter 7.4):

if statements always use braces {}. Avoid the following error-prone form:

if (condition) //AVOID! THIS OMITS THE BRACES {}!
    statement;

Upvotes: 6

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85779

From the old Java Code Conventions, it is the second.

Exact piece of the document: 7. Statements. 7.4 if, if-else, if-else-if-else Statements (page 12):

The if-else class of statements should have the following form

if (condition) {
    statements;
}

if (condition) {
    statements;
} else {
    statements;
}

if (condition) {
    statements;
} else if (condition) {
    statements;
} else if (condition) {
    statements;
}

Note: if statements always use braces {}. Avoid the following error-prone form:

if (condition) //AVOID! THIS OMITS THE BRACES {}!
    statement;

After that and since the Java Code Conventions are really old (since 1997), this falls into a personal matter/taste due to code readability. IMO the second is just fine.

Upvotes: 9

Related Questions