DEV Community

Rajesh Bhola
Rajesh Bhola

Posted on

Part 4 - native Keyword: JNI, Native Methods

Most Java developers use the native keyword only a few times in their careers, yet it remains a popular Java interview topic.

Have you ever wondered how Java can:

  • Access operating system APIs?
  • Communicate with hardware devices?
  • Use existing C or C++ libraries?
  • Call methods like System.currentTimeMillis() or Object.hashCode() that are implemented outside Java?

The answer is the native keyword.

In this article, you'll learn:

  • What native methods are
  • Why Java needs native methods
  • What JNI (Java Native Interface) is
  • How native methods work
  • Rules and restrictions
  • Illegal modifier combinations
  • Advantages and disadvantages
  • Common interview questions

What is the native Keyword?

The native keyword tells the JVM that the implementation of a method is written in another programming language, such as:

  • C
  • C++
  • Assembly (rare)

Instead of Java providing the method body, the implementation exists in a native library.

The native modifier is applicable only to methods.

Applicable To Allowed?
Method
Class
Variable
Constructor

Why Do We Need Native Methods?

Java is designed to be platform-independent.

However, some operations require direct interaction with the operating system or hardware.

Examples include:

  • Accessing device drivers
  • Reading system-level information
  • Communicating with printers or scanners
  • Using high-performance image or audio processing libraries
  • Reusing existing C/C++ libraries without rewriting them in Java

Instead of rewriting everything in Java, we can call native code.


What is JNI?

JNI stands for:

Java Native Interface

JNI is a bridge that allows Java code to communicate with native code.

Java Application
        │
        ▼
Java Native Interface (JNI)
        │
        ▼
Native Library (.dll / .so / .dylib)
        │
        ▼
Operating System / Hardware
Enter fullscreen mode Exit fullscreen mode

JNI handles communication between Java and native languages.


Syntax

A native method contains only its declaration.

It does not contain a method body.

public native void connectDevice();
Enter fullscreen mode Exit fullscreen mode

Notice the semicolon (;).


Why Doesn't a Native Method Have a Body?

The implementation already exists in an external native library.

Java only declares the method signature.

The JVM finds the corresponding implementation at runtime.


Basic Example

class DeviceManager {

    static {
        System.loadLibrary("deviceLibrary");
    }

    public native void connect();

    public static void main(String[] args) {

        DeviceManager manager = new DeviceManager();
        manager.connect();

    }

}
Enter fullscreen mode Exit fullscreen mode

Step-by-Step Explanation

Step 1

The JVM loads the DeviceManager class.

Step 2

The static block executes.

Step 3

System.loadLibrary("deviceLibrary") loads the native library.

Step 4

When connect() is called, the JVM delegates execution to the native implementation.


What Does System.loadLibrary() Do?

Before a native method can execute, its implementation must be loaded.

Example:

System.loadLibrary("deviceLibrary");
Enter fullscreen mode Exit fullscreen mode

Depending on the operating system, the JVM loads files such as:

Operating System Typical Library Format
Windows .dll
Linux .so
macOS .dylib

Once loaded, Java can invoke native methods from that library.


Rule 1: Native Methods Must End with a Semicolon

Correct:

public native void processImage();
Enter fullscreen mode Exit fullscreen mode

Incorrect:

public native void processImage() {

}
Enter fullscreen mode Exit fullscreen mode

Compile-Time Error

native methods cannot have a body
Enter fullscreen mode Exit fullscreen mode

Why?

The implementation already exists outside Java.


Rule 2: Native Methods Are Applicable Only to Methods

Incorrect:

native class DeviceManager {

}
Enter fullscreen mode Exit fullscreen mode

Compile-Time Error

modifier native not allowed here
Enter fullscreen mode Exit fullscreen mode

Rule 3: Native Methods Can Be Inherited

Example:

class Parent {

    public native void connect();

}

class Child extends Parent {

}
Enter fullscreen mode Exit fullscreen mode

The child class inherits the native method.


Rule 4: Native Methods Can Be Overloaded

Example:

class Printer {

    public native void print();

    public native void print(String documentName);

}
Enter fullscreen mode Exit fullscreen mode

Method overloading works exactly as it does for regular Java methods.


Rule 5: Native Methods Can Be Overridden

