78

A native method has the same syntax as an abstract method, but where is it implemented?

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
niks
  • 1,063
  • 2
  • 9
  • 18

5 Answers5

146

What are native methods in Java and where should they be used?

Once you see a small example, it becomes clear:

Main.java:

public class Main {
    public native int intMethod(int i);
    public static void main(String[] args) {
        System.loadLibrary("Main");
        System.out.println(new Main().intMethod(2));
    }
}

Main.c:

#include <jni.h>
#include "Main.h"

JNIEXPORT jint JNICALL Java_Main_intMethod(
    JNIEnv *env, jobject obj, jint i) {
  return i * i;
}

Compile and run:

javac Main.java
javah -jni Main
gcc -shared -fpic -o libMain.so -I${JAVA_HOME}/include \
  -I${JAVA_HOME}/include/linux Main.c
java -Djava.library.path=. Main

Output:

4

Tested on Ubuntu 14.04 with Oracle JDK 1.8.0_45.

So it is clear that it allows you to:

  • call a compiled dynamically loaded library (here written in C) with arbitrary assembly code from Java
  • and get results back into Java

This could be used to:

  • write faster code on a critical section with better CPU assembly instructions (not CPU portable)
  • make direct system calls (not OS portable)

with the tradeoff of lower portability.

It is also possible for you to call Java from C, but you must first create a JVM in C: How to call Java functions from C++?

Example on GitHub for you to play with.

Community
  • 1
  • 1
Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
46

The method is implemented in "native" code. That is, code that does not run in the JVM. It's typically written in C or C++.

Native methods are usually used to interface with system calls or libraries written in other programming languages.

Laurence Gonsalves
  • 137,896
  • 35
  • 246
  • 299
  • you mean if i have a native method forName in my class, the implement of it is a part of system call. Should the native methods to be used same as name of the system calls – niks Sep 19 '13 at 17:02
  • 2
    Not exactly. If you have a method named "forName" in a class called "com.example.Foo" the C function that will get called will be named something like "Java_com_example_Foo_forName". That function could then in turn invoke system calls. See http://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/design.html for more details. – Laurence Gonsalves Sep 19 '13 at 17:07
  • if the native method is implemented with other name as in ur example Java_com_example_Foo_forName in C, how do we know that the name for the native method (forName) we have given is exactly used. I mean here is Java_com_example_Foo_forName has completely different name which can look like a local method in C which one can get confused in understanding it as an implementation of its own method rather than the implementation with the same name. what u have explained i got it clearly but I am unable to catch how does implementation goes part. – niks Sep 19 '13 at 17:37
  • In general, you can't tell what the native method will call without looking at the documentation and/or source, just like any other method. Just because it's called "forName" doesn't mean it will call a system call of that name, but one would hope the author would have used a reasonable naming convention. Incidentally, when I said they're used to interface with system calls, I did not mean to say that they are one-to-one with system calls, necessarily. Interfacing with system calls is just a common use of native methods. – Laurence Gonsalves Sep 19 '13 at 17:45
  • 2
    Say we want to call some system function, `baz`. First, create a class called `com.example.Foo` with native method `bar`. Then write a C function, `Java_com_example_Foo_bar` which calls `baz`. Compile and link that C function into a shared library (eg: `libquux.so` or `quux.dll`). Your Java code would have to invoke `System.loadLibrary(“quux”)` before the `bar` native method is invoked (or an `UnsatisfiedLinkError` will be thrown). I've made names different whenever allowed in this example, but in practice the class and library would have similar names, as would the function and method. – Laurence Gonsalves Sep 19 '13 at 17:56
  • spot on example Laurence got the concept cleared. – niks Sep 19 '13 at 18:07
16

I like to know where does we use Native Methods

Ideally, not at all. In reality some functionality is not available in Java and you have to call some C code.

The methods are implemented in C code.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
6

Java native code necessities:

  • h/w access and control.
  • use of commercial s/w and system services[h/w related].
  • use of legacy s/w that hasn't or cannot be ported to Java.
  • Using native code to perform time-critical tasks.

hope these points answers your question :)

Cjo
  • 1,265
  • 13
  • 19
  • What about I/O? Or does this go under "use of legacy s/w that hasn't or cannot be ported to Java". I wonder because the FileNotFoundException class has native I/O methods. – thz Mar 27 '17 at 14:43
  • @RnBandCrunk : yes you are correct. I/O is typically system-dependent, native methods must be used to implement those operations. – Cjo Mar 28 '17 at 11:41
4

Native methods allow you to use code from other languages such as C or C++ in your java code. You use them when java doesn't provide the functionality that you need. For example, if I were writing a program to calculate some equation and create a line graph of it, I would use java, because it is the language I am best in. However, I am also proficient in C. Say in part of my program I need to calculate a really complex equation. I would use a native method for this, because I know some C++ and I know that C++ is much faster than java, so if I wrote my method in C++ it would be quicker. Also, say I want to interact with another program or device. This would also use a native method, because C++ has something called pointers, which would let me do that.

Zac
  • 347
  • 3
  • 8