text:
The Way of the Java/Introduction

The Way of the Java

The goal of this book, and this class, is to teach you to think like a computer scientist. I like the way computer scientists think because they combine some of the best features of Mathematics, Engineering, and Natural Science. Like mathematicians, computer scientists use formal languages to denote ideas (specifically computations). Like engineers, they design things, assembling components into systems and evaluating tradeoffs among alternatives. Like scientists, they observe the behavior of complex systems, form hypotheses, and test predictions.

The single most important skill for a computer scientist is problem-solving. By that I mean the ability to formulate problems, think creatively about solutions, and express a solution clearly and accurately. As it turns out, the process of learning to program is an excellent opportunity to practice problem-solving skills. That is why this chapter is called The way of the program.

On one level, you will be learning to program, which is a useful skill by itself. On another level you will use programming as a means to an end. As we go along, that end will become clearer.

What is a programming language?
The programming language you will be learning is Java, which is relatively new (Sun released the first version in May, 1995). Java is an example of a high-level language; other high-level languages you might have heard of are C, C++, Pascal, and FORTRAN.

As you might infer from the name high-level language, there are also low-level languages, sometimes referred to as machine language or assembly language. Loosely-speaking, computers can only execute programs written in low-level languages. Thus, programs written in a high-level language have to be translated before they can run. This translation takes some time, which is a small disadvantage of high-level languages.

But the advantages are enormous. First, it is much easier to program in a high-level language; by easier I mean that the program takes less time to write, it is shorter and easier to read, and it is more likely to be correct. Secondly, high-level languages are portable, meaning that they can run on different kinds of computers with few or no modifications. Low-level programs can only run on one kind of computer, and have to be rewritten to run on another.

Due to these advantages, almost all programs are written in high-level languages. Low-level languages are only used for a few special applications.

Compilation vs interpretation
There are two ways to translate a program; interpreting or compiling. An interpreter is a program that reads a high-level program and does what it says. In effect, it translates the program line-by-line, alternately reading lines and carrying out commands. Examples of interpreted languages are BASIC, Perl, and Python.

A compiler is a program that reads a high-level program and translates it all at once, before executing any of the commands. Often you compile the program as a separate step, and then execute the compiled code later. In this case, the high-level program is called the source code, and the translated program is called the executable.

As an example, suppose you write a program in C. You might use a text editor to write the program (a text editor is a simple word processor). When the program is finished, you might save it in a file named program.c, where program is an arbitrary name you make up, and the suffix .c is a convention that indicates that the file contains C source code.

Then, depending on what your programming environment is like, you might leave the text editor and run the compiler. The compiler would read your source code, translate it, and create a new file named program.o to contain the object code, or program.exe to contain the executable.

The Java platform
The Java language is unusual because it is both compiled and interpreted. Instead of translating Java programs into machine language, the Java compiler generates Java byte code. Byte code is easy (and fast) to interpret, like machine language, but it is also portable, like a high-level language. Thus, it is possible to compile a Java program on one machine, transfer the byte code to another machine over a network, and then interpret the byte code on the other machine. This ability is one of the advantages of Java over many other high-level languages.

Although this process may seem complicated, the good news is that in most programming environments (sometimes called development environments), these steps are automated for you. Usually you will only have to write a program and type a single command to compile and run it. On the other hand, it is useful to know what the steps are that are happening in the background, so that if something goes wrong you can figure out what it is.

What is a program?
A program's source code contains a sequence of instructions that specifies how to perform a computation. The computation might be something mathematical, like solving a system of equations or finding the roots of a polynomial, but it can also be a symbolic computation, like searching and replacing text in a document or (strangely enough) compiling a program.

The instructions (or commands, or statements) look different in different programming languages, but there are a few basic functions that appear in just about every language:
 * input—Get data from the keyboard, or a file, or some other device.
 * output—Display data on the screen or send data to a file or other device.
 * math—Perform basic mathematical operations like addition and multiplication.
 * testing—Check for certain conditions and execute the appropriate sequence of statements.
 * repetition—Perform some action repeatedly, usually with some variation.

Believe it or not, that is pretty much all there is to it. Every program you have ever used, no matter how complicated, is made up of functions that look more or less like these. Thus, one way to describe programming is the process of breaking a large, complex task up into smaller and smaller subtasks until eventually the subtasks are simple enough to be performed with one of these simple functions.

What is debugging?
Programming is a complex process, and since it is done by human beings, it often leads to errors. For whimsical reasons, programming errors are called bugs and the process of tracking them down and correcting them is called debugging.

There are a few different kinds of errors that can occur in a program, and it is useful to distinguish between them in order to track them down more quickly.

Compile-time errors
The compiler can only translate a program if the program is syntactically correct; otherwise, the compilation fails and you will not be able to run your program. Syntax refers to the structure of your program and the rules about that structure.

Syntax
For example, in English, a sentence must begin with a capital letter and end with a period. this sentence contains a syntax error. So does this one

For most readers, a few syntax errors are not a significant problem, which is why we can read the poetry of E. E. Cummings without spewing error messages.

Compilers are not so forgiving. If there is a single syntax error anywhere in your program, the compiler will print an error message and quit, and you will not be able to run your program.

To make matters worse, there are more syntax rules in Java than there are in English, and the error messages you get from the compiler are often not very helpful. During the first few weeks of your programming career, you will probably spend a lot of time tracking down syntax errors. As you gain experience, though, you will make fewer errors and find them faster.

Run-time errors
The second type of error is a run-time error, so-called because the error does not appear until you run the program. In Java, run-time errors occur when the interpreter is running the byte code and something goes wrong.

The good news for now is that Java tends to be a safe language, which means that run-time errors are rare, especially for the simple sorts of programs we will be writing for the next few weeks.

Later on in the semester, you will probably start to see more run-time errors, especially when we start talking about objects and references (Chapter objects).

In Java, run-time errors are called exceptions, and in most environments they appear as windows or dialog boxes that contain information about what happened and what the program was doing when it happened. This information is useful for debugging.

Logic errors and semantics
The third type of error is the logical or semantic error. If there is a logical error in your program, it will compile and run successfully, in the sense that the computer will not generate any error messages, but it will not do the right thing. It will do something else. Specifically, it will do what you told it to do.

The problem is that the program you wrote is not the program you wanted to write. The meaning of the program (its semantics) is wrong. Identifying logical errors can be tricky, since it requires you to work backwards by looking at the output of the program and trying to figure out what it is doing.

Experimental debugging
One of the most important skills you will acquire in this class is debugging. Although it can be frustrating, debugging is one of the most intellectually rich, challenging, and interesting parts of programming.

In some ways debugging is like detective work. You are confronted with clues and you have to infer the processes and events that lead to the results you see.

Debugging is also like an experimental science. Once you have an idea what is going wrong, you modify your program and try again. If your hypothesis was correct, then you can predict the result of the modification, and you take a step closer to a working program. If your hypothesis was wrong, you have to come up with a new one. As Sherlock Holmes pointed out, “When you have eliminated the impossible, whatever remains, however improbable, must be the truth.” (from A. Conan Doyle's The Sign of Four).

Holmes, Sherlock Doyle, Arthur Conan

For some people, programming and debugging are the same thing. That is, programming is the process of gradually debugging a program until it does what you want. The idea is that you should always start with a working program that does something, and make small modifications, debugging them as you go, so that you always have a working program.

For example, Linux is an operating system that contains thousands of lines of code, but it started out as a simple program Linus Torvalds used to explore the Intel 80386 chip. According to Larry Greenfield, “One of Linus's earlier projects was a program that would switch between printing AAAA and BBBB. This later evolved to Linux” (from The Linux Users' Guide Beta Version 1).

