What is the difference between java method and native method?

Java 8Object Oriented ProgrammingProgramming

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.

Example

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

Output

4
raja
Published on 23-Apr-2018 15:42:17
Advertisements