Consider this code sample.
This code just serves to explain my question.
boolean status = false;
for ( int i = 0; i <= 5; i++ ) {
if ( i == 4 ) {
System.out.println ( "Enter into first if" );
if ( status == false ) {
System.out.println ( "Enter into second if" );
status = true;
if ( status == true ) {
System.out.println ( "Enter into third if" );
//third if body
}
//second if body
}
//first if body
System.out.println ( "Before exiting first if" );
}
}
All I want to do is come out from third if to first if.
We know break, continue are there that can be used in loops. Can we achieve the same for the blocks?
Well, you can break to any block:
public class Bar {
static void foo(boolean b) {
foo: {
if (b) {
break foo;
}
System.out.println(b);
}
}
public static void main(String[] args) {
foo(true);
foo(false);
}
}
Output:
false
See the Java Language Specification for more.
However, if you tried to deliver this code in one of my projects we would probably have words.
Create a method that encapsulates if #2 and #3. Then return
from inside of the #3 if block:
boolean status = false;
for ( int i = 0; i <= 5; i++ ) {
if ( i == 4 ) {
System.out.println ( "Enter into first if" );
status = perform2ndAnd3rdIf(status);
System.out.println ( "Before exiting first if" );
}
}
private boolean perform2ndAnd3rdIf(boolean status) {
if ( status == false ) {
System.out.println ( "Enter into second if" );
status = true;
if ( status == true ) {
System.out.println ( "Enter into third if" );
return status;
//third if body
}
//second if body
}
return status;
}
Using a method instead of a nested if
block improves overall readability and the ability to understand your code. Instead of code comments, you should give that method a meaningful name (of course not ).perform2ndAnd3rdIf()
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