Session 1: Introduction

About Java (Not in text)
A basic program (Section 2.1)
Pieces of a program (Section 2.3)
    Code
    White space
    Comments
Variables (Section 2.4)
    Definition
    Declaring a variable
    Assigning a value

About Java

Textbook: Not in text

Historically, Java comes from two sources: C++ and Smalltalk.

In any case, Java's developers came along in 1991 and decided to design a new language. They basically took C++'s syntax, but decided not to worry about backwards compatibility with C. They also rethought C++'s additions to C - often deciding not to add C++ features to keep things simpler and closer to the elegance of Smalltalk. The result is something that looks vaguely like C++, but which is definitely distinctly different.

Java's designers made an astonishing number of correct decisions. The first modern version was released in 1995 (Java 1.0), and the developers succeeded in linking the Web with Java. Since the Web was particularly hot in 1995, so did Java quickly become. There was lots of hype, and Java gained its foothold.

Since then, the hype has largely dissapated, but Java has remained in wide use. It's a good language - the design isn't perfect, but it's much better than any previous language that gained such prominence in industrial programming (FORTRAN, C, C++). In its first five years, it has proven to have lasting power.

Now colleges across the country teach Java as their first language, happy to break free from the inelegant C++ while still teaching a language that people use in industry.

In the near future, Java will likely increase in importance, as more Java experts graduate and industry continues to switch their applications over to Java with the realization that it is easier to use than C++. C++ will continue to hold onto a large share - both because of the large base of already-existing C++ programs, and because Java's inefficiencies are unacceptable in some applications. My personal prediction is that in the next several years, Java and C++ will be the two prominent languages (with over 90% of production-quality software development between them), and that each would have an equal share.

A basic program

Textbook: Section 2.1

Consider the following program.

import csbsju.cs160.*;

public class Hello {
    public static void run() {
        IO.println("hello world!");
    }
}
This basic program illustrates the overall structure of a Java program.
class definition
    method definitions
        statements
