Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Java code

if(x == null){
 //some code
}
if(false){
 //some code
}

when is if(false){code} executed?

like image 953
Ballon Avatar asked Apr 20 '11 12:04

Ballon


People also ask

What is the meaning of if (! In Java?

if (b) means "if b is true". if (! b) means "if b is false".

Does if false run?

if (false) will never execute its body... because the value of the condition is never true.

Can we use Elif in Java?

Java does not have an elif pattern like Python.

What will happen if the first condition fails in an Boolean expression with and operator?

No, if the first condition returns false then the whole expression automatically returns false. Java will not bother examining the other condition.


2 Answers

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 ;) )

like image 75
Nanne Avatar answered Nov 08 '22 21:11

Nanne


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.

like image 26
Edwin Dalorzo Avatar answered Nov 08 '22 20:11

Edwin Dalorzo