user12208242
user12208242

Reputation: 335

Why are braces not mandatory (as shown below)?

Now everyone speaks that if you wanna use multiple statements inside a control statement, it is mandatory to include them inside braces. However if you use like this:

if(condition) //first if statement
if(condition) //if statement nested inside the first
System.out.println("test"); //statement inside the second if statement

The code should result an error as the second if statement (without the semicolon) is inside the first one without the braces which completes the first if statement's limit. And hence the scope of the println statement should be out of the first if statement. Therefore the above code should be equivalent to

if(condition) {
    if(condition) 
}
System.out.println("test"); 

But it's not like that. The first code runs successfully. Why?

Upvotes: 0

Views: 62

Answers (2)

templatetypedef
templatetypedef

Reputation: 373442

You began your question with this statement:

Now everyone speaks that if you wanna use multiple statements inside a control statement, it is mandatory to include them inside braces.

That’s absolutely true. The nuance you’re encountering here is what it means for something to be a single statement as opposed to multiple statements.

As @rici noted, in most programming languages an if statement consists of both some sort of conditional expression and a guarded statement to execute if that condition is true. In that sense, an if statement has to have some statement inside of it to be syntactically correct.

So let’s look at your statement, but do it bottom-up. The statement

System.out.println("Test");

is treated as a single statement. Similarly,

if (condition)
System.out.println("Test");

is also a single conditional statement. However,

if (condition)

on its own is not a valid conditional statement; this would be a syntax error.

This means that

if (condition1)
if (condition2)
System.out.println("Test");

is a single conditional. Specifically, it’s a conditional whose condition is condition1. The statement is guards is also a conditional. That conditional has condition condition2 and guards the print statement.

Upvotes: 1

rici
rici

Reputation: 241931

Because a conditional statement includes the statement it qualifies.

Braces are not part of the syntax of the if statement. It's syntax is simply:

 "if" "(" <expression> ")" <statement>

Or

"if" "(" <expression> ")" <statement> "else" <statement>

One type of statement is the block statement, whose syntax is:

"{" <statement>... "}"

Where <statement>... means "zero or more <statement>s".

The block statement can include an if-statement (or any other kind of statement). But it can't chop a statement in half. And if (condition) is only half of a statement.

Upvotes: 4

Related Questions