next up previous contents
Next: Compiling and running Java Up: Java Interlude 1 Quick Previous: Java Interlude 1 Quick   Contents

Structure of a Java program

A Java program is a collection of classes. Each class is normally written in a separate file and the name of the file is the name of the class contained in the file, with the extension .java. Thus, the class stack defined earlier would be stored in a file called stack.java.

As we noted in Chapter 1, we have to fix where the program starts to execute. Java requires that at least one of the classes has a public static method called main. More precisely we need a method with the following signature:

   public static void main(String[] args)

We have already seen what public and static mean. The word void has the same connotation as in C -- this function does not return a value. The argument to main is an array of strings (we'll look at strings and arrays in Java in more detail later)--this corresponds to the argv argument to the main function in a C program. We don't need argc because in Java, unlike in C, it is possible to extract the length of an array passed to a function. Also, unlike C, the argument to main is compulsory. Of course, the name of the argument is not important: in place of args we could have used xyz or any other valid identifier.

Here then, is a Java equivalent of the canonical Hello world program.

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

Here println is a static method in the class System.out which takes a string as argument and prints it out with a trailing newline character.

As noted earlier, we have to save this class in a file with the same name and the extension .java; that is, helloworld.java.


next up previous contents
Next: Compiling and running Java Up: Java Interlude 1 Quick Previous: Java Interlude 1 Quick   Contents
Madhavan Mukund 2004-04-29