Here was a question from Marcus Green's mock exam: What will happen when you attempt to compile and run this code?
The answer is it will Compile and execute without error. The explanation of this is :"It would cause a run time error if you had a call to amethod though." and I am not sure what that means. I mean I've read what a native modifier means, but since I have not really used it, I really don't understand it. Where does this mysterious amethod() code exist, in another file? How does Java know about this other file? If this method can't be called, what's the point? So in reality I guess I can answer some mock exams even, but I really don't konw what it really means to have native code, and I would appreciate it if somebody who does know could give me some insight.
Where does this mysterious amethod() code exist, in another file? The native code of that method exists in a shared library that will be loaded with System.loadLibrary("libraryName"); How does Java know about this other file? It depends on the platform you are on. For instance, on Windows, the library must be either in the current working directory, or in a directory contained in the PATH environment variable. On Solaris, the library must be in a directory contained in the LD_LIBRARY_PATH environment variable. If this method can't be called, what's the point? In a Java program, you can invoke native methods just as you would invoke non-native (aka Java) methods. That's the beauty of it So in reality I guess I can answer some mock exams even You shouldn't get many questions about that subject in the real exam. The only thing you should care about is that "native" is a java keyword. If you want to learn about native methods, there is a whole chapter in the Java tutorial about the Java Native Interface, although it is not required for the purpose of SCJP to know all that stuff. In short, sometimes Java needs fulfill some tasks that cannot be done in Java. For instance, all AWT components are "linked" to their native peers in order to work properly. Sometimes, you might want to use a native C++ library to, say, perform some heavy computation. The way to do it is described in the link I gave above. Remember that binding your Java implementation to some native implementation might make you gain in performance (or other concerns), but this will break the portability of your code. [ May 08, 2003: Message edited by: Valentin Crettaz ]