In later chapters I will make more suggestions about debugging and other programming practices.

Formal languages vs. natural languages
Natural languages are the languages that people speak, like English, Spanish, and French. They were not designed by people (although people try to impose some order on them); they evolved naturally.

Formal languages are languages that are designed by people for specific applications. For example, the notation that mathematicians use is a formal language that is particularly good at denoting relationships among numbers and symbols. Chemists use a formal language to represent the chemical structure of molecules. Likewise, programming languages are formal languages that have been designed to express computations.

When you read a sentence in English or a statement in a formal language, you have to figure out what the structure of the sentence is (although in a natural language you do this subconsciously). This process is called parsing.

For example, when you hear the sentence, “The other shoe fell,” you understand that “the other shoe” is the subject and “fell” is the verb. Once you have parsed a sentence, you can figure out what it means, that is, the semantics of the sentence. Assuming that you know what a shoe is, and what it means to fall, you will understand the general implication of this sentence.

Although formal and natural languages have many features in common(tokens, structure, syntax and semantics, etc.), there are many differences:
 * ambiguity Natural languages are full of ambiguity, which people deal with by using contextual clues and other information. Formal languages are designed to be nearly or completely unambiguous, which means that any statement has exactly one meaning, regardless of context.
 * redundancy In order to make up for ambiguity and reduce misunderstandings, natural languages employ lots of redundancy. As a result, they are often verbose. Formal languages are less redundant and more concise.
 * literalness Natural languages are full of idiom and metaphor. If I say, “The other shoe fell,” there is probably no shoe and nothing falling. Formal languages mean exactly what they say.

People who grow up speaking a natural language (everyone) often have a hard time adjusting to formal languages. In some ways the difference between formal and natural language is like the difference between poetry and prose, but more so:
 * Poetry Words are used for their sounds as well as for their meaning, and the whole poem together creates an effect or emotional response. Ambiguity is not only common but often deliberate.
 * Prose The literal meaning of words is more important and the structure contributes more meaning. Prose is more amenable to analysis than poetry, but still often ambiguous.
 * Programs The meaning of a computer program is unambiguous and literal, and can be understood entirely by analysis of the tokens and structure.

Hints for reading programs
Here are some suggestions for reading programs (and other formal languages). First, remember that formal languages are much more dense than natural languages, so it takes longer to read them. Also, the structure is very important, so it is usually not a good idea to read from top to bottom, left to right. Instead, learn to parse the program in your head, identifying the tokens and interpreting the structure. Finally, remember that the details matter. Little things like spelling errors and bad punctuation, which you can get away with in natural languages, can make a big difference in a formal language.

The first program
Hello, world!

Traditionally the first program people write in a new language is called Hello, World. because all it does is print the words Hello, World. In Java, this program looks like this:

Sometimes the quality of a programming language is judged by the simplicity of the Hello, World. program. By this standard, Java does not do very well. Even the simplest Java program contains a number of features that are hard to explain to beginning programmers. We are going to ignore a lot of them for now, but I will explain a few.

All programs are made up of class definitions, which have the form:

Classes
Here CLASSNAME indicates an arbitrary name that you make up. The class name in the example is Hello.

main
In the second line, you should ignore the words public static void for now, but notice the word main. main is a special name that indicates the place in the program where execution begins. When the program runs, it starts by executing the first statement in main and it continues, in order, until it gets to the last statement, and then it quits.

print
There is no limit to the number of statements that can be in main, but the example contains only one. It is a print statement, meaning that it prints a message on the screen. It is a bit confusing that “print” sometimes means “display something on the screen,” and sometimes means “send something to the printer.” In this book I won't say much about sending things to the printer; we'll do all our printing on the screen.

The command that prints things on the screen is System.out.println, and the thing between the parentheses is the thing that will get printed. At the end of the statement there is a semi-colon, which is required at the end of every statement.

There are a few other things you should notice about the syntax of this program. First, Java uses squiggly-braces { and } to group things together (squiggly-braces are also known as curly braces). The outermost squiggly-braces (lines 1 and 8) contain the class definition, and the inner braces contain the definition of main.

comment
Also, notice that line 3 begins with //. This indicates that this line contains a comment, which is a bit of English text that you can put in the middle of a program, usually to explain what the program does. When the compiler sees a //, it ignores everything from there until the end of the line.

In the first lab you will compile and run this program, and also modify it in various ways in order to see what the syntax rules are, and to see what error messages the compiler generates when you violate one.

Glossary

 * problem-solving The process of formulating a problem, finding a solution, and expressing the solution.
 * high-level language A programming language like Java that is designed to be easy for humans to read and write.
 * low-level language A programming language that is designed to be easy for a computer to execute. Also called “machine language” or “assembly language.”
 * formal language Any of the languages people have designed for specific purposes, like representing mathematical ideas or computer programs. All programming languages are formal languages.
 * natural language Any of the languages people speak that have evolved naturally.
 * portability A property of a program that can run on more than one kind of computer.
 * interpret To execute a program in a high-level language by translating it one line at a time.
 * compile To translate a program in a high-level language into a low-level language, all at once, in preparation for later execution.
 * source code A program in a high-level language, before being compiled.
 * object code The output of the compiler, after translating the program.
 * executable Another name for object code that is ready to be executed.
 * byte code A special kind of object code used for Java programs. Byte code is similar to a low-level language, but it is portable, like a high-level language.
 * algorithm A general process for solving a category of problems.
 * bug An error in a program.
 * syntax The structure of a program.
 * semantics The meaning of a program.
 * parse To examine a program and analyze the syntactic structure.
 * syntax error An error in a program that makes it impossible to parse (and therefore impossible to compile).
 * exception An error in a program that makes it fail at run-time. Also called a run-time error.
 * logical error An error in a program that makes it do something other than what the programmer intended.
 * debugging The process of finding and removing any of the three kinds of errors.

title: The Way of the Java/Introduction


text:
The Way of the Java/Variables and types

More printing
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.

String
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.

newline
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.

Variables
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 sequences of 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. Each variable has 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 may notice that some types begin with a capital letter and some with lower-case. Java is a case-sensitive language, so you should take care to get it right.

declaration
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).

Assignment
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 straightforward:
 * When you declare a variable, you create a named storage location.
 * When you make an assignment to a variable, you give it a value.

As a general rule, 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.

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. So for now you should remember the general rule, 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.

Printing variables
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. For example:

If you want to get a little tricky, you could write:

The output of this program is:

The value of firstLine is Hello, again!

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!

Keywords
A few sections ago, I said that you can make up any name you want for your variables, but that is 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 Java doc.

Rather than memorize the list, I would suggest that you take advantage of a feature provided in many Java development environments: 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
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.

Int division
Addition, subtraction and multiplication all do what you expect, but you might be surprised by division. For example, the following program:

would generate the following output:

Number of minutes since midnight: 719 Fraction of the hour that has passed: 0

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 arguments of an instruction), the result must also be an 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:

Percentage of the hour that has passed: 98

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.

Order of operations
precedence order of operations

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:

Multiplication and division take precedence (happen before) addition and subtraction. So 2*3-1 yields 5, not 4, and 2/3-1 yields -1, not 1 (remember that in integer division 2/3 is 0).

If the operators have the same precedence they are evaluated from left to right. So in the expression minute*100/60, the multiplication happens first, yielding 5900/60, which in turn yields 98. If the operations had gone from right to left, the result would be 59*1 which is 59, which is wrong.

Any time you want to override the rules of precedence (or you are not sure what they are) you can use parentheses. Expressions in parentheses are evaluated first, so 2 * (3-1) is 4. You can also use parentheses to make an expression easier to read, as in (minute * 100) / 60, even though it does not change the result.

