Jni Interview Questions in Java

We have compiled most frequently asked Java J2EE Interview Questions which will help you with different expertise levels.

Java J2EE Interview Questions on Jni

Question 1.
What are native methods? What purpose do they serve?
Answer:
Although it is rare, occasionally you may want to call a subroutine that is written in a language other than Java. Typically, such a subroutine exists as executable code for the CPU and environment in which you are working – that is, native code. For instance, you may want to. calla native code subroutine to achieve faster execution time, or, you may want to use a specialized, third-party library, such as a statistical package. Such subroutines are called native methods.

Question 2.
Java programs are compiled to bytecode, which is then interpreted (or compiled on the fly) by the Java run-time system, so how is it possible to call a native method from within your Java program?
Answer:
Java provides the native keyword, which is used to declare native code methods. Once declared, these methods can be called from inside your Java program just as you call any other Java method.

Question 3.
How do you declare a native method?
Answer:
To declare a native method, precede the method with the ‘native’ modifier, but do not define anybody, i.e. content, for the method, e.g.

public native void my_method( );

Question 4.
What are the problems faced with native methods? Or, why should the use of native methods be restricted?
Answer:
Native methods seem to offer great promise since they enable you to gain access to an existing base of library routines. Moreover, they offer the possibility of faster run-time execution. However, the use of native methods should be restricted since they render your Java program non-portable and pose significant security risks elaborated as under:-

  • Potential Security Risk: Since a native method executes actual machine code, it can gain access to any part of the host system, i.e. native code is not confined to the Java execution environment. This could allow a virus infection, for instance. It is for this reason that applets cannot use native methods. Also, the loading of DLLs can be restricted, and their loading is subject to the approval of the security manager.
  • Loss of Portability: Since the native code is contained in a DLL, it must be present on the machine that is executing the Java program. Furthermore, since each native method is dependent on the CPU and operating system, each DLL is inherently non-portable. Thus, a Java application that uses native methods will be able to run only on the machine for which a compatible DLL has been installed.

Question 5.
Can applets use native methods? Why or why not?
Answer:
Since a native method poses a potential security risk such as a virus infection (refer to the previous problem), applets cannot use native methods at all.

Question 6.
What do you understand by JNI?
Answer:
After you declare a native method, you must write the native method and follow a rather complex series of steps to link it with your Java code. Most native methods are written in C. The mechanism used to integrate C code with a Java program is known as the Java Native Interface (JNI).

Question 7.
Illustrate the use of JNI with a suitable example.
Answer:
Consider the following native method called my_method( ):

// A simple example using a native method
public class MyNative
{
   int i;
   public static void main(String args[ ])
   {
      MyNative mn = new MyNative( );
      mn.i = 100;
      System.out.printlnC'Before native method, mn.i = " + mn.i);
      mn.my_method( ); //call a native method
      System.out.printlnC After native method, mn.i = " + mn.i);
}
// DECLARE NATIVE METHOD public native void my_method();
// LOAD DLL that contains static method
static
  {
    System.loadLibraryC MyNative");
  }
}

The ‘static’ block is used to load the DLL which contains the native implementation of my_method( ). The library is loaded by the load library( ) method which is part of the System class.

The compilation of the above program produces MyNative.class. Next, you must use javah.exe (included in JDK) to produce MyNative.h as follows:

javah -jni MyNative

This command produces MyNative.h which must be included in the C file that implements my_method(). The output produced by this command is machine generated and is as follows:-

/* Do not edit this file - it is machine generated */
#include <jni.h>
/* Header for class MyNative */
#ifndef _Included_MyNative
#define _included_MyNative
#ifdef_ _cplusplus
extern “C"
{
    #endif
    /* Class: MyNative * Method: myjnethod * Signature: ( )V */
    JNIEXPORT void JNICALL Java_MyNative_myjnethod (JNIEnv *, jobject);
    #ifdef_ _cplusplus
}
#endif
#endif

Pay special attention to the following line which defines the prototype of the my_method() function that you will create:-

JNIEXPORT void JNICALL Java_MyNative_my_method (JNIEnv *, object);

Note that the name of the function is Java_MyNativejny_method( ). You must use this as the name of the native function that you implement, i.e. instead of creating a C function called my_method( ), you will create one called Java_MyNative_my_method( ).

After having produced the necessary header file, you can write your implementation of my_method( ) and store it in a file named

MyNative.c:
{
/* This file contains the C version of my_method( ) */
#include <jni.h>
#include "MyNative.h"
#include <stdio.h>
JNIEXPORT void JNICALL Java_MyNative_myjnethod (JNIEnv *env, jobject obj)
{
jclass cls;
jfieldID fid;
jint i;
printf("Start\n");
cls = (*env)->GetObjectClass(env, obj);
fid = (*env)->GetFieldID(env, els, "i", “l");
if (fid == 0)
{
printf("couldn't get field id\n");
return;
 }
/* get i */
i = (env)->GetIntField(env, obj, fid);
printf("i = %d\n”, i);
/* update i*/
(*env)->SetIntField(env, obj, fid, 10 * i);
printfC'End");
}

Note that this file includes jni.h, which contains interfacing information. This file is provided by your Java compiler. The header file MyNative.h was created by javah earlier.

In this function, the GetObjectClass( ) method is used to obtain a C structure that has information about the class MyNative. The GetFieldIDO method returns a C structure with information about the field named “i” for the class. GetlntFieldO retrieves the original value of that field. SetlntFieldO stores an updated value in that field.

After creating MyNative.c, you must compile it and create a DLL. To achieve this by using the Microsoft C/C++ compiler, use the following command line (you might have to specify the path to jni.h and its subordinate jni_md.h):-

Cl/LD MyNative.c

This produces a file called MyNative.dll; once this is done, you can execute the Java program producing the following output:-
Before the native method, mn.i = 100
Start
i = 100
End
After the native method, mn.i = 1000