Chapter 2 Variables and types2.1 More printingYou can put as many statements as you want in main; for example, to print more than one line: class Hello {
// Generates some simple output.
public static void main(String[] args) {
System.out.println("Hello, world."); // print one line
System.out.println("How are you?"); // print another
}
} As this example demonstrates, you can 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 characters. 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 moves the cursor to the next line of the display. The next time println is invoked, the new text appears on the next line. To display the output from multiple print statements all on one line, use print: class Hello {
// Generates some simple output.
public static void main(String[] args) {
System.out.print("Goodbye, ");
System.out.println("cruel world!");
}
} The output appears on a single line as Goodbye, cruel world!. 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: class Hello {
public static void main(String[] args) {
System.out.print("Goodbye, ");
System.out.println("cruel world!");
}
} 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: class Hello { public static void main(String[] args) {
System.out.print("Goodbye, "); System.out.println
("cruel world!");}} That would work, too, but 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 errors. 2.2 VariablesOne 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, stored and (as we’ll see later) operated on. The strings we have been printing ("Hello, World.", "Goodbye, ", etc.) are values. To store a value, you have to create a variable. Since the values we want to store are strings, we declare that the new variable is a string: String bob; This statement is a declaration, because it declares that the variable named bob 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 the String type can store strings. 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: String firstName;
String lastName;
int hour, minute; you could guess 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). 2.3 AssignmentNow that we have created variables, we want to store values. We do that with an assignment statement. bob = "Hello."; // give bob the value "Hello."
hour = 11; // assign the value 11 to hour
minute = 59; // set minute to 59 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:
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: 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 bob. 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. For now you should remember the general rule, and we’ll talk about exceptions later. Another source of confusion is that some strings look like integers, but they are not. For example, bob 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. bob = "123"; // legal
bob = 123; // not legal 2.4 Printing variablesYou can print the value of a variable using println or print: class Hello {
public static void main(String[] args) {
String firstLine;
firstLine = "Hello, again!";
System.out.println(firstLine);
}
} 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: System.out.println("firstLine"); For example, you can write String firstLine;
firstLine = "Hello, again!";
System.out.print("The value of firstLine is ");
System.out.println(firstLine); The output of this program is The value of firstLine is Hello, again! I am happy to report that the syntax for printing a variable is the same regardless of the variable’s type. int hour, minute;
hour = 11;
minute = 59;
System.out.print("The current time is ");
System.out.print(hour);
System.out.print(":");
System.out.print(minute);
System.out.println("."); The output of this program is The current time is 11:59. WARNING: To put multiple values on the same line, is common to use several print statements followed by a println. But you have to remember the println at the end. In many environments, the output from print is stored without being displayed until println is invoked, at which point the entire line is displayed at once. If you omit println, the program may terminate without displaying the stored output! 2.5 KeywordsA 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 http://download.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html. This site, provided by Oracle, includes Java documentation I refer to throughout the book. Rather than memorize the list, I suggest you take advantage of a feature provided in many Java development environments: code highlighting. As you type, 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. 2.6 OperatorsOperators are symbols used to represent computations like addition and multiplication. Most operators in Java do what you expect them to do because they are common mathematical symbols. For example, the operator for addition is +. Subtraction is -, multiplication is *, and division is /. 1+1 hour-1 hour*60 + minute minute/60 Expressions can contain both variable names and numbers. Variables are replaced with their values before the computation is performed. Addition, subtraction and multiplication all do what you expect, but you might be surprised by division. For example, this program: int hour, minute;
hour = 11;
minute = 59;
System.out.print("Number of minutes since midnight: ");
System.out.println(hour*60 + minute);
System.out.print("Fraction of the hour that has passed: ");
System.out.println(minute/60); generates this output: Number of minutes since midnight: 719 Fraction of the hour that has passed: 0 The first line is expected, but the second line is odd. The value of minute is 59, and 59 divided by 60 is 0.98333, not 0. The problem is that Java is performing integer division. When both operands are integers (operands are the things operators operate on), the result is also an integer, and by convention integer division always rounds down, even in cases like this where the next integer is so close. An alternative is to calculate a percentage rather than a fraction: System.out.print("Percentage of the hour that has passed: ");
System.out.println(minute*100/60); 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. To get a more accurate answer, we can use a different type of variable, called floating-point, that can store fractional values. We’ll get to that in the next chapter. 2.7 Order of operationsWhen 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:
2.8 Operators for StringsIn general you cannot perform mathematical operations on Strings, even if the strings look like numbers. The following are illegal (if we know that bob has type String) bob - 1 "Hello"/123 bob * "Hello" By the way, can you tell by looking at those expressions whether bob 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, but it might not do what you 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 bob + "ism" adds the suffix ism to the end of whatever bob is, which is handy for naming new forms of bigotry. 2.9 CompositionSo 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 combine them in a single statement: System.out.println(17 * 3); Any expression involving numbers, strings and variables, can be used inside a print statement. We’ve already seen one example: System.out.println(hour*60 + minute); But you can also put arbitrary expressions on the right-hand side of an assignment statement: int percentage;
percentage = (minute * 100) / 60; This ability may not seem impressive now, but we will see examples where composition expresses complex computations neatly and concisely. WARNING: The left side of an assignment 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;. 2.10 Glossary
2.11 ExercisesExercise 1 If you are using this book in a class, you might enjoy this exercise: find a partner and play "Stump the Chump”: Start with a program that compiles and runs correctly. One player turns away while the other player adds an error to the program. Then the first player tries to find and fix the error. You get two points if you find the error without compiling the program, one point if you find it using the compiler, and your opponent gets a point if you don’t find it. Exercise 2
The point of this exercise is to use string concatenation to display values with different types (int and String), and to practice developing programs gradually by adding a few statements at a time. Exercise 3
The point of this exercise is to use some of the arithmetic operations, and to start thinking about compound entities like the time of day that that are represented with multiple values. Also, you might run into problems computing percentages with ints, which is the motivation for floating point numbers in the next chapter. HINT: you may want to use additional variables to hold values temporarily during the computation. Variables like this, that are used in a computation but never printed, are sometimes called intermediate or temporary variables. |
Like this book?
Are you using one of our books in a class?We'd like to know about it. Please consider filling out this short survey.
|