Operators for Strings
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.

concatenate
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.

Composition
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 multiply 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 is 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:

Glossary
is created.
 * variable A named storage location for values. All variables have a type, which is declared when the variable
 * value A number or string (or other thing to be named later) that can be stored in a variable. Every value belongs to one type.
 * type A set of values. The type of a variable determines which values can be stored there. So far, the types we have seen are integers (int in Java) and strings (String in Java).
 * keyword A reserved word that is used by the compiler to parse programs. You cannot use keywords, like public, class and void as variable names.
 * statement A line of code that represents a command or action. So far, the statements we have seen are declarations, assignments, and print statements.
 * declaration A statement that creates a new variable and determines its type.
 * assignment A statement that assigns a value to a variable.
 * expression A combination of variables, operators and values that represents a single result value. Expressions also have types, as determined by their operators and operands.
 * operator A special symbol that represents a simple computation like addition, multiplication or string concatenation.
 * operand One of the values on which an operator operates.
 * precedence The order in which operations are evaluated.
 * concatenate To join two operands end-to-end.
 * composition The ability to combine simple expressions and statements into compound statements and expressions in order to represent complex computations concisely.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

title: The Way of the Java/Variables and types


text:
Talk:Chess/Basic Openings

Chess!
I will soon create a name in Wikibooks to alter and elaborate this nascent book. Everyone involved should post their user names so that we can discuss via email or this page and make this a group effort because I'm no grandmaster of chess. —Preceding unsigned comment added by 209.12.77.226 (discuss • contribs) 14:06, 19 August 2005

 * Would be interesting to know who you are and when that comment was made. I assume that the Basic Opening became the Opening_theory_in_chess? ChessCreator (talk) 15:14, 6 February 2008 (UTC)

 * I've added the IP address and date for that comment. Νεοπτόλεμος 15:25, 6 February 2008 (UTC)
 * Have now setup Chess to better improve information and communication on chess-related topics. check it out ;) ChessCreator (talk) 16:55, 2 April 2008 (UTC)

The English
I'dd like to get better at the English. It would be helpful if there was some theory behind the openings and variations.

Maybe the different openings could have their own subpages? A linkable table of opening moves could also be helpful...(Nunn's Chess Openings would help, but I'm not sure where copyright issues would be a problem.)
 * There is a work in progress to give a more in-depth exploration of opening lines, transpositions, and theory. Please go to this link to view and contribute. As for copyright, you can copy moves from any source, but not analysis w/o proper clearance from the copyright holder.--JECompton 04:11, 22 June 2006 (UTC)

Exclusive Pronouns
I replaced the exclusive pronouns (he and his) so that women would feel just as welcome participating in chess as men do. 12.168.85.3 12:18, 23 May 2006 (UTC)

"Basic" openings ?
The title is confusing : the page is supposed to list only the basic openings, but some of the quoted openings aren't basic at all ! Or should we understand it as "the basic moves" of each opening ? or "basic" opening knowledge ?

 * yea, it's more like a beginners guide to the openings. ChessCreator (talk) 16:10, 6 February 2008 (UTC)

Blace instead of Black
There is a typo: the word 'Blace' is used once instead of 'Black'

new opening
A user made a new page at Cornstalk Defense. I've moved it into the Chess wikibook, but as this page is a list of all the openings, I assume it should be worked into the current page rather than remain a separate entry (Unless, of course, it is not a "basic" opening and would not be appropriately included on this page). I would do it myself, but I don't have the chess knowledge to be confident in my ability to accurately explain it. Here is a link: Chess/Basic Openings/Cornstalk Defense. Thanks, Νεοπτόλεμος 02:34, 30 December 2007 (UTC)
 * It's not a basic opening, and such an irregular opening is best moved and covered in Opening_theory_in_chess specifically here Opening_theory_in_chess/1._e4/1...a5 ChessCreator (talk) 15:11, 6 February 2008 (UTC)
 * I've nominated the original for deletion, now that you've put it in its proper place. Νεοπτόλεμος 15:34, 6 February 2008 (UTC)

Split
Shouldn't this book be split into Chess/Basic Openings/e4 e5 Openings, Chess/Basic Openings/Other e4 Openings, Chess/Basic Openings/d4 d5 Openings, Chess/Basic Openings/Other d4 Openings, and Chess/Basic Openings/Other Openings? The page is getting lengthy, so I thought it might need to be split just like Chess/The Endgame was. --Whoop whoop pull up Bitching Betty 20:34, 6 April 2011 (UTC)

Scotch and Damiano
Shouldn't the Scotch Game (1. e4 e5 2. Nf3 Nc6 3. d4), Goring Gambit (1. e4 e5 2. Nf3 Nc6 3. d4 exd4 5. c3), and Damiano Defense (1. e4 e5 2. Nf3 f6) be included? --Whoop whoop pull up Bitching Betty 18:10, 10 April 2011 (UTC)

title: Talk:Chess/Basic Openings


text:
The Way of the Java/Methods

Floating-point
In the last chapter we had some problems dealing with numbers that were not integers. We worked around the problem by measuring percentages instead of fractions, but a more general solution is to use floating-point numbers, which can represent fractions as well as integers. In Java, the floating-point type is called double.

You can create floating-point variables and assign values to them using the same syntax we used for the other types. For example:

It is also legal to declare a variable and assign a value to it at the same time:

In fact, this syntax is quite common. A combined declaration and assignment is sometimes called an initialization.

Initialization, conversion
Although floating-point numbers are useful, they are often a source of confusion because there seems to be an overlap between integers and floating-point numbers. For example, if you have the value 1, is that an integer, a floating-point number, or both?

Strictly speaking, Java distinguishes the integer value 1 from the floating-point value 1.0, even though they seem to be the same number. They belong to different types, and strictly speaking, you are not allowed to make assignments between types. For example, the following is illegal:

because the variable on the left is an int and the value on the right is a float. But it is easy to forget this rule, especially because there are places where Java will automatically convert from one type to another. For example:

should technically not be legal, but Java allows it by converting the int to a double automatically. This leniency is convenient, but it can cause problems; for example:

You might expect the variable y to be given the value 0.333333, which is a legal floating-point value, but in fact it will get the value 0.0. The reason is that the expression on the right appears to be the ratio of two integers, so Java does integer division, which yields the integer value 0. Converted to floating-point, the result is 0.0.

One way to solve this problem (once you figure out what it is) is to make the right-hand side a floating-point expression:

This sets y to 0.333333, as expected.

All the operations we have seen so far—addition, subtraction, multiplication, and division—also work on floating-point values, although you might be interested to know that the underlying mechanism is completely different. In fact, most processors have special hardware just for performing floating-point operations.

Converting from double to int
As I mentioned, Java converts ints to doubles automatically if necessary, because no information is lost in the translation. On the other hand, going from a double to an int requires rounding off. Java does not perform this operation automatically, in order to make sure that you, as the programmer, are aware of the loss of the fractional part of the number.

The simplest way to convert a floating-point value to an integer is to use a typecast. Typecasting is so called because it allows you to take a value that belongs to one type and cast it into another type (in the sense of molding or reforming, not throwing).

Unfortunately, the syntax for typecasting is ugly: you put the name of the type in parentheses and use it as an operator. For example:

The (int) operator has the effect of converting what follows into an integer, so x gets the value 3.

Typecasting takes precedence over arithmetic operations, so in the following example, the value of PI gets converted to an integer first, so Java finds an error because the casted value of PI gets converted into a double when multiplied by 20.0, which is not of type int.

Converting to an integer always rounds down, even if the fraction part is 0.99999999.

