Chapter 1. Dive in A Quick Dip: Breaking the Surface

image with no caption

Java takes you to new places. From its humble release to the public as the (wimpy) version 1.02, Java seduced programmers with its friendly syntax, object-oriented features, memory management, and best of all—the promise of portability. The lure of write-once/run-anywhere is just too strong. A devoted following exploded, as programmers fought against bugs, limitations, and, oh yeah, the fact that it was dog slow. But that was ages ago. If you’re just starting in Java, you’re lucky. Some of us had to walk five miles in the snow, uphill both ways (barefoot), to get even the most trivial applet to work. But you, why, you get to ride the sleeker, faster, much more powerful Java of today.

image with no caption

The Way Java Works

The goal is to write one application (in this example, an interactive party invitation) and have it work on whatever device your friends have.

image with no caption
image with no caption

What you’ll do in Java

You’ll type a source code file, compile it using the javac compiler, then run the compiled bytecode on a Java virtual machine.

image with no caption
image with no caption


(Note: this is not meant to be a tutorial... you’ll be writing real code in a moment, but for now, we just want you to get a feel for how it all fits together.)

A very brief history of Java

image with no caption
image with no caption
image with no caption

Code structure in Java

image with no caption

Put a class in a source file.

Put methods in a class.

Put statements in a method.

What goes in a source file?

A source code file (with the .java extension) holds one class definition. The class represents a piece of your program, although a very tiny application might need just a single class. The class must go within a pair of curly braces.

image with no caption

What goes in a class?

A class has one or more methods. In the Dog class, the bark method will hold instructions for how the Dog should bark. Your methods must be declared inside a class (in other words, within the curly braces of the class).

image with no caption

What goes in a method?

Within the curly braces of a method, write your instructions for how that method should be performed. Method code is basically a set of statements, and for now you can think of a method kind of like a function or procedure.

image with no caption

Anatomy of a class

When the JVM starts running, it looks for the class you give it at the command line. Then it starts looking for a specially-written method that looks exactly like:

