Skip to content Skip to sidebar Skip to footer

How Exactly Does Jvm Compile Ternary Operators? Should I Be Concerned About Different Api Versions?

So, lets say I have this piece of code: int mode = android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB ? AudioManager.MODE_IN_COMMUNICATION : AudioManag

Solution 1:

A static final "variable" that is known at compile time is compiled into your code under certain circumstances. (e.g. every int where the compiler knows the final value)

So your code is actually just

int mode = android.os.Build.VERSION.SDK_INT >= 11 ? 3 : 2;

And any version can run that. It's not making any references to the constants that may or may not exist on the Android device.

The technical details can be found within the Java Language Specifiction e.g. §13.1

References to fields that are constant variables (§4.12.4) are resolved at compile time to the constant value that is denoted. No reference to such a field should be present in the code in a binary file

You can see from the documentation if something is such a constant value.

Build.VERSION.SDK_INT is itself a static final int but is not inlined at compile time. The documentation does not state a constant value

It is implemented as

publicstaticfinalint SDK_INT = SystemProperties.getInt("ro.build.version.sdk", 0);

and the compile can't figure out what SystemProperties.getInt will return so this value is the only one that actually references a value from within your device.

Solution 2:

The Java compiler literally replaces it with an if else block. I remember reading about this in a book during Programming Fundamentals I or II.

return isValid ? foo : bar;

literally precompiles to

if(isValid) {
    return foo;
} else {
    return bar;
}

which is then compiled as normal.

Post a Comment for "How Exactly Does Jvm Compile Ternary Operators? Should I Be Concerned About Different Api Versions?"