These two properties (precedence and rounding) can make typecasting awkward.

Math methods
Java provides a set of built-in functions that includes most of the mathematical operations you can think of. These functions are called methods. Most math methods operate on doubles.

The math methods are invoked using a syntax that is similar to the print commands we have already seen:

The first example sets root to the square root of 17. The second example finds the sine of 1.5, which is the value of the variable angle. Java assumes that the values you use with sin and the other trigonometric functions (cos, tan) are in radians. If you need to convert degrees to radians:

Notice that PI is in all capital letters. Java does not recognize Pi, pi, or pie.

Another useful method in the Math class is round, which rounds a floating-point value off to the nearest integer and returns an int.

In this case the multiplication happens first, before the method is invoked. The result is 63 (rounded up from 62.8319).

Composition
Just as with mathematical functions, Java methods can be composed, meaning that you use one expression as part of another. For example, you can use any expression as an argument to a method:

This statement takes the value Math.PI, divides it by two and adds the result to the value of the variable angle. The sum is then passed as an argument to the cos method. (Notice that PI is the name of a variable, not a method, so there are no arguments, not even the empty argument ).

You can also take the result of one method and pass it as an argument to another:

In Java, the log function always uses base 10, so this statement finds the log base 10 of 10. The result gets assigned to x; I hope you know what it is.

Adding new methods
So far we have only been using the methods that are built into Java, but it is also possible to add new methods. Actually, we have already seen one method definition: main. The method named main is special in that it indicates where the execution of the program begins, but the syntax for main is the same as for other method definitions:

You can make up any name you want for your method, except that you cannot call it main or any other Java keyword. The list of parameters specifies what information, if any, you have to provide in order to use (or invoke) the new function.

The single parameter for main is String[] args, which indicates that whoever invokes main has to provide an array of Strings (we'll get to arrays in Chapter arrays). The first couple of methods we are going to write have no parameters, so the syntax looks like this:

This method is named newLine, and the empty parentheses indicate that it takes no parameters. It contains only a single statement, which prints an empty String, indicated by "". Printing a String with no letters in it may not seem all that useful, except remember that println skips to the next line after it prints, so this statement has the effect of skipping to the next line.

In main we can invoke this new method using syntax that is similar to the way we invoke the built-in Java commands:

The output of this program is: First line. Second line.

Notice the extra space between the two lines. What if we wanted more space between the lines? We could invoke the same method repeatedly:

Or we could write a new method, named threeLine, that prints three new lines:

You should notice a few things about this program:
 * You can invoke the same procedure repeatedly. In fact, it is quite common and useful to do so.
 * You can have one method invoke another method. In this case, main invokes threeLine and threeLine invokes newLine. Again, this is common and useful.
 * In threeLine I wrote three statements all on the same line, which is syntactically legal (remember that spaces and new lines usually do not change the meaning of a program).

On the other hand, it is usually a better idea to put each statement on a line by itself, to make your program easy to read. I sometimes break that rule in this book to save space.

So far, it may not be clear why it is worth the trouble to create all these new methods. Actually, there are a lot of reasons, but this example only demonstrates two:
 * 1) Creating a new method gives you an opportunity to give a name to a group of statements. Methods can simplify a program by hiding a complex computation behind a single command, and by using English words in place of arcane code. Which is clearer, newLine or System.out.println ("")?
 * 2) Creating a new method can make a program smaller by eliminating repetitive code. For example, how would you print nine consecutive new lines? You could just invoke threeLine three times.

Classes
Pulling together all the code fragments from the previous section, the whole class definition looks like this:

The first line indicates that this is the class definition for a new class called NewLine. A class is a collection of related methods. In this case, the class named NewLine contains three methods, named newLine, threeLine, and main.

The other class we have seen is the Math class. It contains methods named sqrt, sin, and many others. When we invoke a mathematical function, we have to specify the name of the class (Math) and the name of the function. That is why the syntax is slightly different for built-in methods and the methods that we write:

The first statement invokes the pow method in the Math class (which raises the first argument to the power of the second argument). The second statement invokes the newLine method, which Java assumes (correctly) is in the NewLine class, which is what we are writing.

If you try to invoke a method from the wrong class, the compiler will generate an error. For example, if you type:

The compiler will say something like, "Can't find a method named pow in class NewLine." If you have seen this message, you might have wondered why it was looking for pow in your class definition. Now you know.

Programs with multiple methods
When you look at a class definition that contains several methods, it is tempting to read it from top to bottom, but that is likely to be confusing, because that is not the order of execution of the program.

Execution always begins at the first statement of main, regardless of where it is in the program (in this case I deliberately put it at the bottom). Statements are executed one at a time, in order, until you reach a method invocation. Method invocations are like a detour in the flow of execution. Instead of going to the next statement, you go to the first line of the invoked method, execute all the statements there, and then come back and pick up again where you left off.

That sounds simple enough, except that you have to remember that one method can invoke another. Thus, while we are in the middle of main, we might have to go off and execute the statements in threeLine. But while we are executing threeLine, we get interrupted three times to go off and execute newLine.

For its part, newLine invokes the built-in method println, which causes yet another detour. Fortunately, Java is quite adept at keeping track of where it is, so when println completes, it picks up where it left off in newLine, and then gets back to threeLine, and then finally gets back to main so the program can terminate.

Actually, technically, the program does not terminate at the end of main. Instead, execution picks up where it left off in the program that invoked main, which is the Java interpreter. The Java interpreter takes care of things like deleting windows and general cleanup, and then the program terminates.

What is the moral of this sordid tale? When you read a program, do not read from top to bottom. Instead, follow the flow of execution.

Parameters and arguments
Some of the built-in methods we have used have parameters, which are values that you provide to let the method do its job. For example, if you want to find the sine of a number, you have to indicate what the number is. Thus, sin takes a double value as a parameter. To print a string, you have to provide the string, which is why println takes a String as a parameter.

Some methods take more than one parameter, like pow, which takes two doubles, the base and the exponent.

Notice that in each of these cases we have to specify not only how many parameters there are, but also what type they are. So it should not surprise you that when you write a class definition, the parameter list indicates the type of each parameter. For example:

This method takes a single parameter, named phil, that has type String. Whatever that parameter is (and at this point we have no idea what it is), it gets printed twice. I chose the name phil to suggest that the name you give a parameter is up to you, but in general you want to choose something more illustrative than phil.

In order to invoke this method, we have to provide a String. For example, we might have a main method like this:

The string you provide is called an argument, and we say that the argument is passed to the method. In this case we are creating a string value that contains the text "Don't make me say this twice!" and passing that string as an argument to printTwice where, contrary to its wishes, it will get printed twice.

Alternatively, if we had a String variable, we could use it as an argument instead:

Notice something very important here: the name of the variable we pass as an argument (argument) has nothing to do with the name of the parameter (phil). Let me say that again:

The name of the variable we pass as an argument has nothing to do with the name of the parameter.

They can be the same or they can be different, but it is important to realize that they are not the same thing, except that they happen to have the same value (in this case the string "Never say never.").

The value you provide as an argument must have the same type as the parameter of the method you invoke. This rule is very important, but it often gets complicated in Java for two reasons:
 * There are some methods that can accept arguments with many different types. For example, you can send any type to print and println, and it will do the right thing no matter what. This sort of thing is an exception, though.
 * If you violate this rule, the compiler often generates a confusing error message. Instead of saying something like, "You are passing the wrong kind of argument to this method," it will probably say something to the effect that it could not find a method with that name that would accept an argument with that type. Once you have seen this error message a few times, though, you will figure out how to interpret it.

