Skip to main content Skip to docs navigation
TechSpiderTutorials

Java native Keyword:

In Java, the native keyword is used in method declarations to indicate that the method is implemented in native code using languages such as C or C++. This allows Java programs to interact with platform-specific functionalities or libraries that cannot be accessed through normal Java code.

Purpose of ‘native’ Keyword

The primary purpose of using the ‘native’ keyword in Java is to enable interaction with system-level resources, hardware, or existing non-Java code libraries. These could include device drivers, operating system functions, or performance-critical algorithms that are already implemented in languages other than Java.

Usage of ‘native’ Keyword

  1. Method Declaration: The ‘native’ keyword is used in method declarations to specify that the method's implementation is provided by native code.
  2. public native void nativeMethod();

    Here, nativeMethod is declared without a body, indicating that its implementation will be provided externally, typically in a native library.

  3. Integration with Native Code: To use a native method in Java, you must provide a corresponding implementation in a native language (e.g., C, C++) and load it into the Java runtime environment using mechanisms like Java Native Interface (JNI).
  4. Performance Optimization: native methods can be used to improve performance by leveraging optimized native code for specific tasks, especially those that require low-level access or complex computations.

Example

public class NativeExample {

// Declaration of native method
public native void sayHello();

// Load the native library that contains the implementation of nativeMethod
static {
    System.loadLibrary("NativeLibrary");
}

public static void main(String[] args) {
    NativeExample example = new NativeExample();
    example.sayHello(); // Call to native method
}
}