In Java, the native keyword is used to declare a method which is implemented in platform-dependent code such as C or C++. When a method is marked as native, it cannot have a body and must ends with a semicolon instead. The Java Native Interface (JNI) specification governs rules and guidelines for implementing native methods, such as data type conversion between Java and the native application.

The following example shows a class with a method declared as native:

public class NativeExample {

	public native void fastCopyFile(String sourceFile, String destFile);

}

See all keywords in Java.

 

 

Other Recommended Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.



Add comment

   


Comments 

#8deppwang2020-04-28 06:39
env:jdk8、macOS 10.15

Compile and run:

javac Main.java -h .
gcc -dynamiclib -O3 \
-I/usr/include \
-I$JAVA_HOME/include \
-I$JAVA_HOME/include/darwin \
Main.c -o libMain.dylib
java -cp . -Djava.library.path=$(pwd) Main

Output:
4
Quote
#7Lavern2016-12-11 04:12
Very well written article. It will be useful to anybody who utilizes it,
as well as yours truly :). Keep doing what you are
doing - looking forward to more posts.
Quote
#6Steve2016-07-14 17:25
I have yet to come across a single sample that shows anyone what to import to use the native keyword.
Quote
#5Shailendra Katolkar2015-10-07 12:24
yes i am interested , i want to be expert in java programming.
Quote
#4Manoj2015-10-04 11:24
Minimal example to make things clearer:

Main.java:

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));
}
}
Main.c:

#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
Quote