Scrivio Interview library
ConceptFoundations6 min read · updated 12 November 2026

What is JNI and what are the steps to call a C function from Java with it? What are its main drawbacks?

JNI, the Java Native Interface, lets Java code call functions written in C or C++ and lets that native code call back into Java. To use it we declare a native method in Java, generate a C header with javac -h, implement the C function following JNI's naming convention, build it into a shared library, load it with System.loadLibrary and call the method. Its main drawbacks are hand-written C glue code for every function, crashes in native code that kill the whole JVM, platform-specific builds, and the need to manage local and global references correctly to avoid leaks.

Why this question is asked

Most Java developers never write JNI, but many use it every day without knowing: compression, image processing, cryptography and database drivers often have a native part. When something goes wrong there, a JVM crash with a native frame in the log, we need to understand how the bridge works. Interviewers ask this to check that we know the mechanics and, more importantly, the risks, which explain why the JDK now offers the Foreign Function and Memory API. In this answer, we will recap what JNI is, build a small example step by step, look at references and exceptions, and go through the drawbacks.

1A Quick Recap of JNI

Java code runs on the JVM, isolated from the operating system's native libraries. JNI, the Java Native Interface, has been part of Java since 1.1 and is the official bridge. It works in both directions: Java can call a native function, and native code receives a pointer to a JNIEnv, a table of functions it can use to create Java objects, read fields, call Java methods and throw exceptions.

The bridge has a contract on each side. On the Java side, a method marked native has no body; its implementation lives in a native library. On the C side, a function with a specific name and signature implements it, and the JVM finds it when the library is loaded.

Step throughCalling a C function through JNI
  1. Declare a native method in Javastatic native int add(int a, int b);
  2. Generate the header with javac -hgives the exact C function name
  3. Write the C functionJava_com_example_MathLib_add(JNIEnv*, jclass, jint, jint)
  4. Build a shared librarylibmathlib.so, .dylib or .dll per platform
  5. Load it with System.loadLibrarysearched on java.library.path
  6. Call the method from JavaJVM jumps into the C code

6 steps in order. Play them, or step through them one at a time.

2Declare the Native Method

We start in Java. The native keyword says the method is implemented elsewhere, and a static block loads the library when the class is initialised.

Java
package com.example;
public class MathLib {
static {
System.loadLibrary("mathlib"); // looks for libmathlib.so (Linux), libmathlib.dylib (macOS), mathlib.dll (Windows)
}
public static native int add(int a, int b);
public static void main(String[] args) {
System.out.println(add(2, 3)); // 5
}
}

Notice that loadLibrary takes a name without prefix or extension; the JVM adds the platform's conventions and searches the directories in java.library.path. System.load takes a full path instead. If the library is not found, the call fails with UnsatisfiedLinkError, and the same error appears later if the library loads but the function name does not match.

3Generate the Header and Write the C Code

Since Java 10 the header is generated by javac itself with the -h option (the old javah tool was removed). The header contains the exact name and signature the JVM expects.

Shell
javac -h native/ -d classes/ src/com/example/MathLib.java
# writes native/com_example_MathLib.h with:
# JNIEXPORT jint JNICALL Java_com_example_MathLib_add(JNIEnv *, jclass, jint, jint);
/* native/mathlib.c */
#include "com_example_MathLib.h"
JNIEXPORT jint JNICALL Java_com_example_MathLib_add(JNIEnv *env, jclass cls, jint a, jint b) {
return a + b;
}
# Build on Linux (macOS uses include/darwin and -dynamiclib, Windows uses cl /LD)
gcc -shared -fPIC -I"$JAVA_HOME/include" -I"$JAVA_HOME/include/linux" \
-o libmathlib.so native/mathlib.c
java -Djava.library.path=. -cp classes com.example.MathLib # 5

The naming convention is Java_, then the fully qualified class name with dots replaced by underscores, then the method name. The first two parameters are always the JNIEnv pointer and either the class (for static methods) or the object (for instance methods). Java types map to C types such as jint, jlong and jstring. An alternative to the naming convention is to register functions explicitly with RegisterNatives from JNI_OnLoad.

4References and Exceptions: Where JNI Gets Hard

Simple numbers are easy. Objects are harder, because the garbage collector can move or free them, so native code never holds a raw pointer to a Java object. It holds a reference managed by the JVM. A local reference, which is what most JNI functions return, is valid only until the native method returns, and there is a limited number available at once. A global reference, created with NewGlobalRef, stays valid across calls and threads until we call DeleteGlobalRef.

