Easy to Learn Java: Programming Articles, Examples and Tips

Start with Java in a few days with Java Lessons or Lectures


Code Examples

Java Tools

More Java Tools!

Java Forum

All Java Tips


Submit News
Search the site here...

Living with the natives (Applets)

Custom Search
Living with the natives (Applets)

[ Return to Shlurrrpp......Java ]

Using Native Methods in your Java Code

Using Native Methods in your Java Code

Yep, we can include our old code written in some other language into now-patronized Java. Here we tell you a simple, clean way of integrating C code with a Java program. Could we expect a favour? Please do not tell anyone from Sun that you were smooshing code in this way, for it might get us a load of unsolicited mail trying to size us up about the way we write programs. But wait up.

Can we offer a miniature observation here (with due apologies to the women). Ever realized that next to standing in the rain with pneumonia, trusting a woman during the day is the most dangerous thing to do? Whether young or old, they are born with that femme fatale instinct of putting their best foot forward...both literally as well as metaphorically. Just about as well as the back of their palms, they know what dress to put on and when, how to dab the make-up to look the best in all lights and how to make you-know-what out of every men. The best time to catch them is, therefore, not during the day (especially in its latter part) but at the time they have just woken up. That is the real beauty, and it is easier to love the made-up woman once you have seen what she looks like when she is herself.

The simple example that we use here to introduce the concept to the people might not be the best and the most efficient way to embed code, but IT WORKS. And its a good start. If you don't agree with us, try the original Sun's Tutorial on Native Methods . Another point to be noted is that this example is a standalone program that we chose to use as our first illustration because applets seem to be too ornery when it comes to working without fuss. (That reminds us, we will soon put up some standalone programs as well). And unfortunately, we have also used Visual C++ 4.0 / 2.1 for the purpose of creating DLLs. No need to start day-dreaming, you will soon know what a DLL (Dynamic Link Library) is all about.

