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
Textbook: Not in text
Historically, Java comes from two sources: C++ and Smalltalk.
Unfortunately, C++ suffers from two major problems. First, because the C++ designers considered it important to keep a superset of C (so that any C program is a good C++ program), C++ had to maintain a large number of ideas from C that didn't really work well in their modified language. Second, the C++ developers ended up with a very complicated language, to the point that you can't really hope to understand the entire language.
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.
Textbook: Section 2.1
Consider the following program.
This basic program illustrates the overall structure of a Java program.import csbsju.cs160.*; public class Hello { public static void run() { IO.println("hello world!"); } }
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.)class definition method definitions statements
(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.
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.import csbsju.cs160.*;
In our example program, we've defined the Hello class. Our definition of the class looks something like this.
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.public class Hello { method definitions }
In this case, we defined its run() method. The definition of the run() method looks like this:
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.public static void run() { statements }
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:
This particular line prints the world ``hello world!'' into a window on the screen.IO.println("hello world!");
We could modify the program to do something slightly more interesting. Try modifying the body of the run() method:
Now, when we run run(), two things happen: first it prints ``hello world!'' and then it prints ``good-bye''.public static void run() { IO.println("hello world!"); IO.println("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.
Textbook: Section 2.3
A Java program is a combination of basically three types of data.
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.
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.import csbsju . cs160 . * ; public class Hello { public static void run ( ) { IO . println ( "hello world!" ) ; } }
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.
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.brace-block prefix { first line of brace-block body second line of brace-block body last line of brace-block body }
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.
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.
IO.println("hello world!"); // this comment explains itself IO.println("good-bye!"); // this comment does also
IO.println("hello world!"); /* this comment explains itself. Notice that it extends to the second line with no problem. Or even a third line. Now it ends: */
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.)
Textbook: Section 2.4
A variable is just a place in memory. From the programmer's point of view, a Java variable has three things associated with it.
Names of variables (and classes and methods) can be any sequence of letters, digits, and underscores '_', but the name must not begin with a digit.
The typical Java convention is to name variables will all lower-case letters, with underscores separating different words. Some typical variable names are i, width, and grid_height. Java programmers use this convention for variables, but they use different conventions for class names and method names. By doing this, they can immediately recognize the purpose of an identifier.
For example, the naming convention for classes is to include no underscores and capitalize each word: DrawableFrame. For method names, the convention is the same, except the first letter is lower-case: runProgram().
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.
If you want, you can declare several variables of the same type on the same line.int i;
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.int i, num_students, total_grade;
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 } }
To assign a value to a variable, type the variable name, followed by an equal sign, followed by the value, followed by a semicolon.
From here on, the variable's value is 2.i = 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).