native keyword in java

The native keyword is applied to a method to indicates that the method is implemented in native code using JNI (Java Native Interface). native is a modifier applicable only for methods and we can’t apply it anywhere else. The methods which are implemented in C, C++ are called as native methods or foreign methods.

The main objective of native keyword are:

  • To improve performance of the system.
  • To achieve machine level/memory level communication.
  • To use already existing legacy non-java code.

Pseudo code to use native keyword in java:



filter_none

edit
close

play_arrow

link
brightness_4
code

Class Native
{
    Static
    {
        System.LoadLibrary(“Native library path”);
    }
    Public native void m();
}
Class Test
{
    Public static void main(String[] args)
    {
        Native n = new Native();
        n.m();
    }
}

chevron_right


Important points about native keyword:

  • For native methods implementation is already available in old languages like C, C++ and we are not responsible to provide implementation. Hence native method declaration should ends with ;( semi-colon).
  • We can’t declare native method as abstract.
  • We can’t declare native method as strictfp because there is no guarantee that old languages (C, C++) follow IEEE 754 standard. Hence native strictfp combination is illegal combination for methods.
  • The main advantage of native keyword is performance will be improved but the main disadvantage of native keyword is it breaks platform independent nature of java.

Declaring Native Methods: In this section we explain that how to declare a native method in Java and how to generate the corresponding C/C++ function prototype.

private native String getLine(String prompt);

From the Native Language Side:

javah -jni Prompt
JNIEXPORT jstring JNICALL Java_Prompt_getLine(JNIEnv *, jobject, jstring);

Reference:http://www.codejava.net/java-core/the-java-language/native-keyword

This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



My Personal Notes arrow_drop_up


Article Tags :
Practice Tags :


5


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.