Here we go...

  • Make a directory called yyy in the root directory and be in it.
  • Write the following code and save it as jane.java ...
    	class aaa
    	{      public static void main(String s[])
    		{      bbb a;
          	          	a = new bbb();
                	    	System.out.println("Before xx");
                      	System.out.println("After xx");
    	class bbb
    	{      public native void xx();
    	       public bbb()
    	              System.out.println("in zzz");

    We have an ordinary class called aaa , where we have our main() , very much reminiscent of the good old C/C++. An object that looks like String is passed along with it. Remember argv[] ? Our string s[] is identical to that. Now the word static . It could very well have been free, because that is what static means. Lets get it cleared. Ordinarily, whenever we have to use a function of a class, we have to first initialize an object that looks like that class and then refer the function through the object. But if we make our main() into a static function, we can use it without having to initialize an object to aaa .

    Inside the main() , we have an object a which looks like our class bbb . The System.out.println() takes care of printing on to our monitor, and in that sense, is the cousin of printf. So the string start will be printed on the screen. Then we initialize a to bbb and print Before xx . Through a , we call the xx() of class bbb .

    In the class bbb , we have our statement public native void xx() . People who have tasted C or C++, particularly the ones who have a soft corner for computer terminology, might mistake this statement for a function prototype. But it is not so. One thing that ought to be crystal clear in our minds is that Java does not have prototypes . In fact, without the word native , we would have got an error in the above line. The word native tells the compiler that the function following it is one written in some other language (in our case C). Again, System.loadLibrary() picks up a DLL file in to memory and the alien code that we have to use/call has to be in the form of a .dll file, not .exe . So compile the above program with the usual javac jane.java .

  • Load on Visual C++ (we have used ver. 4.0). Create a new project called zzz . Select the 'Project type' as MFCAppWizard (dll) . Make sure the 'Directory' is the root. Click on 'Create', then on 'Finish' and finally on 'OK'.
  • A bunch of files is created. We ruthlessly delete all of them. Now if making a project and then slashing all its contents kind of piques you, let us make it clear that we used a Wizard to evade the problems of creating a DLL file.
  • Now create a new Code/Text file called zzz.c . Type in the following code, and you are free to wax nostalgic, for it is the same old C...
    	void *Java_bbb_xx_stub(void * p, void * q)
    	{	printf("It works! 
    		return p;

    Note that the function here has to be called by a special name. It has to be prefixed with Java_ and suffixed with _stub . The middle part has to be the class name ( in our case bbb ) and the function name (in our case xx ) seperated by another underscore (_). The function needs a void pointer to be returned so that is the return type of the function. There are two parameters -- both void pointers p and q , but since we are not using them, let us not confuse ourselves with their exact employment. (If you are too adamant, though, p is like the this pointer). For the sake of simplicity, not to mention the stability of our heads, we ensure that the function performs some simple task. Hence, we just use the ever-so-popular printf to display a statement that says It works . And then hope it does :)

  • Lets get back to the DOS prompt and edit the zzz.def file to look like this...
    		Java_bbb_xx_stub	@1

    This is because if you do not have the Java_bbb_xx_stub given under exports, then it cannot be called by any other external program.

  • 'Build' the ZZZ.DLL file.
  • Get back to the DOS prompt.
  • Execute the program with the statement java aaa . You will get an error. To remove it, copy the zzz.dll from the WinDebug directory into the yyy directory. Now when the command java aaa is given , the output will be ...
    	in zzz
    	Before zzz
    	It works! 
    	After zzz


There. We have a small-is-sweet C program integrated with Java! So what's the fuss all about ? Admittedly, this procedure might have its shortcomings, but isn't it a better way to embark on a new concept than groping with CLASSPATH and javah ?

Nevertheless, it does not mean we will overlook the butterfly if we like the caterpillar. Very soon, we will see how to use it in those intricate ways as well...



Do you like this quick and dirty (but undeniably understandable) way of learning Java? Feel free to let us know what you feel about it.

Find out about the Cyberconference on How to teach Java or just scamper back to The Java page



Vijay Mukhi's Computer Institute
B-13, Everest Building, Tardeo, Bombay 400 034, India.
e-mail : vmukhi@giasbm01.vsnl.net.in

[ Return to Shlurrrpp......Java ]

Top 10 read Java Articles
 Get free "1000 Java Tips eBook"

 Java Calendar and Date: good to know facts and code examples

 Array vs ArrayList vs LinkedList vs Vector: an excellent overview and examples

 How can I convert any Java Object into byte array? And byte array to file object

 The Java Lesson 1: What is Java?

 How do I compare two dates and times, date between dates, time between times and

 Maven vs Ant or Ant vs Maven?

 How to open, read, write, close file(s) in Java? Examples on move, rename and de

 Java Array

 Java: JLabel font and color

[ More in News Section ]
Java Lessons

The Java Lesson 1:
What is Java?
The Java Lesson 2:
Anatomy of a simple Java program
The Java Lesson 3:
Identifiers and primitive data types
The Java Lesson 4:
Variables, constants, and literals
The Java Lesson 5:
Arithmetic operations, conversions, and casts
The Java Lesson 6:
Boolean expressions and operations
The Java Lesson 7:
Bitwise operations
The Java Lesson 8:
Flow control with if and else
The Java Lesson 9:
switch statements
The Java Lesson 10:
for, while, and do-while statements
The Java Lesson 11:
Using break and continue
The Java Lesson 12:
Class methods and how they are called
The Java Lesson 13:
Using the Math class
The Java Lesson 14:
Creating and calling custom class methods
The Java Lesson 15:
Overloading class methods
The Java Lesson 16:
An introduction to objects and object references
The Java Lesson 17:
The String class
The Java Lesson 18:
The StringBuffer class
The Java Lesson 19:
Initializing and processing arrays of primitives
The Java Lesson 20:
Initializing and processing arrays of objects
The Java Lesson 23:
Inheritance and overriding inherited methods
The Java Lesson 24:
abstract classes and polymorphism
The Java Lesson 25:
Interfaces, instanceof, and object conversion and casting
The Java Lesson 26:
Introduction to graphical programming and the java.awt packa
The Java Lesson 27:
The Component class
The Java Lesson 28:
Containers and simple layout managers
The Java Lesson 29:
The Color and Font classes
The Java Lesson 30:
Drawing geometric shapes
The Java Lesson 31:
Choice, List, and Checkbox controls
The Java Lesson 32:
Using the Scrollbar graphical control
The Java Lesson 33:
Menus and submenus
The Java Lesson 34:
An introduction to applets and the Applet class
The Java Lesson 35:
Essential HTML to launch an applet and pass it parameters
The Java Lesson 36:
Mouse event processing
Java Lesson 37:
Menus and submenus
Java Lesson 38:
The WindowListener interface and the WindowAdapter class
Java Lesson 39:
An introduction to GridBagLayout
Java Lesson 40:
An introduction to the Java Collections API
Java Lesson 41:
Exception handling with try, catch, and finally blocks
Java Lesson 42:
Claiming and throwing exceptions
Java Lesson 43:
Multithreading, the Thread class, and the Runnable interface
Java Lesson 44:
An introduction to I/O and the File and FileDialog classes
Java Lesson 45:
Low-level and high-level stream classes
Java Lesson 46:
Using the RandomAccessFile class
Java Lessons by
Joh Huhtala: Update

Latest articles
 Java Profiler JProbe to Resolve Performance Problems Faster

 SSL with GlassFish v2, page 5

 SSL with GlassFish v2, page 4

 SSL with GlassFish v2, page 3

 SSL with GlassFish v2, page 2

 The Java Lesson 2: Anatomy of a simple Java program, page 2

 New site about Java for robots and robotics: both software and hardware.

 Exceptions -III: What's an exception and why do I care?

 Exceptions -II: What's an exception and why do I care?

 Exceptions: What's an exception and why do I care?

 Double your Java code quality in 10 minutes, here is receipt

 Murach's Java Servlets and JSP

 How to get ascii code from a char in Java?

 Can we just try without catch? Yes!

 Make Tomcat page load faster

 Make your Tomcat More secure - limit network address for certain IP addresses

 New Java book online starts now here...

 Implementing RESTful Web Services in Java

 Firefox trimming from 1 GB to 40 Mb with many tabs opened

 SSL with GlassFish v2

 My request to replublish Tech Tips

 Search JavaFAQ.nu site here

 New Advanced Installer for Java 6.0 brings XML updates and imports 3rd party MSI

 EJB programming restrictions

 Maven vs Ant or Ant vs Maven?

 Why Java does not use default value which it should?

 How to unsign signed bytes in Java - your guide is here

 The Java Lesson 3: Identifiers and primitive data types. Page 2

 The Java Lesson 7: Bitwise operations with good examples, click here! Page 4

 The Java Lesson 7: Bitwise operations with good examples, click here! Page 3

[ More in News Section ]

Home Code Examples Java Forum All Java Tips Books Submit News, Code... Search... Offshore Software Tech Doodling

RSS feed Java FAQ RSS feed Java FAQ News     

    RSS feed Java Forums RSS feed Java Forums

All logos and trademarks in this site are property of their respective owner. The comments are property of their posters, all the rest 1999-2006 by Java FAQs Daily Tips.

Interactive software released under GNU GPL, Code Credits, Privacy Policy