Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

native keyword in Java

  • Difficulty Level : Medium
  • Last Updated : 14 Sep, 2021

The native keyword is applied to a method to indicate 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 native methods or foreign methods.

The main objectives of the native keyword are: 

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

Illustration: Native keyword in Java  

// Class 1
// Helper class to illustrate native keyword 
class Native

        System.loadLibrary("Native library path");

    // Native method 
    public native void m();

// Main class 
class GFG
    public static void main(String[] args)
        // creating object of helper class inside main() 
        Native n = new Native();

        // Calling native method that is defined
        // inside  the above class

Do remember that there are certain important points about native keywords which are as follows:

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

Do go through strictfp keyword of java as is one of the concept which even very good java developer is unaware of.

In this section, we explain how to declare a native method in Java and how to generate the corresponding C/C++ function prototype.

Syntax: Declaring Native Methods

private native String getLine(String prompt);

Syntax: From the Native Language Side

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

This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to 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
Recommended Articles
Page :

Start Your Coding Journey Now!