CodeBlanks Logo Icon CodeBlanks

native methods

Learn native method declaration with the native keyword.

The native keyword

The native keyword marks a method as implemented in a language other than Java (usually C or C++). Such a method has no body; it ends with a semicolon. At call time the JVM bridges to the native code through JNI (Java Native Interface).

native methods are used for operating system calls, legacy C libraries or hardware access. In modern Java 21 the FFM API is preferred for many cases; still, JNI remains common.

Declaring a native method

A native method is declared like this: native returnType methodName(params);. There is no body, only a semicolon. native can be combined with static. The method must belong to a class; Java has no free functions.

Example: class NativeOps { native int sum(int a, int b); }. Before this method is called, the matching native library must be loaded with System.loadLibrary; otherwise an UnsatisfiedLinkError is thrown.

Practice Declare a native method and print a marker

Define class NativeOps with a native int sum(int a, int b); method (no body). In Main's main method print System.out.println("native declared");. Do not call the native method; only declare it.

Starter code

Main.java
// Define the NativeOps class: native int sum(int a, int b)

// Define the Main class and print native declared in main

Sample solution

Main.java
class NativeOps {
    native int sum(int a, int b);
}

public class Main {
    public static void main(String[] args) {
        System.out.println("native declared");
    }
}

Expected output

native declared

Questions and answers

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

1 What is the defining trait of native methods?

  • They appear only in abstract classes
  • They have no body, implemented in another language Correct answer
  • They must be static
  • They are auto-tested

Explanation: A native method has no body; its implementation is written in C or C++.

2 Complete the native method declaration

Question
class NativeOps {
    native ____(int a, int b);
}
Answer
class NativeOps {
    native int sum(int a, int b);
}

Explanation: The declaration native int sum(int a, int b); is complete.

3 Match the JNI concepts

Term Meaning
native Bodyless method marker
System.loadLibrary Loads native library
JNIEnv C-side interface
javac -h Generates header

All lessons in Expert