Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How smart is Java about if statements with final variables

I'd like to write some troubleshooting code which i can easily remove from later non debug versions of my program. I came up with:

final static boolean debug_on=true;
...
if (debug_on) { system.out.println() or logger.log(...) }

Is Java smart enough to drop the if statement from the final bytecode if debug==false ?

Is there a better practice to achieve the goal of keeping debug code out of the final version of a program ?

like image 960
Rian McGesser Avatar asked Apr 09 '13 15:04

Rian McGesser


People also ask

Is it good to use final in Java?

In Java, there is a practice of declaring every variable (local or class), parameter final if they really are. Though this makes the code a lot more verbose, this helps in easy reading/grasping of the code and also prevents mistakes as the intention is clearly marked.

What happens when you do if var1 == var2?

If the two variables, var1 and var2 , are equal, the expression var1 == var2 is evaluated to true . Otherwise the expression is evaluated to false .

When should I use final in Java?

You use the final keyword in a method declaration to indicate that the method cannot be overridden by subclasses. The Object class does this—a number of its methods are final .

Can you nest if statements in Java?

Nested if condition comes under decision-making statement in Java. It contains several branches with an if condition inside another if condition. The syntax, code examples, and explanations of Nested-if statements are covered in detail in the above article.


1 Answers

See the end of the Java language specification chapter 14.21. Unreachable Statements for a description of if(false):

if (false) { x=3; }

does not result in a compile-time error. An optimizing compiler may realize that the statement x=3; will never be executed and may choose to omit the code for that statement from the generated class file, but the statement x=3; is not regarded as "unreachable" in the technical sense specified here.

The rationale for this differing treatment is to allow programmers to define "flag variables" such as:

static final boolean DEBUG = false;

and then write code such as:

if (DEBUG) { x=3; }

The idea is that it should be possible to change the value of DEBUG from false to true or from true to false and then compile the code correctly with no other changes to the program text.

tl;dr; It depends on the compiler whether the statements inside your if are omitted in the bytecode.

like image 89
halex Avatar answered Sep 21 '22 22:09

halex