What is a native implementation in Java?

dinsim picture dinsim · Feb 17, 2009 · Viewed 18.8k times · Source

If we look at the Java Object class then we can find some of the methods like:

public native int hashCode()
protected native Object clone()

What are these natives and how do these methods work?

Answer

Nick Fortescue picture Nick Fortescue · Feb 17, 2009

These methods are either Intrinsic or written outside Java in "native" code, that is, specific to the given machine.

The ones you mention are Intrinsic and part of the JDK but you can also write native methods yourself using the Java Native Interface (JNI). This would normally use C to write the methods, but a lot of other languages, such as python allow you to write methods this way fairly easily. Code is written this way either for performance, or because it needs to access platform specific infrastructure which cannot be done in plain java.

In the case of hashcode(), this is implemented by the JVM. This is because often the hashcode will be related to something only the JVM knows. On early JVMs this was related to the object's location in memory - on other JVMs the Object may move in memory, and so a more complicated (but still very fast) scheme may be used.