Yes, native methods are methods whose implementation is written in a different language than Java. Following are the steps to use native methods.
Create a header file (.h file) for a C program.
Create C file
Create a DLL
In java code, declare the method as native, load the DLL using System.loadLibrary() method and call the method.
Consider the following example −
Tester.java
public class Tester
public class Tester { public native int getValue(int i); public static void main(String[] args) { System.loadLibrary("Tester"); System.out.println(new Tester().getValue(2)); } }
Tester.c
#include <jni.h> #include "Tester.h" JNIEXPORT jint JNICALL Java_Tester_getValue(JNIEnv *env, jobject obj, jint i) { return i * i; }
Compile and run
javac Tester.java javah -jni Tester gcc -shared -fpic -o libTester.so -I${JAVA_HOME}/include \ -I${JAVA_HOME}/include/linux Tester.c java -Djava.library.path =. Tester
4