Last chance! 50% off DataCamp Premium
Sale ends in
The native keyword in Java is used to declare a method that is implemented in native code using languages like C or C++. This keyword is part of the Java Native Interface (JNI), which allows Java code to interact with native applications and libraries.
The primary use of the native keyword is to enable Java applications to call functions written in other programming languages. This is particularly useful for performance-critical applications or when integrating with existing native libraries.
public native returnType methodName(parameters);
returnType: The return type of the native method.methodName: The name of the native method.parameters: The parameters that the method accepts.public class NativeExample {
// Declare a native method
public native void printHello();
// Load the library containing the native method implementation
static {
System.loadLibrary("NativeLib");
}
public static void main(String[] args) {
new NativeExample().printHello();
}
}
In this example, the printHello method is declared as native, indicating that its implementation is provided in a native library named NativeLib. The System.loadLibrary method loads this library.
#include <jni.h>
#include <stdio.h>
#include "NativeExample.h"
// Implement the native method
JNIEXPORT void JNICALL Java_NativeExample_printHello(JNIEnv *env, jobject obj) {
printf("Hello from C!\n");
}
This C code provides the implementation for the printHello method declared in the Java class NativeExample. The method prints a message to the console.
public class NativeMath {
// Declare a native method with parameters
public native int add(int a, int b);
// Load the library containing the native method implementation
static {
System.loadLibrary("NativeMathLib");
}
public static void main(String[] args) {
NativeMath nm = new NativeMath();
int result = nm.add(5, 3);
System.out.println("Result: " + result);
}
}
Here, the add method is declared as native and takes two int parameters. The native library NativeMathLib is loaded, and the method is called to add two integers.
// Example of calling a native method with proper error handling
try {
nativeMethod();
} catch (Exception e) {
System.err.println("Error calling native method: " + e.getMessage());
}