Java Banner
Hello World- The Application

The following is the Hello World Application as written in Java. Type it into a text file or copy it out of your web browser, and save it as a file named HelloWorld.java. If you want, you can just download the source we wrote by right clicking (for people who can) the link below the code and selecting to "save as". Before you start do ing anything, make yourself a directory somewhere in your computer called "javahtml." Ofcourse, you can name it something else if you want, but we are using that name. It might be easier for you beginners to follow along with us.

class HelloWorld {

  public static void main (String args[]) {

    System.out.println("Hello World!");

  }
  
}

HelloWorld.java

After installing the JDK on your system do the corresponding thing:

Mac OS: Later on in the tutorial Mac Users should drag the java file onto the compiler's icon.
When the tutorial asks you guys to use "java somefile" double click on the class file.
Dosshell in Windows 95/NT:To make it easier for you, you should type in something like:
set path=c:\windows\command\;c:\java\bin\
at the prompt. The bin directory can be anywhere. This line matters on where your java directory is located. That will put the Java directory in the path so when you go into your personal java directory, all you have to type is:
javac SomeFile.java or when it tells you to start the application, just use java SomeFile.
Unix users should type javac because when the JDK is installed your path will be automatically set. You can use java in the same way.

To compile this program make sure you're in the same directory as HelloWorld.java is in and type
javac HelloWorld.java
at the command prompt. Hello World is very close to the simplest program imaginable. Even though this program doesn't teach you much, it gives you a chance to learn the basics of writing and compiling source code. Some people who have never programmed before in a language like this make mistakes and your first try might fail. If there is an error when you compile the code, look at what the problem is and try to fix it. If you are having trouble, compiling code from this tutorial, you shouldn't have any problems. If there are problems, they are probably typos and these are easily fixable because you can always refer to our code.

Once your program has compiled successfully, the compiler places the executable output in a file called HelloWorld.class in the same directory as the source code file. You can then run the program by typing java HelloWorld at the command prompt. As you probably guessed the program responds by printing Hello World! on your screen.

Dosshell/WIN 95/ WIN NT: Set you path in accordance with the previous table. Type java and the name of the .class file.
Mac OS: Double click the .class file
Unix: Use
java with your .class file

Whoopee! You wrote your first Java program. So what, it didn't do anything. If you are new to programming languages like this, the only thing you probably understood were the println command. Anybody who is new to programming, should get something out of this program and the way you interpret the Hello World program and how well you understoold what it did shows how experienced a programmer you are. People who don't get didly squat after doing this program are very inexperienced and have never programmed before. People who understand what "System.out.println()" does are pretty experienced and understand this won't be hard for them.

Understanding Hello World

Hello World is very close to the simplest program that can be done in a language. Nonetheless there's quite a lot going on in it. Let's see what it does.

For now the initial class statement may be thought of as defining the program name, in this case HelloWorld.

The initial class statement is actually quite a bit more than that since this "program" can be called not just from the command line but also by other parts of the same or different programs. We'll see more in the section on classes and methods below.

The HelloWorld class contains one method, the main method. As in C the main method is where an application begins executing. The method is declared public meaning that the method can be called from anywhere. It is declared static meaning that all instances of this class share this one method. It is declared void which means, as in C/C++, that this method does not return a value. Finally we pass any command line arguments to the method in an array of Strings called args. In this simple program there aren't any command line arguments though.

Finally when the main method is called it does exactly one thing: print "Hello World" to the standard output, generally a terminal monitor or console window of some sort. This is accomplished by the System.out.println method. To be more precise this is accomplished by calling the println method of the out class belonging to the System object; but for now we'll just treat this as one method.

One final note: unlike the printf function in C the System.out.println method does append a newline at the end of its output. There's no need to include a \n at the end of each string to break a line.

Braces and Blocks

Let's looks the Hello World program a little more closely. In Java a source code file is broken up into parts separated by opening and closing braces, i.e. the { and } characters. Everything between { and } is a block and exists more or less independently of everything outside of the braces.

Blocks are important in code and they are also logicaly. Without the braces the code wouldn''t compile. The compiler would have trouble figuring out where one method or class ended and the next one began. Similarly it would be very difficult for someone else reading your code to understand what was going on. For that matter it would be very difficult for you, yourself to understand what was going on. The braces are used to group related statements together. Basically everything between matching braces is executed as one statement (though depending not necessarily everything inside the braces is executed every time).

