Java code
if(x == null){
//some code
}
if(false){
//some code
}
when is if(false){code}
executed?
if (b) means "if b is true". if (! b) means "if b is false".
if (false) will never execute its body... because the value of the condition is never true.
Java does not have an elif pattern like Python.
No, if the first condition returns false then the whole expression automatically returns false. Java will not bother examining the other condition.
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.
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