Reputation: 99
if(true)
System.out.println("one");
System.out.println("two);
System.out.println("three);
First it seems weird but it works. My question is just for clarification: if I don't use code blocks anything after if will be affected; if I use codeblock just inside the codeblocks will be affected - am I right? or is there something that I dont know happening through this example?
Upvotes: 1
Views: 370
Reputation: 109079
The Java Language Specification for the if statement defines:
IfThenStatement:
if ( Expression ) Statement
Statement is further defined as:
Statement:
StatementWithoutTrailingSubstatement
<removed for brevity>
StatementWithoutTrailingSubstatement:
Block
<removed for brevity>
In other words: An if statement contains a Statement
, which can be a Block
(which is a list of statements between brackets).
Upvotes: 0
Reputation: 8322
In Java if can be written in two ways
if(true){
//statement 1
//statement 2
//statement 3
}
if you want to execute multiple lines, you have to use block. If you want to use single line you can use with out block.
if(true)
//statement 1
but one line statement also can be written in block, it will work same.
if(true){
//statment 1
}
works same as with out block
Upvotes: 1
Reputation: 23972
Your case is equivalent to:
if(true){
System.out.println("one");
}
System.out.println("two");
System.out.println("three");
and output will be
one
two
three
if
statement executes operator (in your case, it's only System.out.println("one")
, that follows behind it. Figure braces ({}
) is operator too. For example:
if(false)
System.out.println("one");
System.out.println("two");
System.out.println("three");
/*output will be:
two
three
*/
//and in this case there will be no output
if(false){
System.out.println("one");
System.out.println("two");
System.out.println("three");
}
Upvotes: 9
Reputation: 5080
In Java (and in similar languages), a single statement is equivalent to a block containing that single statement.
Upvotes: 0