Monday, November 7, 2011

Java Hello World program

You need to know three things:
1. You need to write a Java class, say a class called HelloWorld

2. You need to save it to a file called HelloWorld.java
NOTE:
* All Java source files end with .java
* The name of the .java file has to exactly match the name of the class
* A single .java file contains exactly one class definition (there are caveats, but no need to think of them now)

3. You need to compile the class to create HelloWorld.class
NOTE:
* All Java source, when compiled, creates a .class file
* The name of the .class file is exactly the name of the class it contains

Lets write this simple Java class:
1. In our notepad, we will open a new file and call it 'HelloWorld.java'
2. We will write the following code:

 class HelloWorld {  
   public static void main(String[] args) {  
     System.out.println("Hello World!");   
   }  
   


Some things to note here:

* The 'class' keyword declares the class HelloWorld

* The name of the class is 'HelloWorld' which matches the filename HelloWorld.java

* The method 'main' has two keywords before it: 'public' which means that this method can be called externally (as opposed to 'private' which cannot be called externally), and 'static' which means that this method can be called without instantiating the class (if this sounds complicated, please refer the Java tutorial at Sun)

* The method takes an array of arguments - these are the args that the user might type on the command line

* The method prints 'Hello World!' to the console

That is it - you just wrote a simple HelloWorld program!

Note, again, that ALL java source code is made of classes. There is no way to write a file with just methods in it, like you might do in C/C++. Methods can only be written inside classes.

No comments: