encyclopegia.org

Java Native Interface

The Java Native Interface (or Native Method Interface) is a foreign function interface designed for non-Java programming frameworks. The JNI enables Java code to call and be called by native code (i.e. any code using the JNIEnv and interfacing through the C application binary interface), native applications (programs specific to a hardware and operating system platform) and libraries written in other languages such as C, C++ and assembly. Java 22 introduces the Foreign Function and Memory API, which can be seen as the successor to Java Native Interface.

The Java Native Interface (or Native Method Interface) is a foreign function interface designed for non-Java programming frameworks. The JNI enables Java code to call and be called by native code (i.e. any code using the JNIEnv and interfacing through the C application binary interface), native applications (programs specific to a hardware and operating system platform) and libraries written in other languages such as C, C++ and assembly. Java 22 introduces the Foreign Function and Memory API, which can be seen as the successor to Java Native Interface. The JNI framework allows native code to manipulate and consume Java objects. A native method (marked by the keyword native in Java) can create Java objects and inspect and use these objects to perform its tasks. A native method can also inspect and use objects created by Java application code. An application that relies on JNI loses the platform portability Java offers (a partial workaround is to write a separate implementation of JNI code for each platform and have Java detect the operating system and load the correct one at runtime). Not only can native code interface with Java, it can also draw on a Java , which is possible with the Java AWT Native Interface, available since J2SE 1.3. JNI also allows direct access to assembly, without a C bridge. Accessing Java applications from assembly is possible in the same way. The JNI is the entry point between languages used to begin the JVM startup. ifdef __cplusplus class _jobject {}; class _jclass : public _jobject {}; // ... typedef _jobject *jobject; typedef _jclass *jclass; // ... else struct _jobject; // ... typedef struct _jobject *jobject; typedef jobject jclass; // ... endif Here, all Java reference types are defined as opaque empty types which act as handles to Java objects. These types should not be dereferenced. Additionally, the following opaque types are used as handles: Note however that jfieldID and jmethodID are just opaque handles, and do not correspond to java.lang.reflect.Field / java.lang.reflect.Method . // jni.h file struct JNINativeInterface_; struct JNIEnv_; ifdef __cplusplus typedef JNIEnv_ JNIEnv; else typedef const struct JNINativeInterface_ *JNIEnv; endif JNIEnv is used to access the structure of functions (array of function pointers), and each function being identifiable by a unique pointer. According to the programming language, C or C++, the implementation can be a little different. For example, in C: // jni.h file struct JNINativeInterface_ { jint (JNICALL *GetVersion) // JNICALL declaration of a pointer to identify the specific function; (JNIEnv *env); // Parameter env is a pointer to the JNIEnv pointer, the pointer-to-pointer; jclass (JNICALL *DefineClass) (JNIEnv *env, const char *name); jclass (JNICALL *FindClass) (JNIEnv *env, const char *name); // Others functions pointers... } extern "C" { JNIEXPORT void JNICALL Java_ClassName_MethodName (JNIEnv* env, jobject obj, jstring javaString) { const char* nativeString = env->GetStringUTFChars(javaString, 0); // Do something with the nativeString env->ReleaseStringUTFChars(javaString, nativeString); } } The env pointer is a structure that contains the interface to the JVM. It includes all of the functions necessary to interact with the JVM and to work with Java objects. Anything that Java code can do can be done using JNIEnv . The argument obj is a reference to the Java object inside which this native method has been declared. Native data types can be mapped to/from Java data types. For compound types, such as objects, arrays and strings, the native code must explicitly convert the data by calling methods in the JNIEnv . A JNI environment pointer ( JNIEnv* ) is passed as an argument for each native function mapped to a Java method, allowing for interaction with the JNI environment within the native method. This JNI interface pointer can be stored, but remains valid only in the current thread. Other threads must first call AttachCurrentThread() to attach themselves to the VM and obtain a JNI interface pointer. Once attached, a native thread works like a regular Java thread running within a native method. The native thread remains attached to the VM until it calls DetachCurrentThread() to detach itself. The JNI framework does not provide any automatic garbage collection for non-JVM memory resources allocated by code executing on the native side. Consequently, native code is responsible explicitly releasing all acquired resources. On Linux and Solaris platforms, if the native code registers itself as a signal handler, it can intercept signals intended for the JVM. A chain of responsibility can be used to allow native code to interoperate with the JVM. On Windows platforms, Structured Exception Handling (SEH) may be employed to wrap native code in SEH try / catch blocks so as to capture machine (CPU/FPU) generated software interrupts (such as null pointer dereferences and divide-by-zero operations), and to handle these situations before the interrupt is propagated back up into the JVM (i.e. Java side code). The encoding used for the NewStringUTF() , GetStringUTFLength() , GetStringUTFChars() , ReleaseStringUTFChars() and GetStringUTFRegion() functions is "modified UTF-8", which is not valid UTF-8 for all inputs, but a different encoding. The null character (U+0000) and codepoints not on the Basic Multilingual Plane (greater than or equal to U+10000, i.e. those represented as surrogate pairs in UTF-16) are encoded differently in modified UTF-8. Many programs actually use these functions incorrectly and treat the UTF-8 strings returned or passed into the functions as standard UTF-8 strings instead of modified UTF-8 strings. Programs should use the NewString() , GetStringLength() , GetStringChars() , ReleaseStringChars() , GetStringRegion() , GetStringCritical() and ReleaseStringCritical() functions, which use UTF-16LE encoding on little-endian architectures and UTF-16BE on big-endian architectures, and then use a UTF-16 to UTF-8 conversion routine. For example, the following demonstrates a native implementation of a Java method HelloJNI::sayHello() : include include JNIEXPORT void JNICALL Java_HelloJNI_sayHello(JNIEnv* env, jobject obj) { printf("Hello from C!\n"); } Then, in Java, the function is called like so: public class HelloJNI { static { // "hello" refers to libhello.so on Linux System.loadLibrary("hello"); // System.load() is other way to load a library. } public native void sayHello(); public static void main(String[] args) { new HelloJNI().sayHello(); } } Java 22 introduced the Foreign Function and Memory API, located in which can be seen as a sort of successor to the Java Native Interface. It has a simpler interface and generally requires less boilerplate than JNI, due to no longer requiring the inclusion of in the foreign library to invoke, and Foreign Function and Memory API abstracts away the usage of the native keyword completely. It supports region-based memory management. The class java.lang.foreign.MemorySegment models a contiguous segment of memory which can lie inside or outside the JVM heap, and a java.lang.foreign.MemorySegment is allocated using a java.lang.foreign.Arena which controls the lifetime of the region of memory backing its allocated segment of memory. The java.lang.foreign.Arena offers the following arena kinds: package org.wikipedia.examples; import java.lang.foreign.Arena; import java.lang.foreign.MemorySegment; import java.lang.foreign.ValueLayout; public class ForeignMemoryExample { public static void main(String[] args) { try (Arena arena = Arena.ofConfined()) { MemorySegment segment = arena.allocate(5 * Double.BYTES); for (int i = 0; i In a sense, Java Foreign Function and Memory API allows for direct memory allocation outside the JVM heap (i.e. the operating system heap), through Arena.allocate() and MemorySegment.allocateNative() which allocate raw memory directly, while Arena.close() and MemorySegment.close() are used to deallocate/release the memory segment. As a foreign function interface, the classes java.lang.foreign.Linker is offered for accessing between foreign functions from Java (to and from), java.lang.foreign.SymbolLookup for retrieving the address of a symbol in a library, and java.lang.foreign.FunctionDescriptor for modelling a foreign function signature. package org.wikipedia.examples; import java.lang.foreign.Arena; import java.lang.foreign.FunctionDescriptor; import java.lang.foreign.Linker; import java.lang.foreign.MemorySegment; import java.lang.foreign.SymbolLookup; import java.lang.foreign.ValueLayout; import java.lang.invoke.MethodHandle; public class ForeignFunctionExample { public static void main(String[] args) throws Throwable { Linker linker = Linker.nativeLinker(); SymbolLookup stdlib = linker.defaultLookup(); MethodHandle printf = linker.downcallHandle( stdlib.findOrThrow("printf"), FunctionDescriptor.of(ValueLayout.JAVA_INT, ValueLayout.ADDRESS) ); MethodHandle strlen = linker.downcallHandle( stdlib.findOrThrow("strlen"), FunctionDescriptor.of(ValueLayout.JAVA_LONG, ValueLayout.ADDRESS) ); try (Arena arena = Arena.ofConfined()) { MemorySegment formatString = arena.allocateUtf8String("Hello, %s!\n"); MemorySegment argString = arena.allocateUtf8String("World"); printf.invokeExact(formatString, argString); // prints "Hello, World!" long len = (long)strlen.invokeExact(formatString); // len = 5 } } } Layouts are modelled by java.lang.foreign.ValueLayout , which consists of: Primitives receive ValueLayout.JAVA_* layouts when mapped to their native types, while pointer types use ValueLayout.ADDRESS (for instance char* , int** or struct Point* ). Additionally, the constant MemorySegment.NULL (of type java.lang.foreign.MemorySegment ) is a zero-length native segment representing a null address ( nullptr ), equivalent to MemorySegment.ofAddress(0) . Java offers additional methods to express more complicated native types. For instance, the following native types struct Point { int x; long y; }; union Choice { float a; int b; }; receive the following layouts: import java.lang.foreign.MemoryLayout; import java.lang.foreign.StructLayout; import java.lang.foreign.UnionLayout; StructLayout pointLayout = MemoryLayout.structLayout( ValueLayout.JAVA_INT.withName("x"), MemoryLayout.paddingLayout(4), ValueLayout.JAVA_LONG.withName("y") }; UnionLayout choiceLayout = MemoryLayout.unionLayout( ValueLayout.JAVA_FLOAT.withName("a"), ValueLayout.JAVA_INT.withName("b") );

