You will need to write your Java programs using a text editor. When you type the examples that follow you must make sure that you use capital and small letters in the right places because Java is case sensitive. The first line you must type is:
This creates a class called Hello. All class names must start with a capital letter. The main part of the program must go between curly brackets after the class declaration. The curly brackets are used to group together everything inside them.
We must now create the main method which is the section that a program starts.
The word public means that it is accessible by any other classes. static means that it is unique. void is the return value but void means nothing which means there will be no return value. main is the name of the method. (String args) is used for command line parameters. Curly brackets are used again to group the contents of main together. You probably won't understand a few of the things that have just been said but you will know what they mean later on. For now it is enough just to remember how to write that line.
You will see that the main method code has been moved over a few spaces from the left. This is called indentation and is used to make a program easier to read and understand.
Here is how you print the words Hello World on the screen:
Make sure that you use a capital S in System because it is the name of a class. println is a method that prints the words that you put between the brackets after it on the screen. When you work with letters like in Hello World you must always put them between quotes. The semi-colon is used to show that it is the end of your line of code. You must put semi-colons after every line like this.
What we have just finished typing is called the source code. You must save the source code with the file name Hello.java before you can compile it. The file name must always be the same as the class name.
Make sure you have a command prompt open and then enter the following:
If you did everything right then you will see no errors messages and your program will be compiled. If you get errors then go through this lesson again and see where your mistake is.
Once your program has been compiled you will get a file called Hello.class. This is not like normal programs that you just type the name to run but it is actually a file containing the Java bytecode that is run by the Java interpreter. To run your program with the Java interpeter use the following command:
Do not add .class on to the end of Hello. You will now see the following output on the screen:
Congratulations! You have just made your first Java program.
Comments are written in a program to explain the code. Comments are ignored by the compiler and are only there for people. Comments must go between a /* and a */ or after //. Here is an example of how to comment the Hello World program: