Previous | Next | Trail Map | Using the JNI to Integrate Native Code and Java Programs | Table of Contents


Step By Step

This lesson walks you through the steps necessary to integrate native code with Java programs.

This lesson implements the canonical "Hello World!" program. The "Hello World!" program has two Java classes. The first, called Main, implements the main() method for the overall program. The second, called HelloWorld, has one method, a native method, that displays "Hello World!". The implementation for the native method is provided in the C programming language.

Step 1: Write the Java Code

Create a Java class named HelloWorld that declares a native method. Also, write the main program that creates a HelloWorld object and calls the native method.

Step 2: Compile the Java Code

Use javac to compile the Java code that you wrote in Step 1.

Step 3: Create the .h File

Use javah to create a JNI-style header file (a .h file) from the HelloWorld Java class. The header file provides a function definition for the implementation of the native method displayHelloWorld() defined in HelloWorld Java class.

Step 4: Write the Native Method Implementation

Write the implementation for the native method in a native language source file. The implementation will be a regular function that's integrated with your Java class.

Step 5: Create a Shared Library

Use the C compiler to compile the .h file and the .c file that you created in Steps 3 and 4 into a shared library. In Windows 95/NT terminology, a shared library is called a dynamically loadable library (DLL).

Step 6: Run the Program

And finally, use java, the Java interpreter, to run the program.


Previous | Next | Trail Map | Using the JNI to Integrate Native Code and Java Programs | Table of Contents