Numeric Parameters and Return Values in Java

When passing numbers between C and Java, you should understand which types correspond to each other. For example, although C does have data types called int and tong, their implementation is platform-dependent. On some platforms, an int is a 16-bit quantity, on others it is a 32-bit quantity. On the Java platform, of course, an int is always a 32-bit integer. For that reason, JNI defines types jint, jtong, and so on.

Table 12.1 shows the correspondence between Java types and C types.

In the header file jni.h, these types are declared with typedef statements as the equivalent types on the target platform. That header file also defines the constants JNI_FALSE = 0 and JNI_TRUE = 1.

Until Java 5, Java had no direct analog of the C printf function. In the following examples, we will suppose you are stuck with an ancient JDK release and decide to implement the same functionality by calling the C printf function in a native method.

Listing 12.5 shows a class called Printf1 that uses a native method to print a floating-point number with a given field width and precision.

Notice that when the method is implemented in C, all int and doubte parameters are changed to jint and jdouble, as shown in Listing 12.6.

The function simply assembles a format string “%w.pf” in the variable fmt, then calls printf. It returns the number of characters printed.

Listing 12.7 shows the test program that demonstrates the Printf1 class.

Source: Horstmann Cay S. (2019), Core Java. Volume II – Advanced Features, Pearson; 11th edition.

Leave a Reply

Your email address will not be published. Required fields are marked *