Example:

class Parent {

    public native void display();

}

class Child extends Parent {

    @Override
    public void display() {

        System.out.println("Java implementation");

    }

}
Enter fullscreen mode Exit fullscreen mode

This is legal.

The child provides a Java implementation instead of using the native one.


Illegal Combination: abstract native

An abstract method says:

"No implementation exists."

A native method says:

"Implementation already exists outside Java."

These two ideas contradict each other.

Incorrect:

public abstract native void process();
Enter fullscreen mode Exit fullscreen mode

Compile-Time Error

illegal combination of modifiers: abstract and native
Enter fullscreen mode Exit fullscreen mode

Illegal Combination: native strictfp

strictfp specifies how floating-point calculations should be performed.

A native method executes outside the JVM.

The JVM cannot guarantee that external code follows IEEE 754 rules.

Therefore:

public native strictfp void calculate();
Enter fullscreen mode Exit fullscreen mode

is illegal.

Compile-Time Error

illegal combination of modifiers: native and strictfp
Enter fullscreen mode Exit fullscreen mode

Advantages of Native Methods

1. Better Performance

Performance-critical operations can leverage optimized native libraries.


2. Access to Existing Libraries

Organizations can reuse mature C/C++ libraries instead of rewriting them.


3. Hardware Communication

Native methods enable interaction with hardware and operating system features.


Disadvantages of Native Methods

1. Platform Dependence

Native libraries are operating-system specific.

A Windows .dll cannot run on Linux.


2. More Complex Deployment

Applications must include the required native libraries.


3. Reduced Portability

Using native code weakens Java's "Write Once, Run Anywhere" philosophy.


Common Beginner Mistakes

Mistake 1: Adding a Body to a Native Method

Incorrect:

public native void connect() {

}
Enter fullscreen mode Exit fullscreen mode

Native methods should end with a semicolon.


Mistake 2: Forgetting to Load the Native Library

Without System.loadLibrary(), the JVM cannot locate the native implementation.

At runtime, this typically results in an UnsatisfiedLinkError.


Mistake 3: Assuming Native Methods Are Faster in Every Case

Crossing the JNI boundary introduces overhead.

Native methods should be used only when necessary.


Mistake 4: Thinking Native Methods Break Inheritance

Native methods participate in inheritance, overloading, and overriding just like regular methods.


Best Practices

  • Use native methods only when Java cannot meet your requirements.
  • Keep the JNI layer as small as possible.
  • Validate all inputs before passing data to native code.
  • Avoid exposing native methods as part of your public API unless necessary.
  • Document platform-specific dependencies clearly.
  • Prefer pure Java solutions whenever practical.

Interview Questions

1. What is a native method?

A native method is a Java method whose implementation is written in a non-Java language, such as C or C++.

Why interviewers ask

To verify your understanding of Java's interaction with external code.


2. What is JNI?

JNI (Java Native Interface) is the bridge between Java code and native code.


3. Why don't native methods have a body?

Because their implementation exists in an external native library.


4. Can native methods be overloaded?

Yes.


5. Can native methods be overridden?

Yes.

A child class can provide its own Java implementation.


6. Why is abstract native illegal?

Because abstract requires an implementation in a subclass, while native already assumes an external implementation exists.


7. Why is native strictfp illegal?

Because the JVM cannot guarantee IEEE 754 floating-point behavior for code executing outside the JVM.


Quick Memory Trick 🧠

Remember JNI:

J → Java Declaration

N → Native Implementation

I → Interface (Bridge)
Enter fullscreen mode Exit fullscreen mode

Think of JNI as a bridge connecting Java with the native operating system.


Key Takeaways

  • native is applicable only to methods.
  • Native methods are implemented outside Java, typically in C or C++.
  • Native methods do not have a Java method body.
  • JNI enables communication between Java and native libraries.
  • Native methods support inheritance, overloading, and overriding.
  • abstract native and native strictfp are illegal modifier combinations.
  • Native methods provide access to hardware, operating system APIs, and legacy libraries.
  • Excessive use of native code reduces Java's platform independence.

If you found this guide helpful, leave a ❤️ and follow for more beginner-friendly Java tutorials, interview questions, and practical coding examples.

Happy Coding!

Top comments (0)