JNI(Java Native Interface) is a very important aspect of Java programming language. JNI provides an interface to the native environment. So we can execute native methods within our Java programs. Lets assume that we have to do a task that need high performance in our Java program. C/C++ is good for high performance tasks rather than Java. If we can cooperate or embed C/C++ with our Java code, we can achieve our high performance targets. But Java is interpreted(byte code based) and C/C++ is compiled. So JNI is the way to cooperate those native code with our Java code.
Lets assume we have calculate factorial of a given integer value. calculation is done by a code written in C++. We call the C++ native method within our Java program and show the result on the console.
Step 1 : write Java code
OurProgram.java
This Java program contains the main method
1 public class OurProgram{
2 public static void main(String args[]){
3 try{
4 System.loadLibrary("myfactorialdll");
5 JNICallerInt jnic=new JNICallerInt();
6
7 for(int i=1;i<15;i++){
8 int factorial=jnic.factorial(i);
9 System.out.println("Factorial of " + i + " is \t : " + factorial);
10 }
11
12 }catch(UnsatisfiedLinkError e){
13 System.out.println("Unsatisfied link to the dll");
14 }
15 }
16 }
JNICallerInt.java
create a interface to the C++ method
1 class JNICallerInt{
2 public native int factorial(int value);
3 }