In C/C++ there is a construct which allows you to conditionally compile code. Yes I am talking about the
#ifdef... #endif Java doesn’t have an equivalent. But you can use the following clever trick to achieve the same functionality.
Why conditionally compile code?
So before we proceed, you might ask me, why we need to do conditionally compiling? There are couple of reasons, but the main reason which motivated me to look for the solution is to conditionally enable debug statements. You can say that we can probably use a boolean variable or a function call, to determine whether we need to output the debug statement or not. But if the number of debug statements is high then they could add up.
Setting up final boolean variable
So the trick is simple. You have to create a if statement with a boolean private variable and if you make the boolean private variable as final and set the value to false, then at compile time, the compiler will be able to determine that these code branches are unreachable and will not include them as part of the compiled code.
The following sample code explains this trick.