CodeBlanks Logo Icon CodeBlanks

JNIEnv

Learn the native call environment with JNIEnv.

The JNIEnv interface

The first parameter of every JNI C function is JNIEnv*. This pointer lets C talk to the JVM: calling Java methods, creating objects and converting arrays and strings all go through env->....

For static native methods the second parameter is jclass (the class); for instance methods it is jobject (this). Without it C would not know which class or object it works on.

C function naming

To match a C function with a Java method JNI uses a fixed name: Java_packageName_ClassName_methodName. Dots in the package become underscores. For example, NativeOps.sum maps to the C function Java_NativeOps_sum.

For overloaded methods a signature suffix (such as __II) is appended to avoid name clashes. This naming is the backbone of the JNI linking mechanism.

Practice Write the class that builds the C function name

Define class JniCall with String className and String method fields and a JniCall(String className, String method) constructor that assigns them. A String cName() method returns "Java_" + className + "_" + method. In main create JniCall c = new JniCall("NativeOps", "sum"); and print it with System.out.println(c.cName());.

Starter code

Main.java
// Define the JniCall class: className, method fields, constructor and cName method

// Main: create a JniCall instance and print the cName output

Sample solution

Main.java
class JniCall {
    String className;
    String method;
    JniCall(String className, String method) {
        this.className = className;
        this.method = method;
    }
    String cName() {
        return "Java_" + className + "_" + method;
    }
}

public class Main {
    public static void main(String[] args) {
        JniCall c = new JniCall("NativeOps", "sum");
        System.out.println(c.cName());
    }
}

Expected output

Java_NativeOps_sum

Questions and answers

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

1 Match the JNI parameter types

Term Meaning
JNIEnv* First parameter
jclass Class in static method
jobject this in instance method
jint int counterpart

2 Complete the C function name

Question
Java_____(JNIEnv* env, jclass cls, jint a, jint b)
Answer
Java_NativeOps_sum(JNIEnv* env, jclass cls, jint a, jint b)

Explanation: The C function is named Java_NativeOps_sum.

3 What is JNIEnv* for?

  • It compiles the class
  • It starts threads
  • It reads files
  • It lets C reach the JVM Correct answer

Explanation: Through JNIEnv* C calls Java methods and creates objects.

All lessons in Expert