notes


Getting Started

A Simple Program

So, let's try to forget about objects as much as possible for a bit and just learn the basic elements. Let's start with a simple hello world program that doesn't even create any objects:

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

There's always the class definition. No way around that. So here we make the class HelloWorld, but we don't give it anything other than a main method. The main method is the code that gets run when the class is run from the command line. In this case, after writing the above code into a file called HelloWorld.java, you enter the following at the prompt:

>javac HelloWorld.java
>java HelloWorld

You should then see "Hello World!" printed out on the console. The single command

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

is the only executable code in the program. It is the body of the main method. The other six lines in the program define the class structure. Whenever you run a Java program, you run the main method of some class. For now, to learn the basic syntax of java executable code without getting too mired in object-orientation, we'll use a class with just a main as above and put all our test code in the body of that main.

Command Line Arguments

Alright, so you want to know what that "String[] args" stuff means? Well, that's how the arguments you pass from the command line come in. For instance, if you had a class called Add that added two numbers, you might use it like:

>java Add 3 4

It would presumably print 7 after you pressed return. Here 3 and 4 are the two arguments. The "String[] args" in the main says that the arguments come in as an array of String objects, referenced in the code by the symbol args. An array is an ordered list of things, referenced by integers, starting at 0. The first argument is args[0], the second args[1], etc. We'll talk about arrays in detail more later. A String is a special Java object for holding a list of characters - basically any chunk of text. From the command line, all the "words" (chunks of text separated by one or more spaces) after the classname become Strings in the array passed to main. Here's a program that prints out the arguments passed in:

public class ShowArgs
{
    public static void main(String[] args)
    {
        for (int i=0; i<args.length; i++)
        {
	    System.out.println("args[" + i + "] is " + args[i]);
        }
    }
}

That's a for loop, the details of which we will study soon, but for now just understand that the System.out.println line is run once for each argument, with the value of i representing the index of that argument in the args array. For instance, if there were three arguments, it would take the values of 0, 1, and 2.

Console Input

Other than taking input from the command line call to the program, you can have the program take input from the user while it runs. The code for this is going to look a little bit more complex because some objects need to be created to handle the input, so bare with me. Notice how the System class has a member called out that we use for printing to the console in the code above? (System.out) Well, it has a member called in as well. System.in is an object of type InputStream. InputStream objects can give you bytes that represent characters from the keyboard. Now, bytes are just numbers and thus aren't so useful to us, so we have to first convert them to the equivalent characters that they represent and then group those characters into lines. First to get characters from bytes, we build an InputStreamReader around System.in like so:

InputStreamReader isr = new InputStreamReader(System.in);

Then we have a reference isr that refers to an object of type InputStreamReader that will give us characters if we ask for them, but we want whole lines, so we have to build a BufferedReader around the InputStreamReader like so:

BufferedReader br = new BufferedReader(isr);

Finally, we can get lines of input like so:

String line = br.readLine();

Or, if we want to continue reading lines:

String line;
while ( (line = br.readLine()) != null )
{
    // do something with line
}

So let's try to put these together into a little program that just reads console input and prints it back. We need two extra complications. First, we need to put this at the top:

import java.io.*;

This means we can call BufferedReader by that shorter name instead of its full name, java.io.BufferfedReader, and likewise with InputStreamReader. The second complication is that we have to to declare that the main method "throws Exception". When a piece of code encountered a problem that stops it from being able to complete its task, it will generally "throw an exception" to indicate this. The compiler won't compile your code unless all exceptions that you can throw or that code you call can throw are either caught or declared to be thrown. Since a BufferedReader or an InputStreamReader can throw an exception while trying to read text for you, you have to deal with it somehow. For now, don't worry about it, just declare that main throws Exception like so:

import java.io.*;

public class TakeInput
{
    public static void main(String[] args) throws Exception
    {
        InputStreamReader isr = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(isr);
	String line;
	System.out.print("say something, human: ");
	while ( (line = br.readLine()) != null)
        {
            System.out.println("you said: " + line);
            System.out.print("say something, human: ");
        }
    }
}