Low Orbit Flux Logo 2 D

Java How To Break Out Of If Statement

Apparently there are people out there asking how to break out of an if statement in Java. It is possible to do this and we are going to show you how.

Just because you can doesn’t mean that you should.

Before we show you how to do this it is worth mentioning that you are not really meant to break out of an if statement. You are really only meant to break out of a loop or a case statement. Really if you want this type of functionality you should probably be using a case statement instead of an if statement.

The Workaround

Normally you will receive a compile time error if you try to use a break statement inside an if statement. One way to get around this is to put the if statement inside a loop. Using the break statement will then actually be breaking you out of the loop. So long as the loop doesn’t actually do anything ( single iteration with no logic ) you will be able to achieve the same behavior as if you were allowed to just break out of an if statement.

Also note that there is a second if statement. Without this statement the compiler will complain that the second print statement is never reachable. This statement is always true and is only intended to trick the compiler into building our code for us anyway. In a real life situation this would probably be based on some type of logic. Of course in a real life situation you wouldn’t be trying to do this in the first place right?

Here is an example showing you how to do this.

class Test1 {
    public static void main( String args[] ) {
        boolean c = true;          // true by default
        while ( c == true ) {       // only loop while true
            c = false;                  // kill loop on first iteration
            int x = 5;                   // variable for first if                
            if( x == 5 ){               // if statement to break out of
                System.out.println("1");    // only print this
                if(true)                              // extra if so that it will compile
                    break;                          // break statement
                System.out.println("2");   // don't print this