native keyword in java

The " native " keyword can be applied to a method to indicate that the method is implemented in a language other then Java such as C or C++.

When a method is marked as native, it can not have a body and should end with a semicolon.

The Java Native Interface is responsible for writing Java native methods and embedding the JavaTM virtual machine into native applications.

Example

1
2
3
4
5
public class JavaNativeExample {
 
    public native int add(int num1,int num2);
 
}
public class JavaNativeExample {
 
    public native int add(int num1,int num2);
 
}


Now add(int num1,int num2) method is defined in native language other than Java either in C or C++ but it can be called in Java code using the object of above class as below

1
2
JavaNativeExample nativeEx = new JavaNativeExample();
int res = nativeEx.add(10,20);
JavaNativeExample nativeEx = new JavaNativeExample();
int res = nativeEx.add(10,20);


Native methods are usually used to interface with system calls or libraries written in other programming languages.

Please look at the below link for more details on JNI

http://docs.oracle.com/javase/7/docs/technotes/guides/jni/

About the Author

Karibasappa G C (KB)
Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on