For the moment, think of a class as a program and a method as a sequence of instructions saying what to do. (Over the next few weeks, we'll refine our understanding to be more accurate. But this one will work fine for now.)

(At this point, I want to get my terminology straight. A brace is either '{' or '}'. Some people redundantly call this a curly brace; I won't. A bracket is either '[' or ']'. Some people redundantly call this a square bracket; I won't. A parenthesis is either '(' or ')'.)

The first line of our example program is the following.

import csbsju.cs160.*;
This just says that we're going to use some stuff defined especially for this class. We'll include this line on every program we write throughout this course. Get used to it.

In our example program, we've defined the Hello class. Our definition of the class looks something like this.

public class Hello {
    method definitions
}
We could have named the program whatever we wanted, but the words public class and the set of braces are required. Within the braces, we place whatever method definitions we need.

In this case, we defined its run() method. The definition of the run() method looks like this:

    public static void run() {
        statements
    }
Again, we could have named the method whatever we wanted (we chose run(), but the words public static void and the set of braces are required.

Within the braces of the method, we list the statements that the computer should execute we tell the computer to execute run(). In this case, there's just one statement to execute:

        IO.println("hello world!");
This particular line prints the world ``hello world!'' into a window on the screen.

We could modify the program to do something slightly more interesting. Try modifying the body of the run() method:

    public static void run() {
        IO.println("hello world!");
        IO.println("good-bye");
    }
Now, when we run run(), two things happen: first it prints ``hello world!'' and then it prints ``good-bye''.

For the next several days, we'll be concentrating on what we can put within the body of that method. Don't worry about the rest of the program for now - we'll get to it when it's time.

Pieces of a program

Textbook: Section 2.3

A Java program is a combination of basically three types of data.

Code

The most important part of the program is the code. This is the part that is actually meaningful to the compiler.

Java ignores all space in a program - it only pays attentions to actual visible letters. When a Java compiler sees a program, the first thing it does is break it into a sequence of tokens. A token is an atomic piece of a program that is meaningful to the compiler. Our particular program breaks into the following atomic pieces. Here are the tokens of the above program.

import          csbsju          .               cs160
.               *               ;               public
class           Hello           {               public
static          void            run             (
)               {               IO              .
println         (               "hello  world!" )
;               }               }
A token is basically a word or a symbol. But in the case of the string of letters "hello world!", it kept the whole thing together, since in the structure of the program, the only important thing is that these characters constitute a string.

White space

Tabs, spaces, and end-of-lines are completely immaterial part of the program as far as the compiler is concerned. But they're integral to the program from the programmer's point of view. For our eyes, the white space is critical to discerning structure in a program.

So it's important when you're programming to pay close attention to white space. You'll see that I use a particular system: Every time I reach a set of braces, I put an opening brace at the end of a line, indent everything within the brace, and put a matching brace on the previous level of indentation.

brace-block prefix {
    first line of brace-block body
    second line of brace-block body
    last line of brace-block body
}
This is a standard technique of white space placement that has stood the test of time for thirty years. There are a couple other techniques that people have developed that have also been in wide use for thirty years - those are fine too.

But it's critical that you choose a rigorous, well-tested white-space insertion technique and stick to it rigorously. Without consistent, good white space, programs are much more difficult to understand.

I also find it very useful to insert blank lines every 10 lines or so - wherever I'm starting a relatively new concept. I think of these as paragraphs. This is because long blocks of code are difficult to understand - you need something to break it up into conceptual pieces.

Comments

We haven't seen comments yet, but they constitute a third type of data occurring in a program. There are two types of Java comments.

Like whitespace, comments are also trimmed off by the compiler before it begins the real work. But comments are useful for documenting how a program works. Generally, they should be there to describe the forest instead of the trees - the code itself usually does the trees quite well, but it's difficult to discern the overall point of the program without some comments explaining.

You should generally use the first type of comment wherever possible. If you do this rigorously, then the second type becomes very useful whenever you want to try removing a large segment of the program at once. (You can't put the second type of comment within itself, since the */ of the inside comment will terminate the overall comment. So if you use the second type for normal programming, it's quite inconvenient to try to comment out large pieces of the program during debugging.)

Variables

Textbook: Section 2.4

Definition

A variable is just a place in memory. From the programmer's point of view, a Java variable has three things associated with it.

Declaring a variable

Before you use a variable, you first have to tell Java that it exists so that the compiler knows about it. This is a declaration. To declare a variable in Java, type the type name followed by the variable name followed by a semicolon.

        int i;
If you want, you can declare several variables of the same type on the same line.
        int i, num_students, total_grade;
In general, I recommend against this practice; declare only one variable per line. This makes it easier to find the variable names and the code easier to edit.

The scope of a variable is the area of the program where you can use it. In Java, a variable's scope begins at the point of the variable's declaration and proceeds to the end of the innermost brace pair in which the declaration lies.

import csbsju.cs160.*;

public class Example {
    public static void run() {
        IO.println("hello world!");
        ... {
            // i isn't usable here
            int i;
            // now it is
            ... {
                // we can still use i within this brace pair
            }
            // and we're still within the brace pair
        }
        // but now we're out of the brace pair; i is unavailable
    }
}

Assigning a value

To assign a value to a variable, type the variable name, followed by an equal sign, followed by the value, followed by a semicolon.

        i = 2;
From here on, the variable's value is 2.

It's often convenient to combine the declaration and the first assignment.

        int i = 2;

What do you think the testI() method will print?

import csbsju.cs160.*;

public class Example {
    public static void testI() {
        int i;
        i = 2;
        IO.println("i");
        IO.println(i);
        i = 5;
        IO.println(i);
    }
}

Constants like 2 have an immediately recognizable type. In the case of integers, a constant is just a sequence of digits. For double values, the constant contains a decimal point (or an exponent, as in 3e8, which represents 3×108). For boolean constants, the only permissible values are true and false. And for characters, you type the character in a set of single quotes: 'A' (the capital A character) or ' ' (the space character). It's important that the character be in quotes; otherwise, the compiler will understand it as a variable name (or whitespace, or whatever else is appropriate).