Introduction to Native Methods in Java
In this post, we will see a detailed explanation of the native methods in java. We will see the basic syntax of it along with their working. There will be java code examples showing the use of native methods.
Here is a basic syntax of how native methods are used in java:
[ public / protected / private] native [return-type] methodName ();
The above syntax shows how a native method is declared in java. Like a normal method, it requires access modifier to be defined followed by a native keyword, then followed by the return type of the method and finally the method name with input parameters specified if required.
How Native Method Works In Java?
Java native methods can be defined as those methods which are implemented in languages other than java like C/C++. The general idea behind using such methods may be to take advantage of high performance or memory management available in C/C++.
In order to support methods written in other languages, Java provides an interface called Java Native Interface which acts as a mediator between java and other languages. The motivation for using JNI comes from the fact that it can provide code reusability and high performance. It is to be noted that code written in other languages like C/C++ is not portable.
The following are main components of the Java native interface:
- javah: This is a tool available in java development kit that creates header files compatible with C from an existing java file java class containing native methods.
- h: This is a C/C++ based header file available in Java development kit whose function is to provide a mapping between Java data types and native data types. Javah file described above generates this file automatically.
Examples of Native Methods in Java
Now we will see an example that will provide a clear understanding of how native methods work in java. The following are steps involved in using native methods:
- Program java code.
- Compile java code.
- Create C header file.
- Implement native method logic in C/C++.
- Create shared library.
- Run and Test java application.
The below example will be divided into two parts one part having java code and other having native code.
Part #1: Java
Here is our java class containing the native method.
public native String encryptData (String inputdata);
System.loadLibrary ("nativedemo"); /* lowercase of classname! */
public static void main (String args)
NativeDemo demo = new NativeDemo ();
System.out.println("Encrypted data is " + demo.encryptData ("This is Edubca"));
The above example contains a native method declared in the NativeDemo class. The Implementation of encryptData method is written in C. As you can see we have used a static block whose purpose is to load the native C library in which implementation of encryptData method is available. One important thing to note that the string parameter supplied in System.loadLibrary method is the lowercase name of the enclosing java class. Now as per steps declared above it is time to compile our java code.
The following command compiles the above java code.
Now in the next step will create a header file using javah utility as described below.
The above command will generate a javah file with the same name as the name of the class. This file will be included while writing the C implementation of the native method.
Part #2: C Code
Here is the C implementation of native function encryptData.
JNIEXPORT void JNICALL
Java_NativeDemo_encryptData(JNIEnv *env, jobject obj, jstring inputstr)
const char *str= (*env)->GetStringUTFChars(env,inputstr,0) // create string from jstring
char Newch = '@';
for(i = 0; i <= strlen(str); i++)
if(str[i] == 'a' || str[i]== 'e' || str[i]== 'i' || str[i]== 'o' || str[i]== 'u' || str[i] == 'A' || str[i]== 'E' || str[i]== 'I' || str[i]== 'O' || str[i]== 'U')
str[i] = Newch;
return env->NewStringUTF(str); // convert string to jstring
- The above files are saved with NativeDemo.c.
- From the above code, we can see the logic of encryption is written in C language. The logic is simply based on replacing all vowels with @ and returning the string.
- In the next step will compile the above C code using the below command:
- The above command creates a shared library that is used by java programming layer to call code written in C.We can use different compilation strategies based on our compiler and operating system.
- After completing the above steps we can call run our java code like the below:
If everything goes well you will see the below output:
From the above article, we have a clear understanding of it. Most real-time applications written in java make use of native methods to take performance as well as memory management advantages available in native programming languages like C/C++.
This is a guide to Native Methods in Java. Here we discuss the introduction, how the native method works in Java? and examples. You may also have a look at the following articles to learn more –