Videos
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) {
// ...
}
Hi there,
I'm trying to improve my programming style and practices, and was wondering which of the two images would be considered best practice? It feels wrong breaking out nested if statements, but in this case it does make it a little more readable. Should deeply nested if statements be avoided? Thanks!
Image 1
Image 2