0

Basically I'm quite new to Java and just been given some code which reads:

if (n > 1)
    l--;
m = l;

Although I'm wondering whether this would be equivalent to either one of these, and if so which and why?

#1

if (n > 1) {
    l--;
    m = l;
}

OR

#2

if (n > 1) {
    l--;
}
m = l;
1
  • 2
    The second, because if statements either take a single statement or a block of statements enclosed by { and }. Commented Mar 19, 2012 at 0:18

4 Answers 4

3

It's equivalent to the second one. The if statement executes the next statement if its expression evaluates to true. It doesn't matter to the compiler if the next statement is a single statement (as it is in your original code sample) or a block (as it is in your second revision).

Sign up to request clarification or add additional context in comments.

Comments

2

It's the same as the second block of code.

When you don't see braces following a "grouping" statement (the if statement, in your example), it means that only the next line falls within the scope of that grouping statement.

Going beyond what the question asks, languages such as Java, C/C++, and C# use braces to declare blocks of code, whereas languages such as Python use whitespace. You can think of line of code is a block by itself. Blocks can be incrementally built by combining more blocks. This is done by grouping blocks; in Java, this is done through curly braces. When the if statement is evaluated (or a for loop, or a while loop, etc), the next outermost block falls under that statement.

Comments

0

the 2nd option.

If there's no { }, only the following statement is part of the If case

Comments

0

Obviously #2, because a if statement only takes the first expression after it into account. That is why it is always important to use brackets around your statements, both for clarity and fewer bugs. There is nothing more frustrating than spending hours wondering why code doesn't work because you forgot to add a bracket somewhere

1 Comment

Meh, I still don't get why you Java programmers always have these problems with one-line ifs... Maybe if you'd use them more often, you wouldn't be so confused about it (:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.