| Java Native Interface Programming

## Mapping between Java and Native Types

> In this section, you will learn how to reference Java types in your native method. This is useful when you want to access the arguments passed in from Java, create new Java objects, and return results to the caller.

> #### Java Primitive Types

> Your native method can directly access Java primitive types such as booleans, integers, floats, and so on, that are passed from Java programs. For example, the Java type boolean maps to the native type `jboolean` (represented as unsigned 8 bits), while the Java type float maps to the native type `jfloat` (represented by 32 bits). The following table describes the mapping of Java primitive types to native types.

> ##### Java Primitive Types and Native Equivalents

> Java Type | Native Type | Size in bits
> | boolean | jboolean | 8, unsigned | byte | jbyte | 8 | char | jchar | 16, unsigned | short | jshort | 16 | int | jint | 32 | long | jlong | 64 | float | jfloat | 32 | double | jdouble | 64 | void | void | n/a

> #### Java Object Types

> Java objects are passed by reference. All references to Java objects have type `jobject`. For convenience and to reduce the chance of programming errors, we introduce a set of types that are conceptually all "subtypes" of `jobject`:

> - `jobject` represents all Java objects.
> - `jclass` represents Java class objects (java.lang.Class).
> - `jstring` represents Java strings (java.lang.String).
> - `jarray` represents Java arrays.
> - `jobjectArray` represents arrays of objects.
> - `jbooleanArray` represents boolean arrays.
> - `jbyteArray` represents byte arrays.
> - `jcharArray` represents char arrays.
> - `jshortArray` represents short arrays.
> - `jintArray` represents int arrays.
> - `jlongArray` represents long arrays.
> - `jfloatArray` represents float arrays.
> - `jdoubleArray` represents double arrays.
> - `jthrowable` represents Java exceptions (java.lang.Throwable).

> In our `Prompt.java` example, the native method `getLine`:

> >     private native String getLine(String prompt);

> takes a Java string as an argument and returns a Java string. Its corresponding native implementation has type:

> >     JNIEXPORT jstring JNICALL
> >     Java_Prompt_getLine(JNIEnv *, jobject, jstring);

> As mentioned above, `jstring` corresponds to Java type `String`. The second argument, which is the reference to the object itself, has type `jobject`.

| Java Native Interface Programming