Now that we have taken a look at the code required in Java, let’s shift gears and take a look at how C++ is integrated into JNI. C++ is an enhanced language that continues to hold many of the same attributes as the C language. Therefore, it can easily be implemented into a cross-platform application with Java using JNI.

We have already seen how a .h file is generated by compiling the Java program. Now let’s see how to code the native method into a C++ function by extending our example from the previous exercise.

First, we must create a .cpp file and make sure to include the generated header file using the following code:

#include <jni.h> #include "FindSum.h"

Within the .h file, you will also find the definition of the native function which can be copied and pasted into your .cpp file. For our example it will look something like the following in your .h file:

JNIEXPORT jdouble JNICALL Java_FindSum_totalSum (JNIEnv *env, jobject thisObj, jdouble x, jdouble y) ;

Notice how when the Java compiler generated the .h file it added the prefix Java_FindSum_ to the function heading. There are also two additional parameters in the function heading. The first parameter, JNIEnv *env, points to the JVM and all the functions that are necessary to interact with it. The second parameter, jobject thisObj, points to the Java object that holds the method totalSum(). We will not be required to use these parameters for our simpler example. The next two parameters are of the type jdouble due to the mapping conventions for JNI. Take a look at the table below to see how other variable types may be mapped.

Java JNI Type Conversion
int jint
boolean jboolean
Void Void
char jchar
byte jbyte

When copied over to your .cpp file and completed, the function may look like the following:

JNIEXPORT jdouble JNICALL Java_FindSum_totalSum (JNIEnv *env, jobject thisObj, jdouble x, jdouble y) { double z = x * y; return z; }

Now that we have looked at how to implement the Java and C++ sides, let’s put it all together!



Now that we have seen an example of how to code the C++ implementation of a program that implements JNI, you will extend your work from the previous exercise to implement the C++ function for subtractValues(). The first step is to create a C++ file in the workspace that has the same name as the .h file we previously generated. This has already been done for you!


Import jni and the header file into your .cpp file.


Now copy and modify the function heading from the SubtractionFun.h file, and fill in the implementation. Make sure the jdouble parameters being passed in are labeled x and y. Inside the function, declare an int variable named difference. Subtract y from x and save the answer in difference.


Add a return statement to your function that returns difference.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?