Native Methods with JNI: Calling C Code from Java
The Java Native Interface: declaring native methods, generating headers with javac -h, JNI function naming and type mapping, strings and modified UTF-8, arrays, calling Java from C, exceptions, references, building and loading libraries, native access restrictions, and why the FFM API replaces JNI.
kvi5hnuCode Sprout team member16 min readOn this page
"100% Pure Java" is the ideal, but sometimes a program has to call code written in another language, usually C or C++. Such code is called native code. Speed alone is rarely a good reason any more: JIT-compiled Java is fast, and the cost of crossing the language boundary often eats the gain. The real reasons are access to operating system features and devices that the Java platform does not expose, and existing libraries that are too large or too specialized to rewrite, such as a compression codec, a database engine, or a machine learning library running on the GPU.
Since Java 1.1, the bridge has been the Java Native Interface (JNI). Since Java 22, the Foreign Function and Memory API (FFM, JEP 454, from Project Panama) offers a better one: it calls C functions directly from Java, without writing C glue code. New code should use FFM, which the rest of this part covers. JNI is still everywhere, though: in the JDK itself, in libraries you depend on, and in code you may maintain. This article explains how it works, so you can read and judge JNI code, and so you see what FFM improves.
Going native has costs in either case. You need a compiled library for every platform you support (Linux x64 and ARM, macOS, Windows, ...). And C code has none of Java's safety: an invalid pointer can corrupt memory, crash the JVM or open a security hole. That is why the JDK now requires programs to opt in to native access.
Declaring a native method
A native method is declared in a Java class with the native modifier and no body, much like an abstract method:
public final class HelloNative {
public static native int printf(String text);
}
Native methods can be static or instance methods, can be overloaded and can throw exceptions. The class compiles normally. Calling the method, however, fails with UnsatisfiedLinkError until a library containing the implementation has been loaded, as the demo shows.
The C side
The JVM finds the implementation by its name. The C function for a native method is named:
Java_, followed by- the fully qualified class name, with the dots of the package replaced by underscores, then
- an underscore and the method name.
jnidemo.HelloNative.printf becomes Java_jnidemo_HelloNative_printf. Characters that are not plain ASCII letters or digits are escaped: _ becomes _1, ; becomes _2, [ becomes _3, and any other character becomes _0 followed by its four-digit hexadecimal UTF-16 code. A nested class Outer$Inner therefore turns into Outer_00024Inner. If a native method is overloaded, the name is followed by two underscores and the mangled descriptor of the parameter types: greeting() becomes ..._greeting__, greeting(int) becomes ..._greeting__I, and print(String[]) becomes ..._print___3Ljava_lang_String_2. The demo implements these rules and agrees with what javac generates.
Nobody writes these names by hand. javac -h directory compiles the class and writes a C header file with the exact declarations (the separate javah tool was removed in Java 10):
javac -h . HelloNative.java
The generated header declares one function per native method:
JNIEXPORT jint JNICALL Java_HelloNative_printf(JNIEnv *, jclass, jstring);
JNIEXPORT and JNICALL are macros from jni.h that mark the function as exported with the right calling convention. Every native function receives two extra parameters before the Java arguments:
JNIEnv *env, a pointer to a table of JNI functions through which C code works with Java objects:(*env)->GetStringUTFChars(env, ...)in C,env->GetStringUTFChars(...)in C++. The pointer is valid only in the current thread.jclassfor a static method (the class), orjobjectfor an instance method (thethisobject).
C++ implementations must be declared extern "C" (the generated header does this) so that the compiler does not mangle the names C++-style.
Type mapping
Java primitive types map to C types of fixed size defined in jni.h: jboolean (unsigned 8 bits), jbyte, jchar (unsigned 16 bits, a UTF-16 code unit), jshort, jint (32 bits), jlong (64 bits), jfloat and jdouble. All object references are opaque handles of type jobject, with typedefs that document what they refer to: jstring, jclass, jthrowable, jarray and the typed arrays jintArray, jdoubleArray, ..., jobjectArray. C code cannot look inside a jobject; it must use JNIEnv functions.
JNI refers to methods and fields with descriptors, the same strings the class file format uses: I for int, Z for boolean, J for long, Ljava/lang/String; for a class, [I for int[], and (Ljava/lang/String;)I for a method taking a String and returning an int. javap -s ClassName prints them, and Class.descriptorString() (Java 12) returns them at run time.
Strings
Java strings are sequences of UTF-16 code units; C strings are zero-terminated byte arrays. JNI offers two conversions:
GetStringUTFCharsreturns aconst char *in modified UTF-8, andNewStringUTFmakes a Java string from one.GetStringCharsreturnsconst jchar *UTF-16 code units, for C functions working with 16-bit characters (Windows' wide character functions, for example), andNewStringgoes the other way.
Modified UTF-8 is UTF-8 with two differences, both visible in the demo. The NUL character is encoded as the two bytes C0 80, so a Java string containing \u0000 never produces a zero byte inside the C string. And characters outside the Basic Multilingual Plane, such as emoji, are not encoded as one 4-byte sequence but as two 3-byte sequences, one for each UTF-16 surrogate, 6 bytes in total. For ASCII text, both encodings are identical. When C code needs real UTF-8, for example to pass a file name with emoji to the operating system, the safe route is to call String.getBytes(StandardCharsets.UTF_8) in Java and pass a byte array.
The characters may be a copy or point directly into the JVM's string data, so they are const, and every Get must be paired with a Release:
const char *chars = (*env)->GetStringUTFChars(env, text, NULL);
if (chars == NULL) return -1; /* out of memory: an exception is pending */
int count = printf("%s", chars);
(*env)->ReleaseStringUTFChars(env, text, chars);
Forgetting the Release leaks memory or keeps the string pinned. GetStringUTFRegion and GetStringRegion copy into a buffer you provide and need no release.
Arrays
Arrays work the same way. GetArrayLength returns the length. Get<Type>ArrayRegion and Set<Type>ArrayRegion copy a range between a Java array and a C buffer, which is simple and safe. Get<Type>ArrayElements returns a pointer to the whole array, possibly a copy, and Release<Type>ArrayElements ends the access with a mode: 0 copies changes back and frees the copy, JNI_COMMIT copies back but keeps the buffer, JNI_ABORT discards changes. GetPrimitiveArrayCritical gives the most direct access, but the code between it and the release must not call other JNI functions or block, because the JVM may have to pause the garbage collector meanwhile.
Object arrays are accessed one element at a time with GetObjectArrayElement and SetObjectArrayElement; New<Type>Array and NewObjectArray create arrays.
Calling Java from C
C code can use any Java class. It looks up the class, the method or field ID by name and descriptor, and then calls or accesses it:
jclass type = (*env)->GetObjectClass(env, listener);
jmethodID accept = (*env)->GetMethodID(env, type, "accept", "(I)V");
(*env)->CallVoidMethod(env, listener, accept, 42);
There are Call<Type>Method, CallStatic<Type>Method and CallNonvirtual<Type>Method variants for each return type, GetFieldID with Get<Type>Field and Set<Type>Field for instance fields, the Static versions for static fields, and FindClass("java/util/ArrayList") with NewObject to construct objects. Looking up IDs is slow, so code that calls the same method often looks it up once and caches the ID.
Exceptions
C has no exceptions. A Java exception thrown in a method called from C, or by a failing JNI function, becomes pending: C code continues, and the exception is thrown in Java when the native method returns. With an exception pending, C code may only clean up and return; calling most JNI functions is not allowed. Check with ExceptionCheck after each call that can throw, and clear with ExceptionClear if the C code handles the problem itself.
To throw an exception from C, call ThrowNew with an exception class and a message, then return:
jclass exception = (*env)->FindClass(env, "java/lang/IllegalArgumentException");
(*env)->ThrowNew(env, exception, "division by zero");
return 0; /* the return value is ignored */
References and threads
The jobject handles that a native method receives or creates are local references, valid only until the method returns. The JVM keeps their objects alive meanwhile. A loop creating many objects should release references with DeleteLocalRef, or use PushLocalFrame and PopLocalFrame, because the number of local references is limited. To keep an object between calls, for example a cached jclass, create a global reference with NewGlobalRef and release it with DeleteGlobalRef; NewWeakGlobalRef creates one that does not keep the object alive.
A JNIEnv belongs to one thread. A thread created in C that wants to call Java must attach itself with AttachCurrentThread (through the JavaVM pointer) to get its own JNIEnv. The same invocation API lets a C program start a JVM with JNI_CreateJavaVM, which is how the java launcher itself works.
Native methods also matter for virtual threads: while a virtual thread is inside a native method, it cannot be unmounted from its carrier thread, so long blocking native calls tie up a platform thread.
Explicit registration
Instead of relying on mangled names, a library can register its functions explicitly. When the JVM loads a library, it calls the library's JNI_OnLoad function if there is one; that function can call RegisterNatives with a table of method names, descriptors and function pointers. Libraries use this to give functions ordinary names, and JNI_OnLoad also returns the JNI version the library needs.
Building and loading the library
Compile the C code into a shared library, with the include directories of the JDK on the path:
gcc -shared -fPIC -I "$JAVA_HOME/include" -I "$JAVA_HOME/include/linux" -o libHelloNative.so HelloNative.c
clang -shared -fPIC -I "$JAVA_HOME/include" -I "$JAVA_HOME/include/darwin" -o libHelloNative.dylib HelloNative.c
cl -I "%JAVA_HOME%\include" -I "%JAVA_HOME%\include\win32" -LD HelloNative.c -FeHelloNative.dll
In Java, load the library before the first call, typically in a static initializer:
static {
System.loadLibrary("HelloNative");
}
loadLibrary takes a platform-independent name and turns it into the file name the platform uses (System.mapLibraryName shows the result: libHelloNative.so, libHelloNative.dylib or HelloNative.dll), then searches the directories in the java.library.path system property, which defaults to the system's library path (LD_LIBRARY_PATH on Linux, PATH on Windows). Set it with -Djava.library.path=.... System.load("/full/path/libHelloNative.so") loads a file by absolute path, which is what libraries do after extracting their native code from a JAR into a temporary directory.

Native access must be enabled
Native code can break every guarantee Java makes, so the JDK has started treating it as a restricted operation. Restricted FFM methods have printed a warning without permission since Java 22, and Java 24 (JEP 472) extended the same treatment to JNI: it prints warnings when code loads a native library without permission:
WARNING: A restricted method in java.lang.System has been called
WARNING: java.lang.System::loadLibrary has been called by HelloNative in an unnamed module
WARNING: Use --enable-native-access=ALL-UNNAMED to avoid a warning for callers in this module
WARNING: Restricted methods will be blocked in a future release unless native access is enabled
Grant access on the command line, for the class path or for named modules:
java --enable-native-access=ALL-UNNAMED -Djava.library.path=. HelloNative
java --enable-native-access=com.example.audio,com.example.db -m com.example.app/...
or, for an executable JAR, with the manifest attribute Enable-Native-Access: ALL-UNNAMED. The option --illegal-native-access=allow|warn|deny chooses what happens without permission; the default warn will become deny in a future release. Module.isNativeAccessEnabled() reports the status; in the demo, run without the flag, it is false. At compile time, javac -Xlint:restricted (part of -Xlint:all) warns about calls of restricted methods such as System.loadLibrary, which you can suppress with @SuppressWarnings("restricted") where the call is intended.
A complete example
This class has native methods for each technique of this article: printing a string, reading an array, modifying an array, calling back into Java, and throwing an exception.
public final class HelloNative {
static {
load();
}
@SuppressWarnings("restricted") // loading native code is a restricted operation
private static void load() {
System.loadLibrary("HelloNative"); // libHelloNative.so, libHelloNative.dylib or HelloNative.dll
}
/** Prints with C's printf and returns the number of characters printed. */
public static native int printf(String text);
/** Sums an int array in C. */
public static native long sum(int[] values);
/** Multiplies every element by factor, in place. */
public static native void scale(double[] values, double factor);
/** Calls back into Java: invokes listener.accept(i) for i from 1 to n. */
public static native void countTo(int n, java.util.function.IntConsumer listener);
/** Throws IllegalArgumentException from C if divisor is 0. */
public static native int divide(int dividend, int divisor);
public static void main(String[] args) {
int printed = printf("Hello, Native World!\n");
System.out.println("Printed " + printed + " characters.");
System.out.println("sum = " + sum(new int[] {1, 2, 3, 4, 5}));
double[] values = {1.5, 2.5};
scale(values, 2);
System.out.println("scaled = " + java.util.Arrays.toString(values));
countTo(3, i -> System.out.println("callback " + i));
try {
divide(1, 0);
} catch (IllegalArgumentException e) {
System.out.println("exception from C: " + e.getMessage());
}
}
}
javac -h . HelloNative.java generates HelloNative.h, which the C file includes:
#include <jni.h>
#include <stdio.h>
#include "HelloNative.h"
JNIEXPORT jint JNICALL Java_HelloNative_printf(JNIEnv *env, jclass cl, jstring text) {
const char *chars = (*env)->GetStringUTFChars(env, text, NULL); /* modified UTF-8 */
if (chars == NULL) return -1; /* OutOfMemoryError pending */
int count = printf("%s", chars);
fflush(stdout);
(*env)->ReleaseStringUTFChars(env, text, chars); /* always release */
return count;
}
JNIEXPORT jlong JNICALL Java_HelloNative_sum(JNIEnv *env, jclass cl, jintArray values) {
jsize length = (*env)->GetArrayLength(env, values);
jint buffer[256];
jlong total = 0;
for (jsize start = 0; start < length; start += 256) { /* copy in chunks */
jsize n = length - start < 256 ? length - start : 256;
(*env)->GetIntArrayRegion(env, values, start, n, buffer);
for (jsize i = 0; i < n; i++) total += buffer[i];
}
return total;
}
JNIEXPORT void JNICALL Java_HelloNative_scale(JNIEnv *env, jclass cl, jdoubleArray values, jdouble factor) {
jdouble *elements = (*env)->GetDoubleArrayElements(env, values, NULL); /* pinned or copied */
if (elements == NULL) return;
jsize length = (*env)->GetArrayLength(env, values);
for (jsize i = 0; i < length; i++) elements[i] *= factor;
(*env)->ReleaseDoubleArrayElements(env, values, elements, 0); /* 0: copy back and free */
}
JNIEXPORT void JNICALL Java_HelloNative_countTo(JNIEnv *env, jclass cl, jint n, jobject listener) {
jclass type = (*env)->GetObjectClass(env, listener);
jmethodID accept = (*env)->GetMethodID(env, type, "accept", "(I)V"); /* name and descriptor */
if (accept == NULL) return; /* NoSuchMethodError pending */
for (jint i = 1; i <= n; i++) {
(*env)->CallVoidMethod(env, listener, accept, i);
if ((*env)->ExceptionCheck(env)) return; /* let the Java exception propagate */
}
}
JNIEXPORT jint JNICALL Java_HelloNative_divide(JNIEnv *env, jclass cl, jint dividend, jint divisor) {
if (divisor == 0) {
jclass exception = (*env)->FindClass(env, "java/lang/IllegalArgumentException");
if (exception != NULL) (*env)->ThrowNew(env, exception, "division by zero");
return 0; /* the exception is thrown when the method returns */
}
return dividend / divisor;
}
Build and run on macOS (use the Linux or Windows command from above on those systems):
javac -h . HelloNative.java
clang -shared -fPIC -I "$JAVA_HOME/include" -I "$JAVA_HOME/include/darwin" -o libHelloNative.dylib HelloNative.c
java --enable-native-access=ALL-UNNAMED -Djava.library.path=. HelloNative
Output:
Hello, Native World!
Printed 21 characters.
sum = 15
scaled = [3.0, 5.0]
callback 1
callback 2
callback 3
exception from C: division by zero
The first line comes from C's printf, the rest from Java. fflush matters: C's standard output has its own buffer, separate from System.out, so without it the C output could appear after later Java output.
Why FFM replaces JNI
The example shows JNI's burdens: every function needs C glue code that converts arguments with JNIEnv calls, the glue must be compiled for each platform, mistakes in reference or exception handling crash the JVM, and calling an existing C library (rather than code written for Java) always requires a wrapper. With FFM, the same printf call is a few lines of Java and no C at all:
Linker linker = Linker.nativeLinker();
MethodHandle printf = linker.downcallHandle(
linker.defaultLookup().findOrThrow("printf"),
FunctionDescriptor.of(ValueLayout.JAVA_INT, ValueLayout.ADDRESS, ValueLayout.ADDRESS),
Linker.Option.firstVariadicArg(1)); // printf takes a variable number of arguments
try (Arena arena = Arena.ofConfined()) {
int count = (int) printf.invokeExact(arena.allocateFrom("%s"), arena.allocateFrom("Hello, Foreign World!\n"));
}
FFM describes C functions and data structures in Java, manages native memory with deterministic lifetimes and bounds checks, and its jextract tool generates the Java bindings for a whole C library from its header files. The next articles cover it step by step. JNI remains supported, and there are no plans to remove it, but new native interoperability should use FFM.
The program
The demo cannot compile C code, but it shows the Java side of JNI: native method declarations, the failure when no library implements them, the header that javac -h generates (through the compiler API, into a temporary directory), the mangled function names, the type mapping and the modified UTF-8 encoding.
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.lang.invoke.MethodType;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.HexFormat;
import java.util.List;
import javax.tools.JavaCompiler;
import javax.tools.SimpleJavaFileObject;
import javax.tools.ToolProvider;
public class Solution {
/** A class with native methods; no library implements them in this demo. */
static class Greeter {
static native int printf(String format);
native void greeting();
native void greeting(int repeat);
native double[] scale(double[] values, double factor);
}
public static void main(String[] args) throws Exception {
nativeMethods();
generatedHeader();
nameMangling();
typeMapping();
modifiedUtf8();
}
static void nativeMethods() {
System.out.println("== Native methods ==");
for (Method m : sorted(Greeter.class.getDeclaredMethods()))
System.out.println(" " + Modifier.toString(m.getModifiers()) + " " + m.getName()
+ MethodType.methodType(m.getReturnType(), m.getParameterTypes()).toMethodDescriptorString());
try {
Greeter.printf("Hello");
} catch (UnsatisfiedLinkError e) {
System.out.println("calling printf: UnsatisfiedLinkError " + e.getMessage());
}
var objectNatives = Arrays.stream(Object.class.getDeclaredMethods())
.filter(m -> Modifier.isNative(m.getModifiers())).map(Method::getName).sorted().toList();
System.out.println("native methods of java.lang.Object: " + objectNatives);
System.out.println("native access enabled for this module: "
+ Solution.class.getModule().isNativeAccessEnabled() + " (run with --enable-native-access=ALL-UNNAMED)");
}
static Method[] sorted(Method[] methods) {
Arrays.sort(methods, java.util.Comparator.comparing(Method::toString));
return methods;
}
/** Compiles a source file with javac -h, like the command line does, and prints the header. */
static void generatedHeader() throws IOException {
System.out.println();
System.out.println("== The header file from javac -h ==");
JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
if (javac == null) {
System.out.println("no compiler available in this runtime");
return;
}
String source = """
package jnidemo;
public class HelloNative {
public static native int printf(String str);
}
""";
var file = new SimpleJavaFileObject(URI.create("string:///jnidemo/HelloNative.java"),
SimpleJavaFileObject.Kind.SOURCE) {
@Override public CharSequence getCharContent(boolean ignoreErrors) { return source; }
};
Path dir = Files.createTempDirectory("jni");
try {
boolean ok = javac.getTask(null, null, null,
List.of("-h", dir.toString(), "-d", dir.toString()), null, List.of(file)).call();
Path header = dir.resolve("jnidemo_HelloNative.h");
System.out.println("compiled: " + ok + ", wrote " + header.getFileName());
Files.readAllLines(header).forEach(line -> System.out.println(" | " + line));
} finally {
try (var walk = Files.walk(dir)) {
for (Path p : walk.sorted(java.util.Comparator.reverseOrder()).toList()) Files.delete(p);
}
}
}
/** Escapes a name the way the JNI specification describes. */
static String mangle(String s) {
var sb = new StringBuilder();
for (char c : s.toCharArray()) {
if (c == '/' || c == '.') sb.append('_');
else if (c == '_') sb.append("_1");
else if (c == ';') sb.append("_2");
else if (c == '[') sb.append("_3");
else if (c < 128 && Character.isLetterOrDigit(c)) sb.append(c);
else sb.append("_0").append("%04x".formatted((int) c));
}
return sb.toString();
}
static String jniName(String className, String method, String descriptor, boolean overloaded) {
String name = "Java_" + mangle(className) + "_" + mangle(method);
if (overloaded) {
String args = descriptor.substring(1, descriptor.indexOf(')'));
name += "__" + mangle(args.replace('.', '/'));
}
return name;
}
static void nameMangling() {
System.out.println();
System.out.println("== C function names that the JVM looks for ==");
for (Method m : sorted(Greeter.class.getDeclaredMethods())) {
boolean overloaded = Arrays.stream(Greeter.class.getDeclaredMethods())
.filter(o -> o.getName().equals(m.getName())).count() > 1;
String descriptor = MethodType.methodType(m.getReturnType(), m.getParameterTypes()).toMethodDescriptorString();
System.out.println(" " + m.getName() + descriptor + " -> "
+ jniName(Greeter.class.getName(), m.getName(), descriptor, overloaded));
}
System.out.println(" com.example.Hello_World.print(String) -> "
+ jniName("com.example.Hello_World", "print", "(Ljava/lang/String;)V", false));
System.out.println(" overloaded print(String[]) -> "
+ jniName("com.example.Hello_World", "print", "([Ljava/lang/String;)V", true));
System.out.println(" class Grüße, method hallo -> " + jniName("Grüße", "hallo", "()V", false));
}
static void typeMapping() {
System.out.println();
System.out.println("== Java types and their JNI counterparts ==");
Class<?>[] types = {boolean.class, byte.class, char.class, short.class, int.class, long.class,
float.class, double.class, void.class, String.class, Class.class, Object.class, int[].class,
String[].class, Throwable.class};
String[] jni = {"jboolean (unsigned 8 bits)", "jbyte (signed 8 bits)", "jchar (unsigned 16 bits)",
"jshort (signed 16 bits)", "jint (signed 32 bits)", "jlong (signed 64 bits)", "jfloat (32 bits)",
"jdouble (64 bits)", "void", "jstring", "jclass", "jobject", "jintArray", "jobjectArray", "jthrowable"};
for (int i = 0; i < types.length; i++)
System.out.printf(" %-20s %-20s %s%n", types[i].getSimpleName(), types[i].descriptorString(), jni[i]);
}
static void modifiedUtf8() throws IOException {
System.out.println();
System.out.println("== Modified UTF-8 (JNI's GetStringUTFChars) versus standard UTF-8 ==");
String s = "A\u0000é😀"; // A, NUL, e with acute, an emoji outside the BMP
var bytes = new ByteArrayOutputStream();
new DataOutputStream(bytes).writeUTF(s); // writeUTF uses modified UTF-8 after a length
byte[] modified = Arrays.copyOfRange(bytes.toByteArray(), 2, bytes.size());
var hex = HexFormat.ofDelimiter(" ");
System.out.println(" standard UTF-8 (" + s.getBytes(StandardCharsets.UTF_8).length + " bytes): "
+ hex.formatHex(s.getBytes(StandardCharsets.UTF_8)));
System.out.println(" modified UTF-8 (" + modified.length + " bytes): " + hex.formatHex(modified));
System.out.println(" NUL becomes C0 80 (no zero byte inside the C string); the emoji becomes two"
+ " 3-byte surrogates");
System.out.println(" UTF-16 for GetStringChars: " + s.length() + " jchar values");
}
}
== Native methods ==
native scale([DD)[D
native greeting()V
native greeting(I)V
static native printf(Ljava/lang/String;)I
calling printf: UnsatisfiedLinkError 'int Solution$Greeter.printf(java.lang.String)'
native methods of java.lang.Object: [clone, getClass, hashCode, notify, notifyAll, wait0]
native access enabled for this module: false (run with --enable-native-access=ALL-UNNAMED)
== The header file from javac -h ==
compiled: true, wrote jnidemo_HelloNative.h
| /* DO NOT EDIT THIS FILE - it is machine generated */
| #include <jni.h>
| /* Header for class jnidemo_HelloNative */
|
| #ifndef _Included_jnidemo_HelloNative
| #define _Included_jnidemo_HelloNative
| #ifdef __cplusplus
| extern "C" {
| #endif
| /*
| * Class: jnidemo_HelloNative
| * Method: printf
| * Signature: (Ljava/lang/String;)I
| */
| JNIEXPORT jint JNICALL Java_jnidemo_HelloNative_printf
| (JNIEnv *, jclass, jstring);
|
| #ifdef __cplusplus
| }
| #endif
| #endif
== C function names that the JVM looks for ==
scale([DD)[D -> Java_Solution_00024Greeter_scale
greeting()V -> Java_Solution_00024Greeter_greeting__
greeting(I)V -> Java_Solution_00024Greeter_greeting__I
printf(Ljava/lang/String;)I -> Java_Solution_00024Greeter_printf
com.example.Hello_World.print(String) -> Java_com_example_Hello_1World_print
overloaded print(String[]) -> Java_com_example_Hello_1World_print___3Ljava_lang_String_2
class Grüße, method hallo -> Java_Gr_000fc_000dfe_hallo
== Java types and their JNI counterparts ==
boolean Z jboolean (unsigned 8 bits)
byte B jbyte (signed 8 bits)
char C jchar (unsigned 16 bits)
short S jshort (signed 16 bits)
int I jint (signed 32 bits)
long J jlong (signed 64 bits)
float F jfloat (32 bits)
double D jdouble (64 bits)
void V void
String Ljava/lang/String; jstring
Class Ljava/lang/Class; jclass
Object Ljava/lang/Object; jobject
int[] [I jintArray
String[] [Ljava/lang/String; jobjectArray
Throwable Ljava/lang/Throwable; jthrowable
== Modified UTF-8 (JNI's GetStringUTFChars) versus standard UTF-8 ==
standard UTF-8 (8 bytes): 41 00 c3 a9 f0 9f 98 80
modified UTF-8 (11 bytes): 41 c0 80 c3 a9 ed a0 bd ed b8 80
NUL becomes C0 80 (no zero byte inside the C string); the emoji becomes two 3-byte surrogates
UTF-16 for GetStringChars: 5 jchar values
Points to notice:
- Calling the unimplemented native method threw
UnsatisfiedLinkErrornaming the method; onlyjava.lang.Object's own natives are bound to the JVM. - The generated header contains the
extern "C"guard for C++ and the descriptor of the method in a comment. - The nested class became
Solution_00024Greeter; only the overloadedgreetingmethods got the__suffix with the argument descriptor;_turned into_1,[into_3and;into_2; non-ASCII letters became_0with four hex digits. - Modified UTF-8 needed 11 bytes where UTF-8 needs 8, and it contains no zero byte.
Common questions
Should I use JNI or the FFM API for new code? FFM (articles 107 to 110) for calling C libraries: no C glue code, no separate build per platform for your wrapper, and memory errors surface as Java exceptions far more often. JNI remains necessary for existing native libraries written against it, and for native code that must call back into many Java APIs.
What does UnsatisfiedLinkError: no xyz in java.library.path mean?
System.loadLibrary("xyz") didn't find libxyz.so, libxyz.dylib or xyz.dll in the directories of java.library.path. Pass -Djava.library.path=dir, set LD_LIBRARY_PATH/DYLD_LIBRARY_PATH/PATH, or load with an absolute path via System.load. The same error with a method name means the library loaded but the function name or signature doesn't match the generated header.
Why do I get a warning about native access?
Since Java 24 (JEP 472), loading native libraries and using JNI prints a warning unless native access is enabled with --enable-native-access=ALL-UNNAMED (or a module name), or Enable-Native-Access: ALL-UNNAMED in an executable JAR's manifest. A future release will turn the warning into an error by default.
Can a bug in native code crash the JVM?
Yes. Native code runs in the JVM process without Java's safety checks; a bad pointer can corrupt memory or crash with a hs_err_pid log. Run with -Xcheck:jni during development to catch many API misuses.
How do I ship native libraries with my JAR?
Package the libraries for each platform as resources, extract the right one to a temporary directory at startup and call System.load with its path, or install them alongside the application with jpackage. Libraries such as JNA and native-image tooling automate this.
API reference
| Item | Purpose |
|---|---|
native modifier | Declares a method implemented in native code. |
System.loadLibrary(name), System.load(path), System.mapLibraryName, java.library.path | Loading native libraries. |
javac -h dir, javap -s | Generating JNI headers; showing descriptors. |
--enable-native-access=ALL-UNNAMED or module names, Enable-Native-Access manifest attribute, --illegal-native-access=allow/warn/deny, Module.isNativeAccessEnabled | Permission for native code. |
UnsatisfiedLinkError | No implementation found for a native method or library. |
GetStringUTFChars/ReleaseStringUTFChars, GetStringChars/ReleaseStringChars, NewStringUTF, NewString, GetStringUTFRegion | Strings. |
GetArrayLength, Get/Set<Type>ArrayRegion, Get/Release<Type>ArrayElements (0, JNI_COMMIT, JNI_ABORT), GetPrimitiveArrayCritical, New<Type>Array | Arrays. |
FindClass, GetObjectClass, GetMethodID, GetStaticMethodID, Call<Type>Method, GetFieldID, Get/Set<Type>Field, NewObject | Using Java classes from C. |
ThrowNew, ExceptionCheck, ExceptionOccurred, ExceptionClear | Exceptions. |
NewGlobalRef, DeleteGlobalRef, NewWeakGlobalRef, DeleteLocalRef, PushLocalFrame | References. |
JNI_OnLoad, RegisterNatives, AttachCurrentThread, JNI_CreateJavaVM | Registration, threads and the invocation API. |
Summary
- A
nativemethod has its implementation in a shared library. The C function's name isJava_plus the mangled class and method names (plus the argument descriptor for overloads);javac -hgenerates the declarations. - Native functions receive a
JNIEnvpointer and work with Java data only through its functions: strings in modified UTF-8 or UTF-16, arrays by region or by pinned elements, method and field IDs looked up by name and descriptor. EveryGetneeds itsRelease. - Exceptions are pending until the native method returns; check after each call. Local references die with the method; keep objects with global references.
- Load libraries with
System.loadLibrary, found throughjava.library.path, and enable native access with--enable-native-access, or the JVM warns (and will refuse in the future). - JNI requires C glue code for every function and platform. The FFM API calls native functions from pure Java and is the recommended choice for new code.
Practice Questions
1. A program declares native methods and calls them, but fails with UnsatisfiedLinkError. Name three possible causes.
The library was never loaded (no System.loadLibrary call before the first use); the library file was not found in java.library.path or has the wrong file name for the platform (for example HelloNative.so instead of libHelloNative.so); or the library was loaded but does not contain a function with the exact expected name, for example because the class was moved to another package, an overload was added (which changes the name to include the argument descriptor), or a C++ file lacks extern "C". A library built for another CPU architecture or operating system also fails to load.
2. Why does every GetStringUTFChars call need a matching ReleaseStringUTFChars?
GetStringUTFChars either allocates a new buffer holding the modified UTF-8 copy, or gives direct access to the JVM's string data, which then must stay pinned in place. ReleaseStringUTFChars frees the copy or unpins the data. Without it, the program leaks native memory on every call, or the garbage collector is hindered. The same applies to the array element functions.
3. Java code passes the string "a\u0000b" to a native method that uses GetStringUTFChars and strlen. What length does strlen report, and why?
- Modified UTF-8 encodes the NUL character as the two bytes
C0 80instead of a zero byte, so the C string holds the bytes61 C0 80 62followed by the terminating zero.strlencounts bytes up to the first zero byte:a, the two bytes standing for NUL, andb. With standard UTF-8 the NUL would be a zero byte, andstrlenwould report 1.
4. A native function calls a Java method with CallVoidMethod, and the Java method throws an exception. What happens in the C code, and what should it do?
Nothing happens immediately: C has no exceptions, so CallVoidMethod returns and the exception becomes pending in the thread. The C code should check with ExceptionCheck (or ExceptionOccurred) right after the call, and then either release its resources and return, so that the exception is thrown in Java when the native method returns, or handle the problem and call ExceptionClear. Calling other JNI functions while an exception is pending is not allowed and may crash.
5. What does --enable-native-access do, and what happens without it in current JDKs?
It grants code in the listed modules (or ALL-UNNAMED for the class path) permission to use restricted operations: loading native libraries for JNI (System.loadLibrary, System.load), and restricted FFM methods such as creating downcall handles. Without it, JDK 24 and later print a warning the first time such an operation is used by code without permission, and the default mode is announced to change to deny, which will make such calls throw an exception. --illegal-native-access=deny already enables that behavior.
Previous: Printing in Java: Print Jobs, Multipage Printing and Print Services
Next: Foreign Function and Memory API: Arenas and Memory Segments
Related reading
- Printing in Java: Print Jobs, Multipage Printing and Print Services
- Raster Images in Java: ImageIO, BufferedImage Pixels and Image Filters
- Java 2D Strokes, Paint, Transforms, Clipping and Transparency
- Java 2D Rendering Pipeline: Shapes, Paths and Constructive Area Geometry
- Swing Trees: JTree, Tree Models, Nodes and Paths

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.