Blocks can be hierarchical. One block can contain one or more subsidiary blocks. In this case we have one outer block that defines the HelloWorld class. Within the HelloWorld block we have a method block called "main".

In this tutorial we help to identify different blocks with indentation. Every time we enter a new block we indent our source code by two spaces. When we leave a block we deindent by two spaces. This is a common convention in many programming languages. However it is not part of the language. For example VRML, and PERL both use this. The code would produce identical output if we didn't indent it. Sometimes, you will see that I left this out. Indentation makes the code easier to read and understand, but it does not change its meaning.

Comments

Comments can appear anywhere in a source file. Comments are identical to those in C and C++. Everything between /* and */ is ignored by the compiler and everything on a line after two consecutive slashes is also thrown away. Therefore the following program is, as far as the compiler is concerned, identical to the first one:

// This is the Hello World program in Java
class HelloWorld {

    public static void main (String args[]) {
      /* Now let's print the line Hello World */
      System.out.println("Hello World");
      
  }

}

Data and Variables

Methods are only half of a Java class. The other half is data. Consider the following generalization of the HelloWorld program:

// This is the Hello Gooar program in Java
class HelloGooar {

    public static void main (String args[]) {
    
      // You may feel free to replace "Gooar" with your own name
      String name = "Gooar";
      
      /* Now let's say hello */
      System.out.print("Hello ");
      System.out.println(name);
  }

}

Here, rather than saying hello to a rather generic world, we allow Java to say hello to a specific individual. We do this by creating a String variable called "name" and storing the value "Rusty" in it. (You may, of course, have replaced Rusty with your own name.) Then we print out "Hello ". Notice that we've switched here from System.out.println method to the similar System.out.print method. System.out.print is just like System.out.println except that it doesn't break the line after it's finished. Therefore when we reach the next line of code, the cursor is still located on the same line as the word "Hello" and we're ready to print out the name.

Command Line Arguments

