Java Keywords (Part XXIV): native

Java keyword list

abstract continue for new switch
assert default goto* package synchronized
boolean do if private this
break double implements protected throw
byte else import public throws
case enum instanceof return transient
catch extends int short try
char final interface static void
class finally long strictfp volatile
const* float native super while
Keyword marked with an asterisk (*) are keywords that, although valid, are not used by programmers.

This is the last chapter of the Java Keyword series. This is probably the keyword I have used the least. In my 20 year career as a software developer, I have used this keyword once, and that was to make some addition to legacy code.

The keyword native is a method modifier. Basically, it is a keyword that can only be applied to methods. According to the Java Language Specification (JLS),

A method that is native is implemented in platform-dependent code, typically written in another programming language such as C.
When I mentioned earlier that I used this keyword once to make some addition to legacy code, I had to call out some DLL's from our Java application. The legacy code were actually the DLL's. We wanted to incorporate these libraries that were coded in C++ in our new Java application, instead of coding all these features from scratch.

How to use the keyword

All you need to do is include the keyword native after the method's access modifier. It is as simple as that. Most of the time, you will simply create a method without body like the one shown below.

public class MyClass {

    static {
    public native double add(double x, double y); // This method has no body because the Calculator code does the work.
    public static void main(String[] args) {
        System.out.println(new MyClass().add(3.2, 5.4));
If you had this Calculator program, running this code example would have displayed

You could also have native methods with method body.

public class MyClass {

    public native void initializeLibraries() {
        // Call some program here and do something else
But I believe this is a bit unusual.The first usage is by far the most common. And that's it. I hope you found it useful. See you next time.

Although this is the "last" keyword, you should learn about a new keyword in the Java Language, the Java Record.


Popular posts from this blog

Combining State and Singleton Patterns to Create a State-Machine

Exception Handling: File CRUD Operations Example

The Beauty of the Null Object Pattern