Native methods are implemented in the machine code used by the host CPU, not using java bytecodes. Native method is used to increase the performance. Syntax of Native Method
class clsName
{
// Variable declaration
// Constructor
// Method
native rtype mthName(params)
{
// Body of method
}
}
clsName is a valid identifier in java. It is a class name.
native is a keyword to define that method an abstract method.
rtype is return type of a method.
mthName is a method name and valid java identifier.
Example of Native Method
Example 1 : Program that illustrates the use of native method
public class nativeClass
{
static
{
System.loadLibrary("nativeClass");
}
public native String displayText(String s);
public static void main(String[] argv)
{
String strValue = null;
nativeClass nObj = new nativeClass();
strValue = nObj.displayText("Hello World");
System.out.println("Text is " + strValue);
}
}
Output
Text is Hello World