Native Modifier

Native Modifier

                                                        Native 

native is a modifier applicable only for methods and we can't apply it anywhere else. the method which is implemented in non-java (mostly C or C++) are called native methods are foreign methods.

The main objective of the native keyword are-:

  • to improve the performance of the system
  • to achieve machine-level or memory-level communication.
  • to use already existing legacy non-java code.
pseudo-code for use to native keyword in java-:
  • load native library.
  • declare native method.
  • invoke native method.
eg-:
class Test{
    static {
          System.loadlibrary("native library path");
    }
    public native void m();
}
class Client{
   public static void main(String[] args){
     Test t=new Test();
      t.m();
   }
}


for native methods, implementation is already available in old languages like C or C++ and we are not responsible to provide implementation hence native method declaration should end with a semi-colon.

eg-:
public native void m(); //valid
public native void m(){}//invalid

for native method implementation is already available in old languages but for abstract methods, the implementation should not be available hence we can't declare the native method as an abstract that is native abstract combination is an illegal combination for methods.

we can't declare it as strictfp because there is no guarantee that old languages follow IEEE 754 standards hence native strictfp combination is an illegal combination for methods.

Advantage-:
the main advantage of native keywords is performance will be improved.

Disadvantage-:
the main disadvantage of native keyword is it breaks the platform's independent nature in Java.


When the Java native method setTheString(), defined in the Java code, is called by the Java code the C function Java_NativeHello_setTheString() gets control and uses Java Native Interface (JNI) to call back into the Java code to set the value of the Java string variable theString. Control is then returned to the Java code, and the string variable is written to stdout out by the Java code.

eg-:

public class Main {
public native int intMethod(int i);
public static void main(String[] args) {
System.loadLibrary("Main");
System.out.println(new Main().intMethod(2));
}
}
#include
#include "Main.h"
JNIEXPORT jint JNICALL Java_Main_intMethod(
JNIEnv *env, jobject obj, jint i) {
return i * i;
}

Compile and run:

javac Main.java
javah -jni Main
gcc -shared -fpic -o libMain.so -I${JAVA_HOME}/include \
-I${JAVA_HOME}/include/linux Main.c
java -Djava.library.path=. Main
Output: 4