Stack diagrams
Parameters and other variables only exist inside their own methods. Within the confines of main, there is no such thing as phil. If you try to use it, the compiler will complain. Similarly, inside printTwice there is no such thing as argument.

For each method there is a gray box called a frame that contains the methods parameters and local variables. The name of the method appears outside the frame. As usual, the value of each variable is drawn inside a box with the name of the variable beside it.

Methods with multiple parameters
The syntax for declaring and invoking methods with multiple parameters is a common source of errors. First, remember that you have to declare the type of every parameter. For example

It might be tempting to write int hour, minute, but that format is only legal for variable declarations, not for parameters.

Another common source of confusion is that you do not have to declare the types of arguments. The following is wrong!

In this case, Java can tell the type of hour and minute by looking at their declarations. It is unnecessary and illegal to include the type when you pass them as arguments. The correct syntax is: printTime (hour, minute).

As an exercise, draw a stack frame for printTime called with the arguments 11 and 59.

Methods with results
You might have noticed by now that some of the methods we are using, like the Math methods, yield results. Other methods, like println and newLine, perform some action but they do not return a value. That raises some questions:
 * What happens if you invoke a method and you do not do anything with the result (i.e. you do not assign it to a variable or use it as part of a larger expression)?
 * What happens if you use a print method as part of an expression, like System.out.println ("boo!") + 7?
 * Can we write methods that yield results, or are we stuck with things like newLine and printTwice?

The answer to the third question is "yes, you can write methods that return values," and we'll do it in a couple of chapters. I will leave it up to you to answer the other two questions by trying them out. In fact, any time you have a question about what is legal or illegal in Java, a good way to find out is to ask the compiler.

Glossary

 * floating-point: A type of variable (or value) that can contain fractions as well as integers. In Java this type is called double.
 * class A named collection of methods. So far, we have used the Math class and the System class, and we have written classes named Hello and NewLine.
 * method A named sequence of statements that performs some useful function. Methods may or may not take parameters, and may or may not produce a result.
 * parameter A piece of information you provide in order to invoke a method. Parameters are like variables in the sense that they contain values and have types.
 * argument A value that you provide when you invoke a method. This value must have the same type as the corresponding parameter.
 * invoke Cause a method to be executed.

title: The Way of the Java/Methods


text:
The Way of the Java/Conditionals graphics recursion

=Conditionals, graphics and recursion=

The modulus operator
The modulus operator works on integers (and integer expressions) and yields the remainder when the first operand is divided by the second. In Java, the modulus operator is a percent sign, %. The syntax is exactly the same as for other operators:

The first operator, integer division, yields 2. The second operator yields 1. Thus, 7 divided by 3 is 2 with 1 left over.

The modulus operator turns out to be surprisingly useful. For example, you can check whether one number is divisible by another: if x%y is zero, then x is divisible by y.

Also, you can use the modulus operator to extract the rightmost digit or digits from a number. For example, x % 10 yields the rightmost digit of x (in base 10). Similarly x % 100 yields the last two digits.

Conditional execution
In order to write useful programs, we almost always need the ability to check certain conditions and change the behavior of the program accordingly. Conditional statements give us this ability. The simplest form is the if statement:

The expression in parentheses is called the condition. If it is true, then the statements in brackets get executed. If the condition is not true, nothing happens.

The condition can contain any of the comparison operators, sometimes called relational operators:

A common error is to use a single = instead of a double ==. Remember that = is the assignment operator, and == is a comparison operator. Also, there is no such thing as =.

The two sides of a condition operator have to be the same type. You can only compare ints to ints and doubles to doubles. Unfortunately, at this point you cannot compare Strings at all! There is a way to compare Strings, but we won't get to it for a couple of chapters.

Alternative execution
A second form of conditional execution is alternative execution, in which there are two possibilities, and the condition determines which one gets executed. The syntax looks like:

If the remainder when x is divided by 2 is zero, then we know that x is even, and this code prints a message to that effect. If the condition is false, the second print statement is executed. Since the condition must be true or false, exactly one of the alternatives will be executed.

As an aside, if you think you might want to check the parity (evenness or oddness) of numbers often, you might want to "wrap" this code up in a method, as follows:

Now you have a method named printParity that will print an appropriate message for any integer you care to provide. In main you would invoke this method as follows:

Always remember that when you invoke a method, you do not have to declare the types of the arguments you provide. Java can figure out what type they are. You should resist the temptation to write things like:

Chained conditionals
Sometimes you want to check for a number of related conditions and choose one of several actions. One way to do this is by chaining a series of ifs and elses:

These chains can be as long as you want, although they can be difficult to read if they get out of hand. One way to make them easier to read is to use standard indentation, as demonstrated in these examples. If you keep all the statements and squiggly-brackets lined up, you are less likely to make syntax errors and you can find them more quickly if you do.

Nested conditionals
In addition to chaining, you can also nest one conditional within another. We could have written the previous example as:

There is now an outer conditional that contains two branches. The first branch contains a simple print statement, but the second branch contains another conditional statement, which has two branches of its own. Fortunately, those two branches are both print statements, although they could have been conditional statements as well.

Notice again that indentation helps make the structure apparent, but nevertheless, nested conditionals get difficult to read very quickly. In general, it is a good idea to avoid them when you can.

On the other hand, this kind of nested structure is common, and we will see it again, so you better get used to it.

The return statement
The return statement allows you to terminate the execution of a method before you reach the end. One reason to use it is if you detect an error condition:

This defines a method named printLogarithm that takes a double named x as a parameter. The first thing it does is check whether x is less than or equal to zero, in which case it prints an error message and then uses return to exit the method. The flow of execution immediately returns to the caller and the remaining lines of the method are not executed.

I used a floating-point value on the right side of the condition because there is a floating-point variable on the left.

Type conversion
You might wonder how you can get away with an expression like "The log of x is " + result, since one of the operands is a String and the other is a double. Well, in this case Java is being smart on our behalf, by automatically converting the double to a String before it does the string concatenation.

This kind of feature is an example of a common problem in designing a programming language, which is that there is a conflict between formalism, which is the requirement that formal languages should have simple rules with few exceptions, and convenience, which is the requirement that programming languages be easy to use in practice.

More often than not, convenience wins, which is usually good for expert programmers (who are spared from rigorous but unwieldy formalism), but bad for beginning programmers, who are often baffled by the complexity of the rules and the number of exceptions. In this book I have tried to simplify things by emphasizing the rules and omitting many of the exceptions.

Nevertheless, it is handy to know that whenever you try to "add" two expressions, if one of them is a String, then Java will convert the other to a String and then perform string concatenation. What do you think happens if you perform an operation between an integer and a floating-point value?

Slates and Graphics objects
In order to draw things on the screen, you need two objects, a Slate and a Graphics object.
 * Slate: a Slate is a window that contains a blank rectangle you can draw on. The Slate class is not part of the standard Java library; it is something I wrote for this course.
 * Graphics: the Graphics object is the object we will use to draw lines, circles, etc. It is part of the Java library, so the documentation for it is on the Sun web site.

The methods that pertain to Graphics objects are defined in the built-in Graphics class. The methods that pertain to Slates are defined in the Slate class, which is shown in Appendix slate.

The primary method in the Slate class is makeSlate, which does pretty much what you would expect. It creates a new window and returns a Slate object you can use to refer to the window later in the program. You can create more than one Slate in a single program.

makeSlate takes two arguments, the width and height of the window. Because it belongs to a different class, we have to specify the name of the class using dot notation.

The return value gets assigned to a variable named slate. There is no conflict between the name of the class (with an upper-case S) and the name of the variable (with a lower-case s).

The next method we need is getGraphics, which takes a Slate object and creates a Graphics object that can draw on it. You can think of a Graphics object as a piece of chalk.

