Compiling and Running from the DOS (Command) Prompt


Try this exercise out now. Download and copy into NotePad (or WordPad) this source file and then save it as HelloWorld.java in some directory of your choice (such as Desktop or any such directory, as long as you know where to find it). The picture below shows what the program might look like in NotePad.


Click on the "File" menu and then "Save as ..." and save the file to the Desktop directory.

Next, bring up a command prompt window, get to the C drive (which is usually where Desktop is) and type

c:> cd windows\desktop 

To compile the HelloWorld program type the following on your command prompt:

c:\windows\Desktop>javac HelloWorld.java

The javac compiler creates a file called HelloWorld.class that contains the "bytecode" version of your program. There's no need to understand what "bytecode" means at this point, other than to think of it as the "executable" version of the program, i.e., the part that can "run".

Next, to run your program you should use the java interpreter, called java as follows (Note that we don't type any file extension at this stage):

c:\windows\Desktop>java HelloWorld

Here is a picture showing both compilation and execution:


Note: The name you give your source file is very important. In the above example the name of the source file should be HelloWorld.java because the class name (inside the file) is HelloWorld. you would have noticed that even the class name defined in the program is same. Note also that Java is case-sensitive so make sure that the capitalization of the filename matches the case of the class name.