Tuesday, April 3, 2012

Java Tutorial & Lesson 3 - Writing the first program: Hello World!

Writing the Hello World in Java


Once you have the environment set up, we can actually begin to code. In last part we set up the environment to work with Java and now we are ready to begin. Here is what you should have by now:



The first line as you can see, says where are we located, this time we are located in a package called "main". There can only be one line that defines the location of the Class for it can only be in one place at the time. The second line defines our class. A class is just a group of functions and attributes (that we will learn about later) all organized in one "file".

Create the main method

Now, for the coding part write inside of the brackets the word "main" and press the space bar while holding the Ctrl key. This is one of my favorite features of Eclipse and it is called Auto-completion. What it does is it gives you a list of possible words of set of words to complete what you are writing, saving you some time while programming. Now you should see something like this:



Select the option that says "main method". If you do it right you should now have something like:

public class Main 
{ 
    public static void main(String[] args) {
    //This is a comment. The contents will be here.
    }
}

This method right here is the first method that will always be executed when running the program as a Java Application. Whatever there is inside those brackets will be the first lines executed by the Java compiler.

Printing a message in the Console

Now, to actually see something working, write the following line inside the main method:

public static void main(String[] args) // This is the main method.
{
    System.out.println( "Hello Java!" ); // Write this line.
}


and Run your program. To do this, Right-click on the main package in your Package explorer (left panel), Run As >> Java Application:





And you should see something like this on the bottom panel. Make sure you are on the "Console" tab:



Please feel free to comment and ask if you have any questions, your feedback will be greatly appreciated.

1 comment:

  1. great lesson, gonna read it when i find the time!

    ReplyDelete