If and If-Else Statements in Java - Quiz

Total: 5 questions

1. 

What is the difference between the = and == operators in Java?

The = operator is assignment: it changes the value of a variable. The == operator is comparison: it tests whether two values are equal without changing anything. In an if condition you must use == (or another comparison operator), never =.

2. 

Are curly braces mandatory in an if statement in Java?

No. If the branch contains exactly one statement, the braces may be omitted and the code compiles. However, Oracle's code conventions recommend always using braces, because adding a second line to a braceless branch — which then silently falls outside the if — is a classic source of bugs.

3. 

How does an if-else-if ladder work in Java?

An if-else-if ladder tests conditions from top to bottom. As soon as one condition is true, its block executes and the rest of the ladder is skipped. If none of the conditions are true and there is a final else block, that block runs instead.

4. 

Is the if statement a type of loop in Java?

No. The if statement is a conditional (decision-making) statement: its block executes at most once, depending on whether the condition is true or false. Loops — for, while, do-while — repeat a block multiple times. An if never repeats anything.

5. 

When should you use an if-else-if ladder instead of a switch statement?

Use an if-else-if ladder when you need to test any boolean conditions, such as ranges (x > 10) or method calls (s.isEmpty()). Use a switch when you have one value to compare against multiple constant labels for equality — it is usually cleaner and easier to read in that case.

Page 1 of 1