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 keywordnative
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 {
System.loadLibrary("Calculator");
}
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));
}
}
8.6
public class MyClass {
public native void initializeLibraries() {
// Call some program here and do something else
}
}
Although this is the "last" keyword, you should learn about a new keyword in the Java Language, the Java Record.
Comments
Post a Comment