Our Hello program still isn't very general. We can't change the name we say hello to without editing and recompiling the source code. This may be fine for the programmers, but what if the secretaries want their computers to say Hello to them? (I know. This is a little far-fetched but bear with me. I'm making a point.)

What we need is a way to change the name at runtime rather than at compile time. (Runtime is when we type java HelloRusty. Compile time is when we type javac HelloRusty.java). To do this we'll make use of command-line arguments. They allow us to type something like Java Hello Gloria and have the program respond with "Hello Oog". Here's the code:

// This is the Hello program in Java
class Hello {

    public static void main (String args[]) {
    
      /* Now let's say hello */
      System.out.print("Hello ");
      System.out.println(args[0]);
  }

}

Compile this program in the javahtml directory as usual and then type java Hello Gloria.

This isn't very hard is it? In fact we've even gotten rid of the name variable from the HelloRusty program. We're using args[0] instead. args is what is known as an array. An array stores a series of values. The values can be Strings as in this example, numbers, objects or any other kind of Java data type.

args is a special array that holds the command line arguments. args[0] holds the first command line argument. args[1] holds the second command line argument, args[2] holds the third command line argument and so on.

At this point almost everyone reading this is probably saying "Whoa, that can't be right." However why you're saying depends on your background.

If you've never programmed before or if you've programmed only in Pascal or Fortran, you're probably wondering why the first element of the array is at position 0, the second at position 1, the third at position 2 instead of the clearly more sensible element 1 being the first element in the array, element 2 being the second and so on. All I can tell you is that this is a holdover from C where this convention almost made sense.

On the other hand if you're used to C you're probably upset because args[0] is the first command line argument instead of the command name. The problem is that in Java it's not always clear what the command name is. For instance in the above example is it java or Hello? On some systems where Java runs there may not even be a command line, the Mac for example.

Now you should experiment with this program a little. What happens if instead of typing java Hello Gloria you type java Hello Gloria and Beth? What if you leave out the name entirely, i.e. java Hello?

That was interesting wasn't it? You should have seen something very close to

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException at Hello.main(C:\javahtml\Hello.java:7)

What happened was that since we didn't give Hello any command line arguments there wasn't anything in args[0]. Therefore Java kicked back this not too friendly error message about an "ArrayIndexOutOfBoundsException." That's a mouthful. We'll see one way to fix it in the next section.

If statements

All but the most trivial computer programs need to make decisions. They need to test some condition and operate differently based on that condition. This is very common in real life.

All programming languages have some form of an if statement that allows you to test conditions. In the previous code we should have tested whether there actually were command line arguments before we tried to use them.

All arrays have lengths and we can access that length by referencing the variable arrayname.length. (Experienced Java programmers will note that this means that the array is an object which contains a public member variable called length.) We test the length of the args array as follows:

// This is the Hello program in Java
class Hello {

    public static void main (String args[]) {
    
      /* Now let's say hello */
      System.out.print("Hello ");
      if (args.length > 0) {
        System.out.println(args[0]);
      }
  }

}

Compile and run this program and toss different inputs at it. You should note that there's no longer an ArrayIndexOutOfBoundsException if you don't give it any command line arguments at all.

What we did was wrap the System.out.println(args[0]) statement in a conditional test, if (args.length > 0) { }. The code inside the braces, System.out.println(args[0]), now gets executed if and only if the length of the args array is greater than zero. In Java numerical greater than and lesser than tests are done with the > and < characters respectively. We can test for a number being less than or equal to and greater than or equal to with <= and >= respectively.

Testing for equality is a little trickier. We would expect to test if two numbers were equal by using the = sign. However we've already used the = sign to set the value of a variable. Therefore we need a new symbol to test for equality. Java borrows C's double equals sign, ==, to test for equality.

It's not uncommon for even experienced programmers to write == when they mean = or vice versa. In fact this is a very common cause of errors in C programs. Fortunately in Java, you are not allowed to use == and = in the same places. Therefore the compiler can catch your mistake and make you fix it before you run the program.

All conditional statements in Java require boolean values, and that's what the ==, <, >, <=, and >= operators all return. A boolean is a value that is either true or false. Unlike in C booleans are not the same as ints, and ints and booleans cannot be cast back and forth. If you need to set a boolean variable in a Java program, you have to use the constants true and false. false is not 0 and true is not non-zero as in C. Boolean values are no more integers than are strings.

Experienced programmers may note that there was an alternative method to deal with the ArrayIndexOutOFBoundsException involving try and catch statements. We'll return to that soon.

Else

You may have noticed a minor cosmetic bug in the previous program. A cosmetic bug is one that doesn't crash the program or system, or produce incorrect results, but just looks a little annoying. Cosmetic bugs are acceptable in quick hacks you'll only use once but not in finished code.

The cosmetic bug here was that if we didn't include any command line arguments, although the program didn't crash, it still didn't say Hello. The problem was that we only used System.out.print and not System.out.println. There was never any end of line character. It was like we typed in what we wanted to say, but never hit the return key.

We could fix this by putting a System.out.println(""); line at the end of the main method, but then we'd have one too many end-of-lines if the user did type in a name. We could add an additional if statement like so:

// This is the Hello program in Java
class Hello {

public static void main (String args[]) {

/* Now let's say hello */
System.out.print("Hello ");
if (args.length > 0) {
System.out.println(args[0]);
}
if (args.length <= 0) {
System.out.println("whoever you are");
}
}

}

This corrects the bug, but the code is hard to read and maintain. It's very easy to miss a possible case. For instance we might well have tested to see if args.length were less than zero and left out the more important case that args.length equals zero. What we need is an else statement that will catch any result other than the one we hope for, and luckily Java provides exactly that. Here's the right answer:

// This is the Hello program in Java
class Hello {

    public static void main (String args[]) {
    
      /* Now let's say hello */
      System.out.print("Hello ");
      if (args.length > 0) {
        System.out.println(args[0]);
      }
      else {
        System.out.println("whoever you are");
      }
  }

}

Now that Hello at least doesn't crash with an ArrayIndexOutOfBoundsException we're still not done. java Hello works and Java Hello Gooar works, but if we type java Hello Oog Gooar Wave, Java still only prints Hello Elliotte. Let's fix that.

We're not just limited to two cases though. We can combine an else and an if to make an else if and use this to test a whole range of mutually exclusive possibilities. For instance here's a version of the Hello program that handles up to four names on the command line:

// This is the Hello program in Java
class Hello {

    public static void main (String args[]) {
    
      /* Now let's say hello */
      System.out.print("Hello ");
      if (args.length == 0) {
        System.out.print("whoever you are");
      }
      else if (args.length == 1) {
        System.out.println(args[0]);
      }
      else if (args.length == 2) {
        System.out.print(args[0]);
        System.out.print(" ");
        System.out.print(args[1]);
      }      
      else if (args.length == 3) {
        System.out.print(args[0]);
        System.out.print(" ");
        System.out.print(args[1]);
        System.out.print(" ");
        System.out.print(args[2]);
      }      
      else if (args.length == 4) {
        System.out.print(args[0]);
        System.out.print(" ");
        System.out.print(args[1]);
        System.out.print(" ");
        System.out.print(args[2]);
        System.out.print(" ");
        System.out.print(args[3]);
      }      
      else {
        System.out.print(args[0]);
        System.out.print(" ");
        System.out.print(args[1]);
        System.out.print(" ");
        System.out.print(args[2]);
        System.out.print(" ");
        System.out.print(args[3]);
        System.out.print(" and all the rest!");
       }
      System.out.println();
  }

}

You can see that this gets mighty complicated mighty quickly. Once again no experienced Java programmer would write code like this. One of the things that makes this solution so unwieldy is that I've used a different print statement for every single variable. However Java makes it very easy to print multiple items at once. Instead of including just one thing in the print method's arguments we put multiple items in there separated by + signs. These items can include variables like args[0] and constant strings like " and all the rest!". For example the last else block could have been written as

else {
  System.out.print(args[0] + " " + args[1] + " " + args[2] + " " + args[3] + " and all the rest!");
}

This syntax is simpler to read and write but would still be unwieldy once the number of command line arguments grew past ten or so. In the next section we'll see how to handle over two billion command line arguments in a much simpler fashion.

Variables and Arithmetic expressions

We'll begin this section by finding a more elegant way to handle multiple command line arguments of an undetermined number. Toward this end we introduce the concept of a loop. A loop is a section of code that is executed repeatedly until a stopping condition is met. A typical loop may look like:

while there's more data {
  Read a Line of Data
  Do Something with the Data
}

