Here we have a long-standing assumption that needs to be cleared up in my head. Is the following an example of nesting 'if' statements:
if (...)
...;
else if (...)
...;
I was under the impression that nesting required an 'if' inside another 'if', like so:
if (...)
if (...)
...;
or at least a clear separation of scope when you nest inside an else, like so:
if (...)
...;
else { //if the next statement didn't
//exist, then the curly brace changes nothing?
...;
if (...)
...;
}
This might boil down to how the compiler interprets things, whether the 'if' in else-ifs are considered in the same level as the parent if, or whether they create "new" 'if' statements. Thank you for your time!
edit: I ask because I am a TA in a java lab, and the topic of the day was nested-ifs. In the end, I found out that the teacher considered my first example to be valid for "nested if statements".
Of course it's nested. Nesting has nothing to do with the way you format the code.
if (...)
{
// some code
}
else if (...)
{
// some code
}
else
{
// some code
}
is exactly equivalent to
if (...)
{
// some code
}
else
{
if (...)
{
// some code
}
else
{
// some code
}
}
There's no 'else if' keyword in Java, the effect is achieved purely by a formatting convention which stops long chains of nested elses from drifting right across the screen.
In case anybody needs persuading, here is the specification for an if statement: Java Language Specification section 14.9
This is an if statement:
if (condition1) {
// ...
}
This is a nested if statement:
if (condition1) {
// ...
if (condition2) {
// ...
}
// ...
}
This is an if-else statement:
if (condition1) {
// ...
} else {
// ...
}
This is a chained if-else statement:
if (condition1) {
// ...
} else if (condition2) {
// ...
}
A nested if is like this:
if (...)
if (...)
...;
The first example you gave is just if/else
.
A good way to remember it is that the indentation increases with a nested if
, but with if/else
it doesn't.
Conceptually, for me the first form
if (cond1)
{
}
else if (cond2)
{
}
else
{
}
is not nested because all conditions are evaluated at the same logical level. In other words, I read this as "branch your action based on cond1:cond2:anything else".
if (cond1){
if (cond2){
if (cond3){
Is nested because you have conditions evaluated within other conditions , that is, dependent on previous conditions. If you want to be literal about it, the scope of cond2 in the second case is literally nested in the scope of cond1. This is not true in the first form.
I never thought this was controversial.
edit: if you've ever had to read code like this the difference might seem less academic.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With