Skip to content

Booleans

Eugene Gershnik edited this page Oct 9, 2021 · 3 revisions

One of the common mistakes when dealing with Java boolean type in JNI is to assume that they are equivalent to C++ bool values: true or false or simply 1 and 0. This is not necessarily correct. Depending on JVM you are using Java true can be represented as some other non 0 value instead of 1. One possibility that is known to exist is -1.

Raw JNI provides manifest constants JNI_TRUE and JNI_FALSE that contain the actual values. The problem with using those in C++ is that they are simple macros (1 and 0 for example) and so have a type int. Whereas jboolean is usually something smaller like unsigned char.

This usually isn't a big deal but can result in annoying compiler warnings. To deal with that SimpleJNI provides typed C++ constants:

constexpr jboolean java_true = JNI_TRUE;
constexpr jboolean java_false = JNI_FALSE;

Here is how to correctly deal with boolean arguments and results using them

jboolean SomeMethod(JNIEnv * env, jobject object, jboolean value)
{
    bool cpp_value = (value != jni_false); 
    return cpp_value ? jni_true : jni_false;
}

Note that most compilers are smart enough to eliminate the conditional entirely when jni_true is 1 and jni_false is 0.