public static void main (String[] args) {
   // your code goes here

Next, the JVM runs everything between the curly braces { } of your main method. Every Java application has to have at least one class, and at least one main method (not one main per class; just one main per application).

image with no caption


Don’t worry about memorizing anything right now... this chapter is just to get you started.

Writing a class with a main

In Java, everything goes in a class. You’ll type your source code file (with a .java extension), then compile it into a new class file (with a .class extension). When you run your program, you’re really running a class.

Running a program means telling the Java Virtual Machine (JVM) to “Load the MyFirstApp class, then start executing its main() method. Keep running ‘til all the code in main is finished.”

In Chapter 2, we go deeper into the whole class thing, but for now, all you need to think is, how do I write Java code so that it will run? And it all begins with main().

The main() method is where your program starts running.

No matter how big your program is (in other words, no matter how many classes your program uses), there’s got to be a main() method to get the ball rolling.

image with no caption
image with no caption

What can you say in the main method?

Once you’re inside main (or any method), the fun begins. You can say all the normal things that you say in most programming languages to make the computer do something.

Your code can tell the JVM to:

image with no caption
  1. do something

    Statements: declarations, assignments, method calls, etc.

    int x = 3;
    String name = "Dirk";
    x = x * 17;
    System.out.print("x is " + x);
    double d = Math.random();
    // this is a comment
  2. do something again and again

    Loops: for and while

    while (x > 12) {
       x = x - 1;
    for (int x = 0; x < 10; x = x + 1) {
       System.out.print("x is now " + x);
  3. do something under this condition

    Branching: if/else tests

    if (x == 10) {
       System.out.print("x must be 10");
    } else {
       System.out.print("x isn't 10");
    if ((x < 3) & (name.equals("Dirk"))) {
    System.out.print("this line runs no matter what");
image with no caption

Looping and looping and...

Java has three standard looping constructs: while, do-while, and for. You’ll get the full loop scoop later in the book, but not for awhile, so let’s do while for now.

The syntax (not to mention logic) is so simple you’re probably asleep already. As long as some condition is true, you do everything inside the loop block. The loop block is bounded by a pair of curly braces, so whatever you want to repeat needs to be inside that block.

The key to a loop is the conditional test. In Java, a conditional test is an expression that results in a boolean value—in other words, something that is either true or false.

If you say something like, “While iceCreamInTheTub is true, keep scooping”, you have a clear boolean test. There either is ice cream in the tub or there isn’t. But if you were to say, “While Bob keep scooping”, you don’t have a real test. To make that work, you’d have to change it to something like, “While Bob is snoring...” or “While Bob is not wearing plaid...”

Simple boolean tests

You can do a simple boolean test by checking the value of a variable, using a comparison operator including:

< (less than)

> (greater than)

== (equality) (yes, that’s two equals signs)

Notice the difference between the assignment operator (a single equals sign) and the equals operator (two equals signs). Lots of programmers accidentally type = when they want ==. (But not you.)

int x = 4; // assign 4 to x
while (x > 3) {
  // loop code will run because
  // x is greater than 3
  x = x - 1; // or we'd loop forever
int z = 27; //
while (z == 17) {
  // loop code will not run because
  // z is not equal to 17

Example of a while loop

image with no caption

Conditional branching

In Java, an if test is basically the same as the boolean test in a while loop – except instead of saying, “while there’s still beer...”, you’ll say, “if there’s still beer...”

image with no caption

The code above executes the line that prints “x must be 3” only if the condition (x is equal to 3) is true. Regardless of whether it’s true, though, the line that prints, “This runs no matter what” will run. So depending on the value of x, either one statement or two will print out.

But we can add an else to the condition, so that we can say something like, “If there’s still beer, keep coding, else (otherwise) get more beer, and then continue on...”

image with no caption

System.out.print vs. System.out.println

If you’ve been paying attention (of course you have) then you’ve noticed us switching between print and println.

Did you spot the difference?

System.out.println inserts a newline (think of println as printnewline while System.out.print keeps printing to the same line. If you want each thing you print out to be on its own line, use println. If you want everything to stick together on one line, use print.

Coding a Serious Business Application

Let’s put all your new Java skills to good use with something practical. We need a class with a main(), an int and a String variable, a while loop, and an if test. A little more polish, and you’ll be building that business back-end in no time. But before you look at the code on this page, think for a moment about how you would code that classic children’s favorite, “99 bottles of beer.”

image with no caption
public class BeerSong {
   public static void main (String[] args) {
     int beerNum = 99;
     String word = "bottles";

   while (beerNum > 0) {

      if (beerNum == 1) {
        word = "bottle"; // singular, as in ONE bottle.

      System.out.println(beerNum + " " + word + " of beer on the wall");
      System.out.println(beerNum + " " + word + " of beer.");
      System.out.println("Take one down.");
      System.out.println("Pass it around.");
      beerNum = beerNum - 1;

      if (beerNum > 0) {
         System.out.println(beerNum + " " + word + " of beer on the wall");
      } else {
         System.out.println("No more bottles of beer on the wall");
     } // end else
   } // end while loop
 } // end main method
} // end class

There’s still one little flaw in our code. It compiles and runs, but the output isn’t 100% perfect. See if you can spot the flaw, and fix it.

Monday morning at Bob’s

Bob’s alarm clock rings at 8:30 Monday morning, just like every other weekday. But Bob had a wild weekend, and reaches for the SNOOZE button. And that’s when the action starts, and the Java-enabled appliances come to life.

image with no caption

First, the alarm clock sends a message to the coffee maker[2] “Hey, the geek’s sleeping in again, delay the coffee 12 minutes.”

The coffee maker sends a message to the Motorola™ toaster, “Hold the toast, Bob’s snoozing.”

image with no caption

The alarm clock then sends a message to Bob’s Nokia Navigator™ cell phone, “Call Bob’s 9 o’clock and tell him we’re running a little late.”

image with no caption

Finally, the alarm clock sends a message to Sam’s (Sam is the dog) wireless collar, with the too-familiar signal that means, “Get the paper, but don’t expect a walk.”

image with no caption

A few minutes later, the alarm goes off again. And again Bob hits SNOOZE and the appliances start chattering. Finally, the alarm rings a third time. But just as Bob reaches for the snooze button, the clock sends the “jump and bark” signal to Sam’s collar. Shocked to full consciousness, Bob rises, grateful that his Java skills and a little trip to Radio Shack™ have enhanced the daily routines of his life.

His toast is toasted.

His coffee steams.

His paper awaits.

image with no caption

Just another wonderful morning in The Java-Enabled House.

You can have a Java-enabled home. Stick with a sensible solution using Java, Ethernet, and Jini technology. Beware of imitations using other so-called “plug and play” (which actually means “plug and play with it for the next three days trying to get it to work”) or “portable” platforms. Bob’s sister Betty tried one of those others, and the results were, well, not very appealing, or safe. Bit of a shame about her dog, too...

Could this story be true? Yes and no. While there are versions of Java running in devices including PDAs, cell phones (especially cell phones), pagers, rings, smart cards, and more –you might not find a Java toaster or dog collar. But even if you can’t find a Java-enabled version of your favorite gadget, you can still run it as if it were a Java device by controlling it through some other interface (say, your laptop) that is running Java. This is known as the Jini surrogate architecture. Yes you can have that geek dream home.

image with no caption

OK, so the beer song wasn’t really a serious business application. Still need something practical to show the boss? Check out the Phrase-O-Matic code.


note: when you type this into an editor, let the code do its own word/line-wrapping! Never hit the return key when you’re typing a String (a thing between “quotes”) or it won’t compile. So the hyphens you see on this page are real, and you can type them, but don’t hit the return key until AFTER you’ve closed a String.

public class PhraseOMatic {
   public static void main (String[] args) {
  1.      // make three sets of words to choose from. Add your own!
         String[] wordListOne = {"24/7","multi-
    Tier","30,000 foot","B-to-B","win-win","frontend",
    "web-based","pervasive", "smart", "sixsigma","
    critical-path", "dynamic"};
       String[] wordListTwo = {"empowered", "sticky",
    "value-added", "oriented", "centric", "distributed",
    "clustered", "branded","outside-the-box", "positioned",
    "networked", "focused", "leveraged", "aligned",
    "targeted", "shared", "cooperative", "accelerated"};
        String[] wordListThree = {"process", "tippingpoint",
    "solution", "architecture", "core competency",
    "strategy", "mindshare", "portal", "space", "vision",
    "paradigm", "mission"};
  2. // find out how many words are in each list
    int oneLength = wordListOne.length;
    int twoLength = wordListTwo.length;
    int threeLength = wordListThree.length;
  3. // generate three random numbers
    int rand1 = (int) (Math.random() * oneLength);
    int rand2 = (int) (Math.random() * twoLength);
    int rand3 = (int) (Math.random() * threeLength);
  4.    // now build a phrase
       String phrase = wordListOne[rand1] + " " +
    wordListTwo[rand2] + " " + wordListThree[rand3];
  5.   // print out the phrase
      System.out.println("What we need is a " + phrase);


How it works

In a nutshell, the program makes three lists of words, then randomly picks one word from each of the three lists, and prints out the result. Don’t worry if you don’t understand exactly what’s happening in each line. For gosh sakes, you’ve got the whole book ahead of you, so relax. This is just a quick look from a 30,000 foot outside-the-box targeted leveraged paradigm.

  1. The first step is to create three String arrays – the containers that will hold all the words. Declaring and creating an array is easy; here’s a small one:

    String[] pets = {"Fido", "Zeus", "Bin"};

    Each word is in quotes (as all good Strings must be) and separated by commas.

  2. For each of the three lists (arrays), the goal is to pick a random word, so we have to know how many words are in each list. If there are 14 words in a list, then we need a random number between 0 and 13 (Java arrays are zero-based, so the first word is at position 0, the second word position 1, and the last word is position 13 in a 14-element array). Quite handily, a Java array is more than happy to tell you its length. You just have to ask. In the pets array, we’d say:

    int x = pets.length;

    and x would now hold the value 3.

  3. We need three random numbers. Java ships out-of-the-box, off-the-shelf, shrink-wrapped, and core competent with a set of math methods (for now, think of them as functions). The random() method returns a random number between 0 and not-quite-1, so we have to multiply it by the number of elements (the array length) in the list we’re using. We have to force the result to be an integer (no decimals allowed!) so we put in a cast (you’ll get the details in Chapter 4). It’s the same as if we had any floating point number that we wanted to convert to an integer:

    int x = (int) 24.6;
  4. Now we get to build the phrase, by picking a word from each of the three lists, and smooshing them together (also inserting spaces between words). We use the “+” operator, which concatenates (we prefer the more technical ‘smooshes’) the String objects together. To get an element from an array, you give the array the index number (position) of the thing you want using:

    String s = pets[0]; // s is now the String "Fido"
    s = s + " " + "is a dog"; // s is now "Fido is a dog"
  5. Finally, we print the phrase to the command-line and... voila! We’re in marketing.

what we need here is a...

pervasive targeted process

dynamic outside-the-box tipping-point

smart distributed core competency

24/7 empowered mindshare

30,000 foot win-win vision

six-sigma networked portal

[2] IP multicast if you’re gonna be all picky about protocol

Get Head First Java, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.