Using the name g is conventional, but we could have called it anything.

setColor
In order to draw things on the screen, you invoke methods on the graphics object. We have invoked lots of methods already, but this is the first time we have invoked a method on an object. The syntax is similar to invoking a method from another class:

The name of the object comes before the dot; the name of the method comes after, followed by the arguments for that method. In this case, the method takes a single argument, which is a color.

setColor changes the current color, in this case to black. Everything that gets drawn will be black, until we use setColor again.

Color.black is a special value provided by the Color class, just as Math.PI is a special value provided by the Math class. Color, you will be happy to hear, provides a palette of other colors, including:

black    blue    cyan   darkGray   gray   lightGray magenta	 orange  pink   red        white  yellow

drawOval
To draw on the Slate, we can invoke draw methods on the Graphics object. For example:

drawOval takes four integers as arguments. These arguments specify a bounding box, which is the rectangle in which the oval will be drawn (as shown in the figure). The bounding box itself is not drawn; only the oval is. The bounding box is like a guideline. Bounding boxes are always oriented horizontally or vertically; they are never at a funny angle.

bounding box
If you think about it, there are lots of ways to specify the location and size of a rectangle. You could give the location of the center or any of the corners, along with the height and width. Or, you could give the location of opposing corners. The choice is arbitrary, but in any case it will require the same number of parameters: four.

By convention, the usual way to specify a bounding box is to give the location of the upper-left corner and the width and height. The usual way to specify a location is to use a coordinate system.

Coordinates
You are probably familiar with Cartesian coordinates in two dimensions, in which each location is identified by an x-coordinate (distance along the x-axis) and a y-coordinate. By convention, Cartesian coordinates increase to the right and up, as shown in the figure.

Annoyingly, it is conventional for computer graphics systems to use a variation on Cartesian coordinates in which the origin is in the upper-left corner of the screen or window, and the direction of the positive y-axis is down. Java follows this convention.

pixel
The unit of measure is called a pixel; a typical screen is about 1000 pixels wide. Coordinates are always integers. If you want to use a floating-point value as a coordinate, you have to round it off to an integer (See Section rounding).

A lame Mickey Mouse
Let's say we want to draw a picture of Mickey Mouse. We can use the oval we just drew as the face, and then add ears. Before we do that it is a good idea to break the program up into two methods. main will create the Slate and Graphics objects and then invoke draw, which does the actual drawing.

The parameters for draw are the Graphics object and a bounding box. draw invokes drawOval three times, to draw Mickey's face and two ears. The following figure shows the bounding boxes for the ears.

/-\ /-\ | | |  |  \ / \ /   /---\  |     |   \___/

As shown in the figure, the coordinates of the upper-left corner of the bounding box for the left ear are (x, y). The coordinates for the right ear are (x+width/2, y). In both cases, the width and height of the ears are half the width and height of the original bounding box.

Notice that the coordinates of the ear boxes are all relative to the location (x and y) and size (width and height) of the original bounding box. As a result, we can use draw to draw a Mickey Mouse (albeit a lame one) anywhere on the screen in any size. As an exercise, modify the arguments passed to draw so that Mickey is one half the height and width of the screen, and centered.

Other drawing commands
prototype drawLine drawRect fillOval fillRect prototype interface

drawRect, drawLine
Another drawing command with the same parameters as drawOval is:

Here I am using a standard format for documenting the name and parameters of methods. This information is sometimes called the method's interface or prototype. Looking at this prototype, you can tell what types the parameters are and (based on their names) infer what they do. Here is another example:

The use of parameter names x1, x2, y1 and y2 suggests that drawLine draws a line from the point (x1, y1) to the point (x2, y2).

One other command you might want to try is:

The first four parameters specify the bounding box of the rectangle; the remaining two parameters indicate how rounded the corners should be, specifying the horizontal and vertical diameter of the arcs at the corners.

fillRect, fillOval
There are also fill versions of these commands, that not only draw the outline of a shape, but also fill it in. The interfaces are identical; only the names have been changed:

There is no such thing as fillLine—it just does not make sense as lines are one-dimensional.

Recursion
I mentioned in the last chapter that it is legal for one method to call another, and we have seen several examples of that. I neglected to mention that it is also legal for a method to invoke itself. It may not be obvious why that is a good thing, but it turns out to be one of the most magical and interesting things a program can do.

The name of the method is countdown and it takes a single integer as a parameter. If the parameter is zero, it prints the word Blastoff. Otherwise, it prints the number and then invokes a method named countdown—itself—passing n-1 as an argument.

What happens if we invoke this method, in main, like this:

 * 1) The execution of countdown begins with n=3, and since n is not zero, it prints the value 3, and then invokes itself, passing 3-1...
 * 2) The execution of countdown begins with n=2, and since n is not zero, it prints the value 2, and then invokes itself, passing 2-1...
 * 3) The execution of countdown begins with n=1, and since n is not zero, it prints the value 1, and then invokes itself, passing 1-1...
 * 4) The execution of countdown begins with n=0, and since n is zero, it prints the word Blastoff! and then returns.
 * 5) The countdown that got n=1 returns.
 * 6) The countdown that got n=2 returns.
 * 7) The countdown that got n=3 returns.

And then you are back in main (what a trip). So the total output looks like:

3 2 1 Blastoff!

As a second example, let's look again at the methods newLine and threeLine.

verbatim

Although these work, they would not be much help if I wanted to print 2 newlines, or 106. A better alternative would be:

This program is very similar; as long as n is greater than zero, it prints one newline, and then invokes itself to print n-1 additional newlines. Thus, the total number of newlines that get printed is 1 + (n-1), which usually comes out to roughly n.

The process of a method invoking itself is called recursion, and such methods are said to be recursive.

Stack diagrams for recursive methods
In the previous chapter we used a stack diagram to represent the state of a program during a method call. The same kind of diagram can make it easier to interpret a recursive method.

Remember that every time a method gets called it creates a new instance of the method that contains a new version of the method's local variables and parameters.

There is one instance of main and four instances of countdown, each with a different value for the parameter n. The bottom of the stack, countdown with n=0 is the base case. It does not make a recursive call, so there are no more instances of countdown.

The instance of main is empty because main does not have any parameters or local variables. As an exercise, draw a stack diagram for nLines, invoked with the parameter n=4.

Convention and divine law
In the last few sections, I used the phrase by convention several times to indicate design decisions that are arbitrary in the sense that there are no significant reasons to do things one way or another, but dictated by convention.

In these cases, it is to your advantage to be familiar with convention and use it, since it will make your programs easier for others to understand. At the same time, it is important to distinguish between (at least) three kinds of rules:
 * Divine law This is my phrase to indicate a rule that is true because of some underlying principle of logic or mathematics, and that is true in any programming language (or other formal system). For example, there is no way to specify the location and size of a bounding box using fewer than four pieces of information. Another example is that adding integers is commutative. That is part of the definition of addition and has nothing to do with Java.
 * Rules of Java These are the syntactic and semantic rules of Java that you cannot violate, because the resulting program will not compile or run. Some are arbitrary; for example, the fact that the + symbol represents addition and string concatenation. Others reflect underlying limitations of the compilation or execution process. For example, you have to specify the types of parameters, but not arguments.
 * Style and convention There are a lot of rules that are not enforced by the compiler, but that are essential for writing programs that are correct, that you can debug and modify, and that others can read. Examples include indentation and the placement of squiggly braces, as well as conventions for naming variables, methods and classes.

As we go along, I will try to indicate which category various things fall into, but you might want to give it some thought from time to time.