References

  1. Java Native Interface · retrieved 2026-11-23 · rev 1371632371
    Cite this reference

    MLA "Java Native Interface." 2026-11-23. https://en.wikipedia.org/w/index.php?oldid=1371632371. Accessed 23 November 2026.

    Chicago "Java Native Interface." 2026-11-23. https://en.wikipedia.org/w/index.php?oldid=1371632371.

    APA encyclopegia.org. (2026). Java Native Interface. Retrieved November 23, 2026, from https://en.wikipedia.org/w/index.php?oldid=1371632371

Cite this article

MLA

"Java Native Interface." encyclopegia.org, 2026, https://encyclopegia.org/wiki/java-native-interface. Accessed 23 November 2026.

Chicago

"Java Native Interface." encyclopegia.org. Accessed November 23, 2026. https://encyclopegia.org/wiki/java-native-interface.

APA

encyclopegia.org. (2026). Java Native Interface. Retrieved November 23, 2026, from https://encyclopegia.org/wiki/java-native-interface

Accessed November 23, 2026 · CC BY-SA 4.0 · citation page · JSON

Claims

PredicateValueSource
definitiona foreign function interface designed for non-Java programming frameworks.article body

Related articles

Egyptology

stub · references available

ZanZarah: The Hidden Portal

stub · references available

AZERTY

stub · references available

Arkady and Boris Strugatsky

stub · references available

Adelbert von Chamisso

stub · references available

Patrice de MacMahon

stub · references available
CC BY-SA 4.0 · tier1-factual · https://en.wikipedia.org/w/index.php?oldid=1371632371 · 0.55 · snapshot java-native-interface-020276-569c10b24ed61657 · QID Q168492

Cite · JSON · Search

Related services and records

Services

  • Estate — measured countries, lanes and facts
  • Intel — live corroborated events
  • Legal — statutes, cases and citations
  • Encyclopedia — articles with inline sources
  • Space — launches, satellites and orbits
  • Search — federated search and reports
  • Pass — passport account and SSO
  • Corpora — read-only corpus origins
  • e01 — self-hosted corpora and tools

Text and metadata only; each target carries its own sources. Missing data is published as no-data, never estimated.