Computer Science – Java Lesson 2
Welcome to lesson 2 of my Java series. Now that you’ve installed Java successfully, we can start learning the basics of Java.
First, we should start a new project. Open NetBeans and create a new project, specifically a Java Application with a name of MyFirstProject. Once open, go ahead and just delete everything in the editor (the right window). Now type this into the article and click the Build button, followed by the Run button. I’ll explain it afterwards.
public class MyFirstProject
{
public static void main(String[] args)
{
System.out.println(“Hello World!!!”);
}
}
What this program does is print the message Hello World!!! in the window on the bottom. Let’s see what each individual line accomplishes.
public class MyFirstProject
This line indicates the start of a Java file. This line is always present in any Java program. In a later article I’ll introduce the concept of a class, but for now remember that this marks the start of our file. Following the words ‘public’ and ‘class’ is the name you gave to your file. So, whatever you plan on naming your file, your class header needs to reflect it.
{
This open curly bracket is matched with the closing bracket in the last line. Whatever goes between these two brackets belongs to the class.
public static void main(String[] args)
This is the main method. Every time a program is run it looks for the main method, then executes the code within it. It’s difficult for me to explain at this time what the words mean, but just know that like the class header this needs to be present.
{
This marks another set of curly brackets to indicate the contents of the main method.
System.out.println(“Hello World!!!”);
This is the only line that actually does anything. The System.out.println() method takes a message surrounded by quotes and prints it. Notice the semi-colon at the end. All commands need to end with a ‘;’. Think of it as the period at the end of a sentence.
}
Ends the main() method.
]
Ends the class.
For practice, try making a picture using a bunch of System.out.println() instructions.
Next article I’ll start explaining variables.