Tuesday, March 13, 2007

Anatomy of the first program!

Generically speaking any Java program has the following structure...

package x.y.z;
import a.b.c;

class classname{
public static void main(String args[]){
}
}

Text in italics above are all optional. We didn't have any package and import in our program... did we?

We'll talk a lot about packaging and imports later. But for now, let's take a look at the first program we wrote.

public class Receptionist{

void meet( ){
greetVisitor( );
}

void greetVisitor( ){
System.out.println(“Hello Guest! Welcome!”);
}

public static void main(String args[]){
Receptionist receptionist = new Receptionist( );
receptionist.meet( );
}

}

We have a class named Receptionist indicated by

public class Receptionist{
-----
}

But what is this public all about? Again this is something related to packaging and access modifiers which we would cover in detail later. For now, think of the public key word as something that is used to make the class... well... public i.e. accessible to everyone.

Next come methods. The template for any method is

( ){ }

Again this is a generic template and there are a few exceptions to this syntax which we'd see later. But for now be informed that every method should have a return type, a name and the parantheses following the name.

void meet(){
----
}

void visitor(){
----
}

public static void main(String args[]){
------
}

are all methods in our class. The idea of having void should be clear now. When a method need not return anything, we declare the method as void.

So we got a new question. What is meant by returning? Returning what and to whom? Why should a method ever return something? The answer is pretty trivial. Let's imagine that you need a method to find out (NOT PRINT) the sum of two numbers. You might write say c= a + b; and the addition is done. But how does the caller (someone who wanted this method to add up two numbers) know the result? Afterall isn't that the only reason the method was called? That is precisely when you RETURN something from your method. In our case we would return a number.

For now, the code shouldn't appear as strange as it did when you saw it the first time. As we go on, you should be pretty comfortable with all the basic aspects of a Jav program. Nevertheless, keep thinking about the other questions and their possible answers. That would help you understand the system better.

Tired of all this coding stuff? Chill out at http://forwardszone.blogspot.com