O'Reilly logo

Ivor Horton's Beginning Java™ 2, JDK™ 5th Edition by Ivor Horton

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

5.13. Native Methods

It is possible to include in a class a method that is implemented in some other programming language, such as C or C++, external to the Java Virtual Machine. To specify such a method within a class definition, you use the keyword native in the declaration of the method. For example:

public native long getData();     // Declare a method that is not in Java

Of course, the method will have no body in Java since it is defined elsewhere, where all the work is done, so the declaration ends with a semicolon. The implementation of a native method will need to use an interface to the Java environment. The standard API for implementing native methods in C, for example, is called JNI—the Java Native Interface.

The major drawback to using native methods in Java is that your program will no longer be portable. Security requirements for applets embedded in web pages require that the code must all be written in Java-using native methods in an applet is simply not possible. Since the primary reasons for using Java are the portability of the code and the ability to produce applets, the need for you to add native methods to your Java programs will be minimal. I will therefore not delve any deeper into this topic.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required