Learn

Now that we’ve understood JNI’s purpose, let’s look at how to implement JNI into Java code.

Firstly, when creating a method that is meant to be used by JNI, you will need to use the keyword native when declaring the method. Take a look at the following example:

private native void totalSum();

Notice how there is no implementation of totalSum() that is provided - there is no code block of commands that will tell a program what to do if the method is called. This is because the implementation of the method will be written in the native language that is being used on the other end of the JNI.

You may define passing arguments and return values the same way as any other method definition. For example in the following method definition:

public int void totalSum(double num1, double num2);

The method will return an int; num1 and num2 are parameters that will be passed into the method.

Another important element needed in the Java code is the following method: System.loadLibrary(). This method call is used on the Java side, usually within the main method, to load the dynamic library that holds the native code.

To implement a native method in native code, we must compile our Java program, and generate a .h file. To do this, you will run the following command in your compiler:

javac -h . FindSum.java

Running the following command will output a name file that will look like this:

FindSum.h

Instructions

1.

For this exercise, we will begin filling in the skeleton for our first JNI project, SubtractionFun.

Create a private native method called subtractValues() that has two double parameters named num1 and num2 and an int return type.

2.

Call the function subtractValues() in the main method. The return int value should be saved in a new int variable named difference. Make sure to pass the two double variables that have already been defined for you.

3.

Next, compile your Java file to generate a .h file. This will be done by compiling and using the -h command in the terminal.

Sign up to start coding

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?