Scrivio Interview library
CodingIntermediate6 min read · updated 12 November 2026

Using the Foreign Function and Memory API (final in Java 22), call the C library function strlen on a Java string. Describe the classes you use.

We get the native linker with Linker.nativeLinker(), find strlen's address with linker.defaultLookup().find("strlen"), and create a MethodHandle with linker.downcallHandle using FunctionDescriptor.of(ValueLayout.JAVA_LONG, ValueLayout.ADDRESS). Then, inside a confined Arena, arena.allocateFrom("hello") copies the Java string into native memory as a NUL-terminated C string, and (long) strlen.invokeExact(segment) returns 5. Closing the arena frees the native string, and jextract can generate this kind of binding automatically from C headers.

Why this question is asked

Calling strlen is the hello world of the Foreign Function and Memory API: small enough to read in one go, but it touches every important class, the linker, symbol lookup, function descriptors, method handles, arenas and memory segments. Interviewers use it to see whether we can write real FFM code and explain what each piece does, which is the basis for calling any native library without JNI. In this answer, we will recap the C function we are calling, write the complete program, then walk through each class in the order we use it, look at the mistakes that commonly break it, and finish with jextract.

1A Quick Recap of strlen and What We Need

strlen is a function in the C standard library with the signature size_t strlen(const char *s). It takes a pointer to a C string, a sequence of bytes ending with a zero byte (called the NUL terminator), and returns how many bytes come before that zero. On the 64-bit platforms Java runs on, size_t is a 64-bit unsigned integer.

To call it from Java we need four things: the function's address in memory, a description of its parameters and return type so the JVM knows how to pass values, a Java handle we can invoke, and a C string in native memory, because a Java String lives on the heap in a different format and the GC may move it.

2The Complete Program

Here is the whole thing. It compiles and runs on Java 22 and later without any flags, though it prints a native access warning unless we grant access, which we will come back to.

Java
import java.lang.foreign.*;
import java.lang.invoke.MethodHandle;
public class StrLen {
public static void main(String[] args) throws Throwable {
Linker linker = Linker.nativeLinker(); // the platform's C calling convention
MemorySegment addr = linker.defaultLookup() // symbols in the standard C library
.find("strlen")
.orElseThrow(); // address of strlen
MethodHandle strlen = linker.downcallHandle(
addr,
FunctionDescriptor.of(ValueLayout.JAVA_LONG, // returns size_t (64-bit)
ValueLayout.ADDRESS)); // takes const char *
try (Arena arena = Arena.ofConfined()) {
MemorySegment s = arena.allocateFrom("hello"); // 6 bytes: h e l l o \0
long n = (long) strlen.invokeExact(s);
System.out.println(n); // 5
System.out.println(s.byteSize()); // 6
} // native string freed here
}
}
// java --enable-native-access=ALL-UNNAMED StrLen.java
// 5
// 6
Step throughWhat happens during the call
Java codeArenaMethod handlestrlen in libc
allocateFrom("hello")
segment: 6 bytes, hello plus NUL
invokeExact(segment)
call with the segment's address in a register
5 (size_t)
5 as a Java long
close(): native memory freed

7 messages in order. Play them, or step through them one at a time.

The method handle does the work JNI's C wrapper used to do.

Notice that the result is 5, while the segment is 6 bytes long. The extra byte is the NUL terminator that allocateFrom added, which is exactly what strlen looks for.

3Linker and SymbolLookup: Finding the Function

Linker.nativeLinker() returns the linker for the platform we run on. It knows the C calling convention: which registers hold which arguments and where the return value comes back, for example on Linux x64 or macOS on ARM.

defaultLookup() returns a SymbolLookup, an object that maps names to addresses, for libraries the linker treats as always available, which on the common platforms includes the C standard library. find("strlen") returns an Optional of MemorySegment: a zero-length segment whose address is the function's entry point. For our own libraries we would use SymbolLookup.libraryLookup(path, arena) instead, which loads the library and ties it to an arena's lifetime.

4FunctionDescriptor and the Downcall Handle

A FunctionDescriptor describes the C signature with memory layouts. FunctionDescriptor.of(ret, args...) takes the return layout first, then the parameter layouts; for a void function we would use FunctionDescriptor.ofVoid(args...). ValueLayout.JAVA_LONG matches a 64-bit integer, and ValueLayout.ADDRESS matches a pointer.

