CodeBlanks Logo Icon CodeBlanks

C/C++ implementation

Learn JNI implementation with C/C++.

JNI type mapping

JNI represents Java types with signature letters on the C side: int → I, long → J, boolean → Z, void → V, String → Ljava/lang/String;. A method signature has the form (params)return.

For example, int sum(int a, int b) has the signature (II)I. These signatures are visible with javap -s and are appended to the C function name for overloading.

Loading the native library

Before a native method is called the native library must be loaded: System.loadLibrary("nativeops");. This call is usually placed in a static block so the library is ready when the class loads. The library is searched along java.library.path.

If the library is not found an UnsatisfiedLinkError is thrown. Cross-platform projects build a separate library for each operating system.

Practice Write the type mapper and native class

Define class TypeMapper with a static String jni(String t) method that uses a switch to return int → "I", long → "J", boolean → "Z", void → "V". Define class NativeOps with native int sum(int a, int b); and a static block calling System.loadLibrary("nativeops"); (wrapped in try). In main print System.out.println("(" + TypeMapper.jni("int") + TypeMapper.jni("int") + ")" + TypeMapper.jni("int"));.

Starter code

Main.java
// Define the TypeMapper class: static String jni(String t) returns I/J/Z/V via switch
// Define the NativeOps class: native int sum(int a, int b) and a static block with System.loadLibrary

// main: print the (II)I signature

Sample solution

Main.java
class TypeMapper {
    static String jni(String t) {
        return switch (t) {
            case "int" -> "I";
            case "long" -> "J";
            case "boolean" -> "Z";
            case "void" -> "V";
            default -> "?";
        };
    }
}

class NativeOps {
    native int sum(int a, int b);
    static {
        try { System.loadLibrary("nativeops"); } catch (UnsatisfiedLinkError e) { }
    }
}

public class Main {
    public static void main(String[] args) {
        System.out.println("(" + TypeMapper.jni("int") + TypeMapper.jni("int") + ")" + TypeMapper.jni("int"));
    }
}

Expected output

(II)I

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is the JNI signature letter of int?

  • I Correct answer
  • J
  • Z
  • L

Explanation: int is shown with the letter I in JNI signatures.

2 Complete the method signature

Question
String sig = "(____";
Answer
String sig = "(II)I";

Explanation: The signature (II)I means int sum(int, int).

3 Match the type mapping

Term Meaning
int I
long J
boolean Z
String Ljava/lang/String;

All lessons in Expert