Getting Started With Java

Java is one of the most popular programming languages in the world. Let's see what programs in Java look like, and learn how to write and run simple ones on a desktop or laptop computer.

Java Programming

The Java language was introduced in 1995 and quickly achieved worldwide popularity. Java is one of those "serious" languages for which programs of hundreds of millions of lines of code can be written. (The downside of this is that really simple programs tend to look overly complicated! Don't worry about that for now; you will get used to it.)

You can write a Java program to run

Regardless of the environment and any special set up required, this is the central concept of Java:

Every Java program is made up exclusively of a collection of (one or more) classes.

A First Program

Here is an example of a program that runs on a desktop or laptop. Do not try to understand every line of this code just yet. We'll cover all of it in class later.

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

If you already have the Java Development Kit on your computer, you can build and run this program as follows:

  1. Put the program above in a file called Greeter.java
  2. In a console, enter the command javac Greeter.java
  3. In a console, enter the command java Greeter

If you don't have the JDK on your computer, you will have to install it. Use a web search engine (like Google) to find out how.

A Few More Simple Programs

Here are a few programs, each illustrating one or more new concepts. Again, do not worry about trying to understand every single line of code. We'll talk about the details in class.

This program illustrates popup messages and imports.

import javax.swing.JOptionPane;
public class PopupGreeter {
    public static void main(String[] args) {
        JOptionPane.showMessageDialog(null, "Hello, World");
    }
}

Save this in PopupGreeter.java, Run javac PopupGreeter.java and then java PopupGreeter.

This next example illustrates comments, variables, and random number generation.

import java.util.Random;

/**
 * An application that simulates the rolling of two six-sided
 * dice.  Each time you run the program you get a potentially
 * different roll.
 */
public class PairOfDiceRoller {
    public static void main(String[] args) {
        Random generator = new Random();
        int die1 = generator.nextInt(6) + 1;
        int die2 = generator.nextInt(6) + 1;
        System.out.println("Rolled a " + die1 + " and a " + die2);
    }
}

This one shows off console input, if statements, the == and || operators, and trim.

/**
 * A program which asks the user for his or her name, then
 * says hello to that person.  If the user refuses to answer,
 * the program responds with an understanding comment.
 */
public class PersonalizedGreeter {
    public static void main(String[] args) {
        String name = System.console().readLine("Hi, what is your name? ");
        if (name == null || name.trim().equals("")) {
            System.out.println("It's okay to be shy.");
        } else {
            System.out.println("Hello, " + name + ".");
        }
    }
}

Now we introduce input from a dialog box, static imports and "\n".

import static javax.swing.JOptionPane.showInputDialog;
import static javax.swing.JOptionPane.showMessageDialog;

/**
 * An application that prompts the user for his or her given
 * and surnames, and replies with how the name might be formatted
 * on a French passport.
 */
public class FrenchNameComputer {
    public static void main(String[] args) {
        String given = showInputDialog("What is your given name?");
        String surname = showInputDialog("What is your surname?");
        showMessageDialog(null, "Your name might appear in France as\n\n" +
                surname.toUpperCase() + ", " + given);
    }
}

Instead of prompting the user to enter data on the console or in a dialog box, we can just take the data from the commandline arguments:

/**
 * An application which says hi to the person whoe name is
 * given as the sole command line argument.  If it is not the
 * case that exactly one command line argument is given, the
 * program complains.
 */
public class BrusqueGreeter {
    public static void main(String[] args) {
        if (args.length != 1) {
            System.out.println("A single command line argument is required");
        } else {
            System.out.printf("Hi, %s, whaddya want?", args[0]);
        }
    }
}

After coding this in BrusqueGreeter.java (of course), try this:

    javac BrusqueGreeter.java
    java BrusqueGreeter
    java BrusqueGreeter Pablo
    java BrusqueGreeter Pablo Honey

Now let's look at all the commandline arguments, for which the for-statement is very useful:

/**
 * An application which echoes all the commandline arguments
 * with r's and l's replaced with w's.  NOTE: This program does
 * not do the replacement as efficiently as it could.  At some
 * point we will talk about making it more efficient.
 */
public class Fuddifier {
    public static void main(String[] args) {
        for (String s: args) {
            System.out.print(s.replaceAll("[rlRL]", "w"));
            System.out.print(" ");
        }
        System.out.println();
    }
}

Try

    javac Fuddifier.java
    java Fuddifier
    java Fuddifier rascally rabbit
    java Fuddifier Rodney Rat likes spring lettuce and other greens
    java Fuddifier Release Roger!
Exercise: Can you fix this program so that it preserves capitalization of the r's and l's?

Notice that regardless of whether you get input from System.console().readLine() or showInputDialog or from command line arguments, input data are always strings (text), even if the text is composed entirely of digits!

/**
 * An application which writes the average of the command line arguments. It
 * does not tolerate errors very well.
 */
public class AverageFinder {
    public static void main(String[] args) {
        double total = 0.0;
        for (String s : args) {
            total += Double.parseDouble(s);
        }
        System.out.println("The average is " + total / args.length);
    }
}