How exactly does JVM compile ternary operators? Should I be concerned about different api versions?

android, java

Solution

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_CODES.HONEYCOMB "Constant Value: 11"

- AudioManager.MODE_IN_COMMUNICATION "Constant Value: 3"

- AudioManager.MODE_IN_CALL "Constant Value: 2"

`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

- Build.VERSION.SDK_INT

It is implemented as

public static final int 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.

Problem

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 : AudioManager.MODE_IN_CALL; ``` Now, lets say I run this code on some device that is pre-gingerbread. Is there any case in which the non-available static import of `AudioManager.MODE_IN_COMMUNICATION` would be hit? What I mean is, is there any scenario in which I would see a crash due to the `MODE_IN_COMMUNICATION` which is not available pre gingerbread being checked? How does the ternary operator compile in Java? Does it compile these two things as ints? Does it expand the code during compilation?

Original source