linker.downcallHandle(address, descriptor) builds a MethodHandle, a Java object we can invoke like a function pointer, whose Java type is derived from the descriptor: here (MemorySegment)long. A downcall is a call from Java down into native code; the opposite, a function pointer that C can call back into Java, is an upcall. downcallHandle is a restricted method, because a wrong descriptor can crash the JVM, which is why the JDK prints a warning without --enable-native-access.

5Arena, allocateFrom and invokeExact

Arena.ofConfined() creates an arena owned by the current thread. arena.allocateFrom("hello") encodes the string in UTF-8, allocates a segment one byte longer and writes the bytes plus a zero terminator. In Java 21's preview the method was called allocateUtf8String; in the final API of Java 22 it is allocateFrom. When the try block ends, close() frees the segment, and any later access to s throws IllegalStateException.

invokeExact calls the handle, and as its name says it requires the exact types. The argument must be a MemorySegment and the result must be cast to long, because the handle's type is (MemorySegment)long.

Java
int bad = (int) strlen.invokeExact(s);
// WrongMethodTypeException: handle's method type (MemorySegment)long but found (MemorySegment)int
Object alsoBad = strlen.invokeExact(s);
// WrongMethodTypeException: the cast is part of the call site type
long ok = (long) strlen.invoke(s); // invoke adapts types, at a small cost; invokeExact is preferred

The cast in front of invokeExact is not an ordinary cast; it tells javac what return type to compile into the call site, and the JVM checks it against the handle's type. That strictness lets the JIT turn the call into an almost direct native call.

6Generating Bindings With jextract

Writing descriptors by hand is fine for one function, but error-prone for a real library with hundreds of functions and structs. jextract, a separate tool from Project Panama, reads C header files and generates Java classes with ready-made method handles, layouts and wrapper methods.

Java
jextract --output src --target-package org.libc /usr/include/string.h
// generated code lets us call it like a Java method:
try (Arena arena = Arena.ofConfined()) {
long n = string_h.strlen(arena.allocateFrom("hello")); // 5
}

The generated code uses exactly the classes we wrote by hand above, so understanding the manual version helps us read and debug the generated bindings.

7Follow-up questions

Why ValueLayout.JAVA_LONG for size_t?

Because size_t is 64 bits on the 64-bit platforms Java supports, and JAVA_LONG is a 64-bit layout. size_t is unsigned while long is signed, but string lengths never reach the range where that matters. For portability across platforms with different C type sizes, linker.canonicalLayouts().get("size_t") returns the right layout.

What happens if we pass a Java String directly?

The handle's type requires a MemorySegment, so passing a String fails with WrongMethodTypeException or a ClassCastException. The string must be copied to native memory, because C expects bytes ending with zero at a stable address, and heap objects have neither.

Do we need --enable-native-access?

On Java 22 and later the code runs without it but prints a warning, because downcallHandle is a restricted method. We should grant it explicitly, for the module or for ALL-UNNAMED on the class path, as future releases are expected to deny it by default.

8Conclusion

In this answer, we called strlen with the FFM API: Linker.nativeLinker() and defaultLookup().find("strlen") locate the function, FunctionDescriptor.of(JAVA_LONG, ADDRESS) describes its signature, downcallHandle turns it into a MethodHandle, and inside a confined Arena allocateFrom creates the C string, invokeExact returns 5, and closing the arena frees the memory. jextract can generate these bindings from C headers.

What to say in the interviewAbout 70 seconds aloud

Open with

I would start with Linker.nativeLinker(), which knows the platform's C calling convention, and use its defaultLookup to find strlen, which returns an Optional of a MemorySegment holding the function's address, so I call orElseThrow.

Then, if they want more

Then I describe the C signature with FunctionDescriptor.of: the return layout first, ValueLayout.JAVA_LONG because size_t is 64 bits, then the parameter, ValueLayout.ADDRESS for the char pointer. linker.downcallHandle with the address and descriptor gives me a MethodHandle of type MemorySegment to long.

To get a C string, I open a confined Arena in try-with-resources and call arena.allocateFrom with hello, which writes the UTF-8 bytes plus a NUL terminator into a six-byte native segment. Then long n equals, with a cast to long, strlen.invokeExact of the segment, which gives 5. invokeExact needs the exact types, so the cast matters.

When the try block ends the arena closes and frees the string; any later access throws IllegalStateException. downcallHandle is a restricted method, so I would run with --enable-native-access to avoid the warning. For a real library I would let jextract generate these bindings from the C headers.

About this answer

Last updated
12 November 2026
Versions it names
Java 22, Java 21
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 "Using the Foreign Function and Memory API (final in Java 22), call the C library...": https://scrivio-interview-library.netlify.app/java/foreign-memory-and-native/20c047514d/