Java Lesson 1 - Your First Program
Firstly, to create a Java program you need to install a few things:
- The Java SDK (aka JDK) from Sun
- Something to create plain text files with, we'll use notepad for now.
1. Assuming that you have installed that correctly (if you have any problems then please ask for help in our forum), start notepad or your desired text editor and enter the following code:
public class HelloWorld
{
public static void main(String[] args)
{
System.out.println("Hello World!");
}
}
It's not terribly important that you understand what the code does just now, as the main emphasis of this lesson is on compiling and running your code, what the code does will be explained in a future lesson.
2. Save that file as HelloWorld.java (the filename is important) and start the command prompt (usually done by selecting start->run, entering "cmd" then pressing ok).
3. At the command prompt, browse to the directory where you saved your program using the command cd "directory name" to change directories (to change drives, type the letter of the drive followed by a colon, for example E: to change to the E: drive).
4. When you've made it to the folder, type:
javac HelloWorld.java
to compile your code. If you recieve an error message similar to "'javac' is not recognized as an internal or external command, operable program or batch file." then ensure that you have followed instruction number 5 in the JDK install instructions.
If your program compiles successfully then you won't recieve any output but you will notice that a new file has appeared in the same directory as HelloWorld.java - this one being called HelloWorld.class which is your compiled program.
5. Now you are ready to run the program! At the command prompt again, type:
java HelloWorld
(note that this time you type java, without the c, and no file extension). You should notice the output "Hello World!" in the cmd window.
Phew, that's the first lesson over - in this lesson you've seen how to create, compile and run a program in Java using just notepad and a command prompt (there are less tedious ways to do it as we shall see, but it is helpful to know that it is possible this way).
This lesson is demonstrated in a flash video: Lesson 1 (370KB)
Summary
- You can create a java program in any text editor, as long as you save it as plain text
- To compile a java program from the command line, type javac FileName.java
- javac.exe is the program which compiles java code.
- To run a java program from the command line, type java FileName
