- Write Native Methods in Java
- What Are Native Methods in Java
- Write Native Methods in Java Programs
- Write a Java Program
- Compile the Java Program
- Create a Header File
- Write the Native Code
- Create the Shared Library
- Run the Java Program
- Related Article — Java Method
- Native Methods in Java
- How Does Native Method Works In Java?
- Examples of Native Methods in Java
- Part #1: Java
- Part #2: C Code
- Conclusion
- Recommended Articles
Write Native Methods in Java
- What Are Native Methods in Java
- Write Native Methods in Java Programs
This article takes you through various steps necessary to learn how to write native methods in Java programs.
What Are Native Methods in Java
The native keyword is a modifier in Java programming, used with methods only. It represents that this particular method is written in the native code via Java Native Interface (JNI).
The native (or foreign) methods are implemented in C, C++, or any other platform-dependent code.
[public/protected/private] native [returnType] youMethodName();
Write Native Methods in Java Programs
Listed below is the multi-step process to write native methods in Java programs:
Write the Java program containing the native method’s declaration and the main method to call the native method.
Compile the Java program with the main method and declare the specified native method.
Use javah with -jni flag to create the header file for the native method.
Write the code for the native method in the programming language you like, for instance, C/C++.
Create the shared library to compile the implementation and header files.
Finally, execute/run the Java Program.
Let’s follow all of these steps to call native methods in the Java program.
Write a Java Program
class nativeDemoClass //declaration of the native method public native void showMessage(); //load native C library static System.loadLibrary("nativedemoclass"); //lowercase of classname > //java main method public static void main (String[] args) nativeDemoClass demo = new nativeDemoClass(); demo.showMessage(); > >
We must include the native keyword as a method’s declaration part in the Java program if we implement the method in a programming language other than Java.
This native keyword tells the Java compiler that this specific method is a native programming language method. Remember, the declaration of a native method in the Java program provides the method signature only.
We have a static block that loads the native C library in which we have written the implementation of the showMessage() method. Have you noticed that we are passing a string to the System.loadLibrary() method?
Why is it so? It is because this static block from the nativeDemoClass class will load the appropriate library, named nativedemoclass .
Let’s move to the second step and compile the Java program.
Compile the Java Program
Use the command given below to compile the Java program.
javac nativeDemoClass.java
After successfully compiling the Java program, we get the nativeDemoClass.class file.
Create a Header File
Use the following command to create a header file.
Here, -h produces the C/C++ header files and places the generated file into the specified directory. We use dot ( . ) to keep the generated header file in the current directory.
javac -h . nativeDemoClass.java
You may find on the Internet that javah creates C/C++ header files, which was correct until JDK 8. According to the oracle, javah is deprecated now, but we have an alternative solution given above.
The nativeDemoClass.h file looks as follows. We do not edit this because it is a machine-generated file.
/* DO NOT EDIT THIS FILE - it is machine generated */ #include /* Header for class nativeDemoClass */ #ifndef _Included_nativeDemoClass #define _Included_nativeDemoClass #ifdef __cplusplus extern "C" #endif /* * Class: nativeDemoClass * Method: showMessage * Signature: ()V */ JNIEXPORT void JNICALL Java_nativeDemoClass_showMessage (JNIEnv *, jobject); #ifdef __cplusplus > #endif #endif
The JNIEXPORT void JNICALL Java_nativeDemoClass_showMessage declares the C function in this header file. We can have multiple function signatures if the nativeDemoClass has more native methods.
- Prefix as Java_
- The package name
- The class name
- native method’s name
Each section is separated by an underscore ( _ ), as shown graphically below:
Further, the JNIEnv* refers to the Java Native Interface environment that allows us to access the Java Native Interface (JNI) methods. The jobject references this object of Java programming.
Write the Native Code
#include #include "nativeDemoClass.h" #include JNIEXPORT void JNICALL Java_nativeDemoClass_showMessage(JNIEnv *env, jobject obj) printf("Hello world!\n"); return; >
The implementation of Java_nativeDemoClass_showMessage is pretty straightforward because we are only using a printf() statement to print Hello world . Remember, this .c file has three headers, jni.h , stdio.h , and nativeDemoClass.h created in the previous step.
Create the Shared Library
Use the following command to create the shared library. We must have build tools for visual studio to use the CL command.
cl -Ic:\java\jdk-17.0.2\include -Ic:\java\jdk-17.0.2\include\win32 -LD nativeDemoClassImp.c -Fenativedemoclass.dll
Remember, the Java program uses the following method to load the shared library, named nativedemoclass at run time.
System.loadLibrary("nativedemoclass");
Run the Java Program
Finally, use the command given below to run the Java program.
You will see Hello world! on the command line if you have done everything correctly.
Mehvish Ashiq is a former Java Programmer and a Data Science enthusiast who leverages her expertise to help others to learn and grow by creating interesting, useful, and reader-friendly content in Computer Programming, Data Science, and Technology.
Related Article — Java Method
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.
Web development, programming languages, Software testing & others
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. Similar to a regular method, it necessitates the definition of an access modifier, followed by the native keyword, then the return type of the method, and lastly, the method name with any necessary input parameters specified.
How Does Native Method Works In Java?
We can define it as methods implemented in languages other than Java, such as C/C++. The general idea behind using such methods may be to take advantage of high performance or memory management available in C/C++.
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 its ability to provide code reusability and high performance. Note that code written in other languages like C/C++ is not portable.
The following are the main components of the Java native interface:
- javah: This tool is available in the 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 the Java development kit that provides 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 clearly understands how native methods work in Java. The following are the steps involved in using native methods:
- Program java code.
- Compile java code.
- Create a C header file.
- Implement native method logic in C/C++.
- Create a shared library.
- Run and Test java applications.
The below example will be divided into two parts: having java code and having native code.
Part #1: Java
Here is our java class containing the native method.
package com.edubca.nativedemo; class NativeDemo < public native String encryptData (String inputdata); static < 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. We have written the implementation of the encryptData method in C. As you can see, we have used a static block whose purpose is to load the native C library in which the implementation of the encryptData method is available. One important note is that you should supply the lowercase name of the enclosing Java class as the string parameter in the System.loadLibrary method. As per the steps declared above, it is time to compile our java code.
The following command compiles the above java code.
In the next step, we 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. While writing the C implementation of the native method, you should include this file.
Part #2: C Code
Here is the C implementation of the native function encryptData.
#include #include #include "NativeDemo.h" 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 > 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 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 used by the 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:
Conclusion
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++.
Recommended Articles
This is a guide to Native Methods in Java. Here we discuss the introduction, how the native method works in Java? Along with examples. You may also have a look at the following articles to learn more –
500+ Hours of HD Videos
15 Learning Paths
120+ Courses
Verifiable Certificate of Completion
Lifetime Access
1000+ Hours of HD Videos
43 Learning Paths
250+ Courses
Verifiable Certificate of Completion
Lifetime Access
1500+ Hour of HD Videos
80 Learning Paths
360+ Courses
Verifiable Certificate of Completion
Lifetime Access
3000+ Hours of HD Videos
149 Learning Paths
600+ Courses
Verifiable Certificate of Completion
Lifetime Access
All in One Software Development Bundle 3000+ Hours of HD Videos | 149 Learning Paths | 600+ Courses | Verifiable Certificate of Completion | Lifetime Access
Financial Analyst Masters Training Program 1000+ Hours of HD Videos | 43 Learning Paths | 250+ Courses | Verifiable Certificate of Completion | Lifetime Access