What is difference between a 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.

  • 1. Create a header file (.h file) for a C program.
  • 2. Create C file
  • 3. Create a DLL
  • 4. In java code, declare the method as native, load the DLL using System.loadLibrary() method and call the method.


Tester.java −

public class Tester {
   public native int getValue(int i);
   public static void main(String[] args) {
      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


Published on 07-Feb-2018 07:49:35