While I am on the topic, you have probably figured out by now that the names of classes always begin with a capital letter, but variables and methods begin with lower case. If a name includes more than one word, you usually capitalize the first letter of each word, as in newLine and printParity. Which category are these rules in?

Glossary

 * modulus An operator that works on integers and yields the remainder when one number is divided by another. In Java it is denoted with a percent sign.
 * conditional A block of statements that may or may not be executed depending on some condition.
 * chaining A way of joining several conditional statements in sequence.
 * nesting Putting a conditional statement inside one or both branches of another conditional statement.
 * coordinate A variable or value that specifies a location in a two-dimensional graphical window.
 * pixel The unit in which coordinates are measured.
 * bounding box A common way to specify the coordinates of a rectangular area.
 * typecast An operator that converts from one type to another. In Java it appears as a type name in parentheses, like (int).
 * interface A description of the parameters required by a method and their types.
 * prototype A way of describing the interface to a method using Java-like syntax.
 * recursion The process of invoking the same method you are currently executing.
 * infinite recursion A method that invokes itself recursively without ever reaching the base case. The usual result is a StackOverflowException.
 * fractal A kind of image that is defined recursively, so that each part of the image is a smaller version of the whole.


text:
The Way of the Java/Fruitful methods

Return values
Some of the built-in methods we have used, like the Math functions, have produced results. That is, the effect of invoking the method is to generate a new value, which we usually assign to a variable or use as part of an expression. For example:

But so far all the methods we have written have been void methods; that is, methods that return no value. When you invoke a void method, it is typically on a line by itself, with no assignment:

In this chapter, we are going to write methods that return things, which I will refer to as fruitful methods, for want of a better name. The first example is area, which takes a double as a parameter, and returns the area of a circle with the given radius:

The first thing you should notice is that the beginning of the method definition is different. Instead of public static void, which indicates a void method, we see public static double, which indicates that the return value from this method will have type double. I still have not explained what public static means, but be patient.

static
Also, notice that the last line is an alternate form of the return statement that includes a return value. This statement means, return immediately from this method and use the following expression as a return value. The expression you provide can be arbitrarily complicated, so we could have written this method more concisely:

On the other hand, temporary variables like area often make debugging easier. In either case, the type of the expression in the return statement must match the return type of the method. In other words, when you declare that the return type is double, you are making a promise that this method will eventually produce a double. If you try to return with no expression, or an expression with the wrong type, the compiler will take you to task.

temporary variable
Sometimes it is useful to have multiple return statements, one in each branch of a conditional:

Since these return statements are in an alternative conditional, only one will be executed. Although it is legal to have more than one return statement in a method, you should keep in mind that as soon as one is executed, the method terminates without executing any subsequent statements.

Code that appears after a return statement, or any place elsewhere it can never be executed, is called dead code. Some compilers warn you if part of your code is dead.

Dead code
If you put return statements inside a conditional, then you have to guarantee that every possible path through the program hits a return statement. For example:

This program is not legal because if x happens to be 0, then neither condition will be true and the method will end without hitting a return statement. A typical compiler message would be return statement required in absoluteValue, which is a confusing message considering that there are already two of them.

Program development
At this point you should be able to look at complete Java methods and tell what they do. But it may not be clear yet how to go about writing them. I am going to suggest one technique that I call incremental development.

incremental development
As an example, imagine you want to find the distance between two points, given by the coordinates. By the usual definition:

The first step is to consider what a distance method should look like in Java. In other words, what are the inputs (parameters) and what is the output (return value).

In this case, the two points are the parameters, and it is natural to represent them using four doubles, although we will see later that there is a Point object in Java that we could use. The return value is the distance, which will have type double.

Already we can write an outline of the method:

The statement return 0.0; is a place-keeper that is necessary in order to compile the program. Obviously, at this stage the program does not do anything useful, but it is worthwhile to try compiling it so we can identify any syntax errors before we make it more complicated.

In order to test the new method, we have to invoke it with sample values. Somewhere in main I would add:

I chose these values so that the horizontal distance is 3 and the vertical distance is 4; that way, the result will be 5 (the hypotenuse of a 3-4-5 triangle). When you are testing a method, it is useful to know the right answer.

Once we have checked the syntax of the method definition, we can start adding lines of code one at a time. After each incremental change, we recompile and run the program. That way, at any point we know exactly where the error must be—in the last line we added.

The next step in the computation is to find the differences between x_1 and x_2, and between y_1 and y_2. I will store those values in temporary variables named dx and dy.

I added print statements that will let me check the intermediate values before proceeding. As I mentioned, I already know that they should be 3.0 and 4.0.

scaffolding
When the method is finished I will remove the print statements. Code like that is called scaffolding, because it is helpful for building the program, but it is not part of the final product. Sometimes it is a good idea to keep the scaffolding around, but comment it out, just in case you need it later.

The next step in the development is to square dx and dy. We could use the Math.pow method, but it is simpler and faster to just multiply each term by itself.

Again, I would compile and run the program at this stage and check the intermediate value (which should be 25.0).

Finally, we can use the Math.sqrt method to compute and return the result.

Then in main, we should print and check the value of the result.

As you gain more experience programming, you might find yourself writing and debugging more than one line at a time. Nevertheless, this incremental development process can save you a lot of debugging time.

The key aspects of the process are:
 * Start with a working program and make small, incremental changes. At any point, if there is an error, you will know exactly where it is.
 * Use temporary variables to hold intermediate values so you can print and check them.
 * Once the program is working, you might want to remove some of the scaffolding or consolidate multiple statements into compound expressions, but only if it does not make the program difficult to read.

Composition
As you should expect by now, once you define a new method, you can use it as part of an expression, and you can build new methods using existing methods. For example, what if someone gave you two points, the center of the circle and a point on the perimeter, and asked for the area of the circle?

Let's say the center point is stored in the variables xc and yc, and the perimeter point is in xp and yp. The first step is to find the radius of the circle, which is the distance between the two points. Fortunately, we have a method, distance that does that.

The second step is to find the area of a circle with that radius, and return it.

Wrapping that all up in a method, we get:

The name of this method is fred, which may seem odd. I will explain why in the next section.

The temporary variables radius and area are useful for development and debugging, but once the program is working we can make it more concise by composing the method invocations:

Overloading
In the previous section you might have noticed that fred and area perform similar functions—finding the area of a circle—but take different parameters. For area, we have to provide the radius; for fred we provide two points.

If two methods do the same thing, it is natural to give them the same name. In other words, it would make more sense if fred were called area.

Having more than one method with the same name, which is called overloading, is legal in Java as long as each version takes different parameters. So we can go ahead and rename fred:

When you invoke an overloaded method, Java knows which version you want by looking at the arguments that you provide. If you write:

Java goes looking for a method named area that takes a single double as an argument, and so it uses the first version, which interprets the argument as a radius. If you write:

Java uses the second version of area. More amazing still, the second version of area actually invokes the first.

Many of the built-in Java commands are overloaded, meaning that there are different versions that accept different numbers or types of parameters. For example, there are versions of print and println that accept a single parameter of any type. In the Math class, there is a version of abs that works on doubles, and there is also a version for ints.

Although overloading is a useful feature, it should be used with caution. You might get yourself nicely confused if you are trying to debug one version of a method while accidentally invoking a different one.

Actually, that reminds me of one of the cardinal rules of debugging: make sure that the version of the program you are looking at is the version of the program that is running! Some time you may find yourself making one change after another in your program, and seeing the same thing every time you run it. This is a warning sign that for one reason or another you are not running the version of the program you think you are. To check, stick in a print statement (it does not matter what you print) and make sure the behavior of the program changes accordingly.

