Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I come out of if block?

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?

like image 375
Code Enthusiastic Avatar asked Sep 16 '25 07:09

Code Enthusiastic


2 Answers

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.

like image 81
McDowell Avatar answered Sep 17 '25 21:09

McDowell


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()).

like image 39
Moritz Petersen Avatar answered Sep 17 '25 20:09

Moritz Petersen