What does if(false){some code} mean in java

It is never executed. Sometimes people do it when they have some old code they want to remember, or some new code that should not yet be used. like

if(false){fancyNewFunction();}

(as far as i'm concerned, this is bad form and you should not do it, but that doesn't mean it doesn't happen ;) )


This could also be a common way to emulate macro preprocessor directives like #ifdefine. Some people use it to enable or disable logging.

For instance the following code:

public class Sample{

    private static final boolean LOG_ENABLED = true;

    public static void main(String args[]){
        if(LOG_ENABLED){
            System.out.println("Hello World");
        }
    }
}

Produces the following bytecodes:

public class Sample extends java.lang.Object{
public Sample();
  Code:
   0:   aload_0
   1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
   4:   return

public static void main(java.lang.String[]);
  Code:
   0:   getstatic   #2; //Field java/lang/System.out:Ljava/io/PrintStream;
   3:   ldc #3; //String Hello World
   5:   invokevirtual   #4; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
   8:   return

}

If you disable the flag, you get this bytecodes:

public class Sample extends java.lang.Object{
public Sample();
  Code:
   0:   aload_0
   1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
   4:   return

public static void main(java.lang.String[]);
  Code:
   0:   return

}

As you can see, no bytecodes were generated for the second case in the main method. So, if you disable logging and recompile the code, you improve underlying bytecodes.


I use

if (false)
{
   doSomething();
}

on occasion to prevent execution of doSomething().

It may be better/clearer to do this:

final static private boolean ENABLE_WOLZOPPERY = false;

if (ENABLE_WOLZOPPERY)
{
   wolzopp1();
}
blah_blah_blah();
if (ENABLE_WOLZOPPERY)
{
   wolzopp2();
}

so that a single constant can enable/disable the behavior of more than one block in a named fashion.