3.2. Compile and run your Java program

Java (11 Part Series)

1 1. Introduction to Java.. Small but worthy..
2 1.1 simple hello world program
7 more parts…
3 2. Installation of Java
4 3. Exercise: Write, compile and run a Java program
5 3.2. Compile and run your Java program
6 4. Base Java language structure (Class, objects, inheritance )
7 4.2 Exception handling in Java
8 5. Java interfaces
9 6. Annotations in Java
10 7. Variables and methods
11 Important announcement

Open a shell for command line access.

If you don’t know how to do this, google for “How to open a shell under [your_OS]”.
Switch to the javadir directory with the command cd javadir, for example, in the above example via the cd \home\vogella\javastarter command. Use the ls command (dir under Microsoft Windows) to verify that the source file is in the directory.

Compile your Java source file into a class file with the following command.

javac HelloWorld.java
Afterwards list again the content of the directory with the ls or dir command. The directory contains now a file HelloWorld.class. If you see this file, you have successfully compiled your first Java source code into bytecode.

By default, the compiler puts each class file in the same directory as its source file. You can specify a separate destination directory with the -d compiler flag.
You can now start your compiled Java program. Ensure that you are still in the jardir directory and enter the following command to start your Java program.

java HelloWorld
The system should write “Hello World” on the command line.

Compiling and running Java programs on the command line
3.3. Using the classpath
You can use the classpath to run the program from another place in your directory.

Switch to the command line, e.g., under Windows Start Run cmd. Switch to any directory you want. Type:

java HelloWorld
If you are not in the directory in which the compiled class is stored, then the system will show an error message: Exception in thread “main” java.lang.NoClassDefFoundError: test/TestClass

To use the class, type the following command. Replace “mydirectory” with the directory which contains the test directory. You should again see the “HelloWorld” output.

java -classpath “mydirectory” HelloWorld

Java (11 Part Series)

1 1. Introduction to Java.. Small but worthy..
2 1.1 simple hello world program
7 more parts…
3 2. Installation of Java
4 3. Exercise: Write, compile and run a Java program
5 3.2. Compile and run your Java program
6 4. Base Java language structure (Class, objects, inheritance )
7 4.2 Exception handling in Java
8 5. Java interfaces
9 6. Annotations in Java
10 7. Variables and methods
11 Important announcement

原文链接:3.2. Compile and run your Java program

© 版权声明
THE END
喜欢就支持一下吧
点赞10 分享
Be happy. No worries, just smile.
开心点,别担心,微笑就好
评论 抢沙发

请登录后发表评论

    暂无评论内容