Hello, world - Java style

Introduction

Way back when Kernighan & Ritchie first created the C programming language, they introduced it to the world in the famous white book with their "Hello, world!" example. After all these years, it still seems like a good way to introduce a programming language, so here's our version of "Hello, world!", written in Java:

public class HelloWorld {

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

}

Listing 1 (above): HelloWorld.java - the source code for the "Hello, world!" program.

Discussion

The Java language, and the object-oriented model are pretty cool. Object-oriented programming has proven it's advantages time and again compared to procedural coding. But one place where the object-oriented syntax seems wasteful is in a simple example like this program. Using Java, five lines of code are required for the "Hello, world!" example, where the same thing can be achieved with a one-line batch file in DOS or Unix.

Fear not, though. Although this example makes Java look bad, in the real world most programs are not simple examples like this, and the elegance of the object-oriented model soon becomes apparent.

In this example we've created a class named HelloWorld. In Java, everything must be defined inside of a class, and since this program is about printing the string "Hello, world!", this seemed like as good a name as any for the class.

Inside of a standalone program like this the function named main is where all activity begins. This is similar to the C language. The only activity of this program is to print the string "Hello, world", so we do this using Java's System.out.println function. The printlnfunction prints our string to the standard output.

To run this program, save it in a file with the name HelloWorld.java. Important note - the file name must match the name of the class, so if you used a name besides HelloWorld for your class, make sure you use the same name for your file. Then, assuming you have the Java JDK loaded, compile the program with this command:

javac HelloWorld.java

When you compile the program you'll create a byte-code file named HelloWorld.class. You can confirm this with the ls command in Unix, or the dir command in the DOS/Windows world. Now you can execute the byte code in the Java interpreter with this command:

java HelloWorld

When you run the program at the command line, you'll see this output

Hello, world!

Conclusion

Well, that seemed like more work than necessary for a simple example. Although it may seem like overkill right now - relax - the extra syntax required by Java in this example is not the norm for larger programs, and eventually defining classes will seem like the really natural way to program.

What's Related


devdaily logo