tags:

views:

91

answers:

3

Give a whole implementation in Java with examples and requirements for native methods

+5  A: 

The native keyword is used for methods that are implemented in libraries, rather than in Java itself. Typically you use System.load or System.loadLibrary to load a library into the JVM, and then declare native methods that match functions in those libraries so you can call those functions from Java


A common way if you're implementing your own native functions is to use the Java Native Interface (JNI). You declare a native function:

public class Foo {
    public static native int addOne(int n);
}

And then you declare a corresponding function in another language like C:

JNIEXPORT jint JNICALL Java_Foo_addOne(JNIEnv*, jclass, jint n) {
    return n+1;
}

You build a shared library containing that function, and load it with System.load[Library], and then when you call Foo.addOne it calls the native Java_Foo_addOne

Michael Mrozek
+1  A: 

Native is a Java keyword that is used in method declarations to specify that the method will not be implemented in another language, not in Java. This keyword signals to the Java compiler that the function is a native language function i.e. its implementation for is written in another programming language because of the native keyword. For example you can write machine-dependent C code and invoke it from Java.

check this link for more details - http://www.roseindia.net/help/java/n/java-native.shtml

Sachin Shanbhag
A: 

native key word prefixed to method says that this method is implemented in native C language.Java generally provided this facility to perform some operation faster,but it always a problem if you are developing the portable code.For examples i would recommend google for JNI example,you will get lots of articles.

Anil Vishnoi