This isn't working code but it does give you an idea of a very typical loop. We have a test condition (Is there more data?) and something we want to do with if the condition is met. (Read a Line of Data and Do Something with the Data.)

There are many different kinds of loops in Java including while, for, and do while loops. They differ primarily in the stopping conditions used.

For loops typically iterate a fixed number of times and then exit. While loops iterate continuously until a particular condition is met. You usually do not know in advance how many times a while loop will loop.

In this case we want to write a loop that will print each of the command line arguments in succession, starting with the first one. We don't know in advance how many arguments there will be, but we can easily find this out before the loop starts using the args.length. Therefore we will write this with a for loop. Here's the code:

// This is the Hello program in Java
class Hello {

    public static void main (String args[]) {
    
      int i;
    
      /* Now let's say hello */
      System.out.print("Hello ");
      for (i=0; i < args.length; i = i+1) {
        System.out.print(args[i]);
        System.out.print(" ");
      }
      System.out.println();
  }

}

We begin the code by declaring our variables. In this case we have exactly one variable, the integer i.

Then we begin the program by saying "Hello" just like before.

Next comes the for loop. The loop begins by initializing the counter variable i to be zero. This happens exactly once at the beginning of the loop. Programming tradition that dates back to Fortran insists that loop indices be named i, j, k, l, m and n in that order. This is purely a convention and not a feature of the Java language. However anyone who reads your code will expect you to follow this convention. If you choose to violate the convention, try to give your loop variables mnemonic names like counter or loop_index.

Next is the test condition. In this case we test that i is less than the number of arguments. When i becomes equal to the number of arguments, (args.length) we exit the loop and go to the first statement after the loop's closing brace. You might think that we should test for i being less than or equal to the number of arguments; but remember that we began counting at zero, not one.

Finally we have the increment step, i=i+1. This is executed at the end of each iteration of the loop. Without this we'd continue to loop forever since i would always be less than args.length. (unless, of course, args.length were less than or equal to zero. When would this happen?).

Next you'll learn all about For loops.

Previous PageNext Page