|How to Think Like a Computer Scientist|
source ref: ebookit.html
|Chapter 1:The way of the program.|
|chapter 2:Variables and types|
|Chapter 4:Conditionals, graphics, and recursion|
|Chapter 5:Methods that return things|
|Chapter 7:Strings and things|
|Chapter 8:Interesting objects|
|Chapter 9:Create your own objects|
|Chapter 11:Object methods|
|Chapter 12:Arrays of Objects|
|Chapter 13:Object-oriented programming|
As I mentioned in the last chapter, you can put as many statements as you want in main. For example, to print more than one line:
Also, as you can see, it is legal to put comments at the end of a line, as well as on a line by themselves.
The phrases that appear in quotation marks are called strings, because they are made up of a sequence (string) of letters. Actually, strings can contain any combination of letters, numbers, punctuation marks, and other special characters.
println is short for "print line," because after each line it adds a special character, called a newline, that causes the cursor to move to the next line of the display. The next time println is invoked, the new text appears on the next line.
Often it is useful to display the output from multiple print statements all on one line. You can do this with the print command:
In this case the output appears on a single line as Goodbye, cruel world!. Notice that there is a space between the word "Goodbye" and the second quotation mark. This space appears in the output, so it affects the behavior of the program.
Spaces that appear outside of quotation marks generally do not affect the behavior of the program. For example, I could have written:
This program would compile and run just as well as the original. The breaks at the ends of lines (newlines) do not affect the program's behavior either, so I could have written:
That would work, too, although you have probably noticed that the program is getting harder and harder to read. Newlines and spaces are useful for organizing your program visually, making it easier to read the program and locate syntax errors.
One of the most powerful features of a programming language is the ability to manipulate variables. A variable is a named location that stores a value. Values are things that can be printed and stored and (as we'll see later) operated on. The strings we have been printing ("Hello, World.", "Goodbye, ", etc.) are values.
In order to store a value, you have to create a variable. Since the values we want to store are strings, we will declare that the new variable is a string:
This statement is a declaration, because it declares that the variable named fred has the type String. All variables have a type that determines what kind of values it can store. For example, the int type can store integers, and it will probably come as no surprise that the String type can store strings.
You will notice that some types begin with a capital letter and some with lower-case. We will learn the significance of this distinction later, but for now you should take care to get it right. There is no such type as Int or string, and the compiler will object if you try to make one up.
To create an integer variable, the syntax is int bob;, where bob is the arbitrary name you made up for the variable. In general, you will want to make up variable names that indicate what you plan to do with the variable. For example, if you saw these variable declarations:
you could probably make a good guess at what values would be stored in them. This example also demonstrates the syntax for declaring multiple variables with the same type: hour and second are both integers (int type).
Now that we have created some variables, we would like to store values in them. We do that with an assignment statement.
This example shows three assignments, and the comments show three different ways people sometimes talk about assignment statements. The vocabulary can be confusing here, but the idea is straighforward:
A common way to represent variables on paper is to draw a box with the name of the variable on the outside and the value of the variable on the inside. This figure shows the effect of the three assignment statements:
For these diagrams I will use different shapes to indicate different variable types. These shapes should help remind you that one of the rules in Java is that a variable has to have the same type as the value you assign it. You cannot store a String in minute or an integer in fred. It would be like putting a square peg in a round hole.
On the other hand, that rule can be confusing, because there are many ways that you can convert values from one type to another, and Java sometimes converts things automatically. But for now you should remember that as a general rule variables and values have the same type, and we'll talk about special cases later.
Another source of confusion is that some strings look like integers, but they are not. For example, fred can contain the string "123", which is made up of the characters 1, 2 and 3, but that is not the same thing as the number 123.
You can print the value of a variable using the same commands we used to print strings.
This program creates a variable named firstLine, assigns it the value "Hello, again!" and then prints that value. When we talk about "printing a variable," we mean printing the value of the variable. To print the name of a variable, you have to put it in quotes (and make it a string). For example: System.out.println ("firstLine");
If you want to get a little tricky, you could write
The output of this program is
I am pleased to report that the syntax for printing a variable is the same regardless of the variable's type.
The output of this program is The current time is 11:59.
WARNING: It is common practice to use several print commands followed by a println, in order to put multiple values on the same line. But you have to be careful to remember the println at the end. In many environments, the output from print is stored without being displayed until the println command is invoked, at which point the entire line is displayed at once. If you omit println, the program may terminate without ever displaying the stored output!
A few sections ago, I said that you can make up any name you want for your variables, but that's not quite true. There are certain words that are reserved in Java because they are used by the compiler to parse the structure of your program, and if you use them as variable names, it will get confused. These words, called keywords, include public, class, void, int, and many more.
The complete list is available at
This WWW site, provided by Sun, includes Java documentation I will be referring to throughout this book.
Rather than memorize the list, I would suggest that you take advantage of a feature provided in many Java development environments, which is code highlighting--as you type, different parts of your program should appear in different colors. For example, keywords might be blue, strings red, and other code black. If you type a variable name and it turns blue, watch out! You might get some strange behavior from the compiler.
Operators are special symbols that are used to represent simple computations like addition and multiplication. Most of the operators in Java do exactly what you would expect them to do, because they are common mathematical symbols. For example, the operator for adding two integers is +.
The following are all legal Java expressions whose meaning is more or less obvious:
Expressions can contain both variable names and numbers. In each case the name of the variable is replaced with its value before the computation is performed.
Addition, subtraction and multiplication all do what you expect, but you might be suprised by division. For example, the following program:
would generate the following output:
The first line is what we expected, but the second line is odd. The value of the variable minute is 59, and 59 divided by 60 is 0.98333, not 0. The reason for the discrepancy is that Java is performing integer division.
When both of the operands are integers (operands are the things operators operate on), the result must also be in integer, and by convention integer division always rounds down, even in cases like this where the next integer is so close.
A possible alternative in this case is to calculate a percentage rather than a fraction:
The result is:
Again the result is rounded down, but at least now the answer is approximately correct. In order to get an even more accurate answer, we could use a different type of variable, called floating-point, that is capable of storing fractional values. We'll get to that in the next chapter.
When more than one operator appears in an expression the order of evaluation depends on the rules of precedence. A complete explanation of precedence can get complicated, but just to get you started:
In general you cannot perform mathematical operations on strings, even if the strings look like numbers. The following are illegal (if we know that fred has type String)
By the way, can you tell by looking at those expressions whether fred is an integer or a string? Nope. The only way to tell the type of a variable is to look at the place where it is declared.
Interestingly, the + operator does work with strings, although it does not do exactly what you might expect. For strings, the + operator represents concatenation, which means joining up the two operands by linking them end-to-end. So "Hello, " + "world." yields the string "Hello, world." and fred + "ism" adds the suffix ism to the end of whatever fred is, which is often handy for naming new forms of bigotry.
So far we have looked at the elements of a programming language--variables, expressions, and statements--in isolation, without talking about how to combine them.
One of the most useful features of programming languages is their ability to take small building blocks and compose them. For example, we know how to add numbers and we know how to print; it turns out we can do both at the same time:
Actually, I shouldn't say "at the same time," since in reality the multiplication has to happen before the printing, but the point is that any expression, involving numbers, strings, and variables, can be used inside a print statement. We've already seen one example:
But you can also put arbitrary expressions on the right-hand side of an assignment statement:
This ability may not seem so impressive now, but we will see other examples where composition makes it possible to express complex computations neatly and concisely.
WARNING: There are limits on where you can use certain expressions; most notably, the left-hand side of an assignment statement has to be a variable name, not an expression. That's because the left side indicates the storage location where the result will go. Expressions do not represent storage locations, only values. So the following is illegal: minute+1 = hour;.