Executing your first programFrom WikiJavabuy this book
BasicsOnce we've compiled our application using 'javac' from the JDK we are now ready to execute the program. To execute our program we need a properly installed JRE, it is in this moment in which we can understand why having the same version of the JRE and of the JDK was so important. Over the development process Java language changed in some of its parts, for example the APIs have been improved and Java now even supports some new structures that before it didn't. It may happen, if we have installed two different versions of the JDK and of the JRE, that we try to execute a program compiled with one JDK (i.e. Java 6) and then execute it with a different version of the JRE (i.e. Java 1.4). This may work in some cases, but when we try to execute a program that uses some specific characteristics of Java 6 that Java 1.4 doesn't support (the generics for example). The program may not work as expected. The only good solution to this situation is to make sure to have the same version of JRE and JDK installed, most often following the Installing the JDK tutorial. To execute a program we will use the java command which runs a JVM and executes your program. According to the JVMS for executing a program the JVM searches the main method in the class that you want to execute. If the main method is found, the JVM starts executing the commands contained in it. The execution terminates when there are no more commands to execute in the main method. A way to explicitly terminate the execution is to call the 'return' keyword in the main method, this causes the end of the execution of the current method, and in this case the end of the program execution. ExecutingWe proceed now in the execution of our first Java program. After compiling it we have a directory containing our 'HelloWorld.java' source file and our 'HelloWorld.class' bytecode file. All we need to do is to open a command prompt and change to the directory containing the two files (for example 'C:\javaPrograms'). The command to execute the program is: java HelloWorld This command runs the program called 'java' (it's contained in a file called 'java.exe' in the case of windows) and the parameter passed to it is the name of the class you want to execute. Note that 'java' assumes that the class is contained in a file called with the name of the class and having extension '.class', so we don't need to specify it. The output of this command should be: Hello World!!!
|