Java
JNIEXPORT jstring JNICALL Java_com_example_Text_upper(JNIEnv *env, jclass cls, jstring s) {
const char *in = (*env)->GetStringUTFChars(env, s, NULL);
if (in == NULL) return NULL; /* OutOfMemoryError already pending */
char out[256];
/* ... copy and convert to upper case, checking the length ... */
(*env)->ReleaseStringUTFChars(env, s, in); /* forget this and we leak */
return (*env)->NewStringUTF(env, out);
}
/* Keeping a class across calls needs a global reference */
static jclass cachedClass;
cachedClass = (*env)->NewGlobalRef(env, localClass); /* must DeleteGlobalRef later */

Notice the pairs: every Get must have its Release, and every NewGlobalRef its DeleteGlobalRef, or memory leaks. Storing a local reference in a static variable and using it in a later call is a classic bug: the reference is invalid by then, and the JVM may crash much later. Creating many local references in a loop can exhaust the local reference table, so long loops call DeleteLocalRef or use PushLocalFrame. Exceptions also work differently: a Java exception thrown during a JNI call is only pending, and native code must check it with ExceptionCheck before continuing, otherwise it carries on in an invalid state.

5The Main Drawbacks

First, glue code. Every native function needs a C wrapper that converts arguments and results, written and maintained by hand. A library with 200 functions needs 200 wrappers, in C, reviewed by people who may not know C well.

Second, safety. Native code runs inside the JVM process without any of Java's protections. A bad pointer, a buffer overflow or a use of freed memory does not throw an exception; it crashes the whole JVM with a SIGSEGV and an hs_err_pid log file, taking every request in the process down with it.

Third, builds. The library must be compiled for each operating system and CPU: Linux x64, Linux ARM, macOS, Windows. Each needs its own toolchain in CI, and shipping means packaging and extracting the right binary at run time.

These are the reasons the JDK added the Foreign Function and Memory API, final in Java 22, which calls native functions directly from Java with bounds-checked memory and no C glue. Recent JDKs also print a warning when JNI is used without --enable-native-access, as part of making native access an explicit choice; check your version.

JNI drawbacks and why they hurt
DrawbackWhat it means in practice
C glue per functionMore code to write, review and keep in sync with Java
Native crashesA bad pointer kills the JVM, not just the request
Platform buildsOne binary per OS and CPU in CI and packaging
Reference managementLeaks or crashes if local and global refs are misused
Pending exceptionsNative code must check after JNI calls

6Follow-up questions

What is the difference between System.loadLibrary and System.load?

loadLibrary takes a short library name and searches java.library.path, adding the platform's prefix and extension. load takes an absolute file path and loads exactly that file. Libraries packaged inside a JAR are usually extracted to a temporary file and loaded with load.

Can native code call back into Java?

Yes. Through the JNIEnv it can find a class, look up a method ID with GetMethodID and call it with CallVoidMethod and similar functions. A native thread that the JVM did not create must first attach itself with AttachCurrentThread.

Why use JNI today if the FFM API exists?

Mostly for existing code and libraries that already use it, and for older JDKs. For new work on Java 22 and later, the FFM API is the recommended way to call native code.

7Conclusion

In this answer, we saw that JNI is the bridge that lets Java call native code and native code call back into Java. We declared a native method, generated the header with javac -h, implemented the function with JNI's naming convention, built a shared library, loaded it with System.loadLibrary and called it. Its drawbacks are C glue per function, native crashes that kill the JVM, platform-specific builds and careful local and global reference management, which is why the FFM API now exists.

What to say in the interviewAbout 80 seconds aloud

Open with

JNI is the Java Native Interface, the bridge between Java and native code, in both directions: Java can call a C function, and native code gets a JNIEnv pointer it can use to create objects, call Java methods or throw exceptions.

Then, if they want more

The steps are: declare a method with the native keyword in a Java class; run javac with -h to generate a header, which gives the exact function name, Java underscore, the class name with underscores, then the method name, taking JNIEnv and the class or object; implement that function in C; compile it into a shared library for each platform, like libmathlib.so; then call System.loadLibrary with the short name, which searches java.library.path, and call the method.

The drawbacks are real. Every function needs hand-written C glue. A bug in native code, like a bad pointer, crashes the whole JVM instead of throwing an exception. We need a build per OS and CPU.

And native code must manage references: local ones are only valid during the call, global ones must be deleted, every Get needs its Release, and pending exceptions must be checked. That is why the FFM API in Java 22 is now preferred.

About this answer

Last updated
12 November 2026
Versions it names
Java 22, Java 10
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "What is JNI and what are the steps to call a C function from Java with it? What are its...": https://scrivio-interview-library.netlify.app/java/foreign-memory-and-native/c682bf8bf7/