Thursday, September 17, 2009

Hello World ... is anybody out there?

Now that you have a project open in Eclipse, it's time to get down to the business of writing and running a program. We're going to start with the ever popular "Hello World" program.

Java programs are built from text files with the extension ".java". The .java files are organized in directories called "packages". So, in order to say "hello" to the world, we will need to create a .java file in our project.

To create a .java file, right-mouse click on the project folder in the navigation window and select "new->class". This brings up a dialog window with a bunch of options. Most of the defaults should be OK. You will want to make sure that the "Source folder" is set to [your project name]/src and you will need to give it a name. The name of the class file must be the same as your class (capitalization counts). So, we should pick a good name.

As a convention, I like to use nouns for the names of classes, — I find this helps maintain the whole object-oriented paradigm
— so, let's call the program "Greetings". Also by convention, we start class names with a capital letter.

Once you've entered the name of the class, click on the "Finish" button. (You might see a warning at this point stating the the use of the default package is discouraged. Just ignore that for now, we'll talk more about that later.)

You should now see a new file in the src directory called Greetings.java, like this:


The file itself will just have this:



Now you are ready to build your class that will be your Hello World program. Put this code in between the curly braces of your new "Greetings" class:



public static void main (String[] args){

String strGreeting = "Hello World!";
System.out.println (strGreeting);

}
Save your Greetings.java file, and you are ready to run it. (Eclipse will automatically pre-compile your .java file into a .class file ready to run.)

To run a Java file in Eclipse, locate the "run icon" in your navigation bar and click on it.



If you've done everything correctly, you should see something like this in the output console (generally found in the bottom tile of the Eclipse screen).




Tadaa, and congratulations! Welcome to the World!

No comments:

Post a Comment