Boolean expressions
Most of the operations we have seen produce results that are the same type as their operands. For example, the + operator takes two ints and produces an int, or two doubles and produces a double, etc.

relational operator
The exceptions we have seen are the relational operators, which compare ints and floats and return either true or false. true and false are special values in Java, and together they make up a type called boolean. You might recall that when I defined a type, I said it was a set of values. In the case of ints, doubles and Strings, those sets are pretty big. For booleans, not so big.

Boolean expressions and variables work just like other types of expressions and variables:

The first example is a simple variable declaration; the second example is an assignment, and the third example is a combination of a declaration and an assignment, sometimes called an initialization. The values true and false are keywords in Java, so they may appear in a different color, depending on your development environment.

initialization
As I mentioned, the result of a conditional operator is a boolean, so you can store the result of a comparison in a variable:

and then use it as part of a conditional statement later:

A variable used in this way is frequently called a flag, since it flags the presence or absence of some condition.

Logical operators
There are three logical operators in Java: AND, OR and NOT, which are denoted by the symbols &&, || and !. The semantics (meaning) of these operators is similar to their meaning in English. For example (x > 0) && (x < 10) is true only if x is greater than zero AND less than 10.

semantics
evenFlag n3 == 0 is true if either of the conditions is true, that is, if evenFlag is true OR the number is divisible by 3.

Finally, the NOT operator has the effect of negating or inverting a boolean expression, so !evenFlag is true if evenFlag is false—if the number is odd.

nested structure
Logical operators often provide a way to simplify nested conditional statements. For example, how would you write the following code using a single conditional?

Boolean methods
Methods can return boolean values just like any other type, which is often convenient for hiding complicated tests inside methods. For example:

The name of this method is isSingleDigit. It is common to give boolean methods names that sound like yes/no questions. The return type is boolean, which means that every return statement has to provide a boolean expression.

The code itself is straightforward, although it is a bit longer than it needs to be. Remember that the expression x >= 0 && x < 10 has type boolean, so there is nothing wrong with returning it directly, and avoiding the if statement altogether:

In main you can invoke this method in the usual ways:

The first line assigns the value true to bigFlag only if 17 is not a single-digit number. The second line prints true because 2 is a single-digit number. Yes, println is overloaded to handle booleans, too.

The most common use of boolean methods is inside conditional statements:

More recursion
Now that we have methods that return values, you might be interested to know that we have a complete programming language, by which I mean that anything that can be computed can be expressed in this language. Any program ever written could be rewritten using only the language features we have used so far (actually, we would need a few commands to control devices like the keyboard, mouse, disks, evil robots, etc., but that is all).

Turing, Alan
Proving this claim is a non-trivial exercise first accomplished by Alan Turing, one of the first computer scientists (well, some would argue that he was a mathematician, but a lot of the early computer scientists started as mathematicians). Accordingly, it is known as the Turing thesis. If you take a course on the Theory of Computation, you will have a chance to see the proof.

To give you an idea of what you can do with the tools we have learned so far, let's look at some methods for evaluating recursively-defined mathematical functions. A recursive definition is similar to a circular definition, in the sense that the definition contains a reference to the thing being defined. A truly circular definition is typically not very useful:

description
frabjuous: an adjective used to describe something that is frabjous.

If you saw that definition in the dictionary, you might be annoyed. On the other hand, if you looked up the definition of the mathematical function factorial, you might get something like:

eqnarray* && 0! = 1 &&  n! = n (n-1)! eqnarray*

(Factorial is usually denoted with the symbol, which is not to be confused with the Java logical operator ! which means NOT.) This definition says that the factorial of 0 is 1, and the factorial of any other value, , is multiplied by the factorial of. So is 3 times, which is 2 times , which is 1 times. Putting it all together, we get equal to 3 times 2 times 1 times 1, which is 6.

If you can write a recursive definition of something, you can usually write a Java program to evaluate it. The first step is to decide what the parameters are for this function, and what the return type is. With a little thought, you should conclude that factorial takes an integer as a parameter and returns an integer:

If the argument happens to be zero, all we have to do is return 1:

Otherwise, and this is the interesting part, we have to make a recursive call to find the factorial of, and then multiply it by.

If we look at the flow of execution for this program, it is similar to nLines from the previous chapter. If we invoke factorial with the value 3:

Process:
 * Since 3 is not zero, we take the second branch and calculate the factorial of ...
 * Since 2 is not zero, we take the second branch and calculatethe factorial of ...
 * Since 1 is not zero, we take the second branch and calculate the factorial of ...
 * Since 0 is zero, we take the first branch and return the value 1 immediately without making any more recursive calls.
 * The return value (1) gets multiplied by n, which is 1, and the result is returned.
 * The return value (1) gets multiplied by n, which is 2, and the result is returned.
 * The return value (2) gets multiplied by n, which is 3, and the result, 6, is returned to main, or whoever invoked factorial (3).

Notice that in the last instance of factorial, the local variables recurse and result do not exist because when n=0 the branch that creates them does not execute.

Leap of faith
Following the flow of execution is one way to read programs, but as you saw in the previous section, it can quickly become labarynthine. An alternative is what I call the leap of faith. When you come to a method invocation, instead of following the flow of execution, you assume that the method works correctly and returns the appropriate value.

In fact, you are already practicing this leap of faith when you use built-in methods. When you invoke Math.cos or drawOval, you do not examine the implementations of those methods. You just assume that they work, because the people who wrote the built-in classes were good programmers.

Well, the same is true when you invoke one of your own methods. For example, in Section boolean we wrote a method called isSingleDigit that determines whether a number is between 0 and 9. Once we have convinced ourselves that this method is correct—by testing and examination of the code—we can use the method without ever looking at the code again.

The same is true of recursive programs. When you get to the recursive invocation, instead of following the flow of execution, you should assume that the recursive invocation works (yields the correct result), and then ask yourself, Assuming that I can find the factorial of, can I compute the factorial of ? In this case, it is clear that you can, by multiplying by.

Of course, it is a bit strange to assume that the method works correctly when you have not even finished writing it, but that is why it is called a leap of faith!

One more example
In the previous example I used temporary variables to spell out the steps, and to make the code easier to debug, but I could have saved a few lines:

From now on I will tend to use the more concise version, but I recommend that you use the more explicit version while you are developing code. When you have it working, you can tighten it up, if you are feeling inspired.

After factorial, the classic example of a recursively-defined mathematical function is fibonacci, which has the following definition:

eqnarray* && fibonacci(0) = 1 && fibonacci(1) = 1 && fibonacci(n) = fibonacci(n-1) + fibonacci(n-2); eqnarray*

Translated into Java, this is:

If you try to follow the flow of execution here, even for fairly small values of n, your head explodes. But according to the leap of faith, if we assume that the two recursive calls (yes, you can make two recursive calls) work correctly, then it is clear that we get the right result by adding them together.

Glossary

 * return type The part of a method declaration that indicates what type of value the method returns.
 * return value The value provided as the result of a method invocation.
 * dead code Part of a program that can never be executed, often because it appears after a return statement.
 * scaffolding Code that is used during program development but is not part of the final version.
 * void A special return type that indicates a void method; that is, one that does not return a value.
 * overloading Having more than one method with the same name but different parameters. When you invoke an overloaded method, Java knows which version to use by looking at the arguments you provide.
 * boolean A type of variable that can contain only the two values true and false.
 * flag A variable (usually boolean) that records a condition or status information.
 * conditional operator An operator that compares two values and produces a boolean that indicates the relationship between the operands.
 * logical operator An operator that combines boolean values and produces boolean values.
 * initialization A statement that declares a new variable and assigns a value to it at the same time.

title: The Way of the Java/Fruitful methods