Translate
Friday, 3 August 2018
Friday, 18 May 2018
The if and switch Statements
In previous post, you've learned a lot about the way Java works. You now know how to type and compile programs, how to input and output simple data, how to perform mathematical operations, and how to perform comparisons using logical expressions. But these techniques are merely the building blocks of a program. To use these building blocks in a useful way, you have to understand how computers make decisions.
In this post, you learn how your programs can analyze data in order to decide what parts of your program to execute. Until now, your applets have executed their statements in strict sequential order, starting with the first line of a method and working, line by line, to the end of the method. Now it's time to learn how you can control your program flow-the order in which the statements are executed-so that you can do different things based on the data your program receives.
If the idea of computers making decisions based on data seems a little strange, think about how you make decisions. For example, suppose you're expecting an important letter. You go out to your mailbox and look inside. Based on what you find, you choose one of two actions:
Computers use this same method to make decisions (except they never complain and they don't give a darn how late your mail is). You will see the word if used frequently in computer programs. Just as you might say to yourself, "If the mail is in the mailbox, I'll bring it in," a computer also uses an if statement to decide what action to take.
When a program breaks the sequential flow and jumps to a new section of code, it is called branching. When this branching is based on a decision, the program is performing conditional branching. When no decision-making is involved and the program always branches when it encounters a branching instruction, the program is performing unconditional branching. Unconditional branching is rarely used in modern programs, so this chapter deals with conditional branching.
A simple if statement includes the keyword if followed by a logical expression, which, as you learned in the previous chapter, is an expression that evaluates to either true or false. These expressions are surrounded by parentheses. You follow the parentheses with the statement that you want executed if the logical expression is true. For example, look at this if statement:
In the case of an if statement that contains only one program line to be executed, you can choose to include or do away with the curly braces that usually mark a block of code. With this option in mind, you could rewrite the preceding if statement like Listing 9.1.
Another way you'll often see braces used with an if statement is shown here:
How do these if statements work? Let's say that when Java executes the program code in Listing 9.2, the variable choice equals 1. When the program gets to the first if statement, it checks the value of choice. If choice equals 1 (which it does, in this case), the program sets the variable num to 1 and then drops down to the next if statement. This time, the program compares the value of choice with the number 2. Because choice doesn't equal 2, the program ignores the following part of the statement and drops down to the next if statement. The variable choice doesn't equal 3 either, so the code portion of the third if statement is also ignored.
Suppose choice equals 2 when Java executes the code in Listing 9.2. When the program gets to the first if statement, it discovers that choice is not equal to 1, so it ignores the num = 1 statement and drops down to the next program line, which is the second if statement. Again, the program checks the value of choice. Because choice equals 2, the program can execute the second portion of the statement; that is, num gets set to 2. Program execution drops down to the third if statement, which does nothing because choice doesn't equal 3.
What's happening in Listing 9.3? Suppose choice equals 2. When Java gets to the first if statement, it compares the value of choice with the number 1. Because these values don't match (or, as programmers say, the statement doesn't evaluate to true), Java skips over every line until it finds the next if statement.
This brings Java to the second if statement. When Java evaluates the expression, it finds that choice equals 2, and it executes the second portion of the if statement. This time the second portion of the statement is not just one command, but two. The program sets the values of both num and num2.
This brings the program to the last if statement, which Java skips over because choice doesn't equal 3. Notice that, when you want to set up an if statement that executes multiple lines of code, you must use the curly braces-{ and }-to denote the block of instructions that should be executed.
One way to keep processing to a minimum is to use Java's else clause. The else keyword enables you to use a single if statement to choose between two outcomes. When the if statement evaluates to true, the second part of the statement is executed. When the if statement evaluates to false, the else portion is executed. (When the if statement evaluates to neither true nor false, it's time to get a new computer!) Listing 9.4 demonstrates how else works.
In Listing 9.4, if choice equals 1, Java sets num to 1 and num2 to 10. If choice is any other value, Java executes the else portion, setting num to 2 and num2 to 20. As you can see, the else clause provides a default outcome for an if statement. A default outcome doesn't help much, however, if an if statement has to deal with more than two possible outcomes (as in the original Listing 9.3). Suppose you want to rewrite Listing 9.3 so that it works the same but doesn't force Java to evaluate all three if statements unless it really has to. No problem. Listing 9.5 shows you how to use the else if clause:
When Java executes the program code in Listing 9.5, if choice is 1, Java will look at only the first if section and skip over both of the else if clauses. That is, Java will set num to 1 and num2 to 10 and then continue on its way to whatever part of the program followed the final else if clause. Note that, if choice doesn't equal 1, 2, or 3, Java must evaluate all three clauses in the listing but will not do anything with num or num2.
![]()
If you were awake at all during the previous post you should already know how most of the Applet6 applet works. But, there's some new stuff in the paint() method that warrants a close look. First, after converting the user's typed selection from text to an integer, the program uses the integer in an if statement to match up each menu selection with the appropriate color. The setColor() method is part of the Graphics object; you call it to set the color of graphical elements, such as text, that the program draws in the applet's display area. The setColor() method's single argument is the color to set. As you can see, Java has a Color object that you can use to select colors. You'll learn more about the Color object in , "The Java Class Libraries." Notice that, if the user's selection does not match a menu selection, the color is set to black.
After the program sets the color, a second if statement determines which text to display, based on whether the user entered a valid selection. If the user's selection is valid, the program displays "This is the color you chose." in the selected color. Otherwise, the program displays "Invalid menu selection" in black.
You could easily rewrite the preceding if statement as a switch statement, as shown in Listing 9.9:
The first line of a switch statement is the keyword switch followed by the variable whose value will determine the outcome. This variable is called the control variable. Inside the main switch statement (which begins and ends with curly braces) are a number of case clauses, one for each possible value of the switch control variable (the x, in this case). In the above example, if x equals 1, Java jumps to the case 1 and sets y equal to 1. Then, the break statement tells Java that it should skip over the rest of the switch statement.
If x is 2, the same sort of program flow occurs, except Java jumps to the case 2, sets y equal to 2, and then breaks out of the switch. If the switch control variable is not equal to any of the values specified by the various case clauses, Java jumps to the default clause. The default clause, however, is optional. You can leave it out if you want, in which case Java will do nothing if there's no matching case for the control variable.
In this example, funny things happen, depending on whether the control variable x equals 1 or 2. In the former case, Java first jumps to case 1 and sets y equal to 1. Then, because there is no break before the case 2 clause, Java continues executing statements, dropping through the case 2 and setting y equal to 2. Ouch! The moral of the story is: Make sure you have break statements in the right places.
If the outcome of Listing 9.10 was really what you wanted to happen, you'd probably rewrite the switch statement is to look like Listing 9.11:
Here, just as in Listing 9.10, y will end up equal to 2 if x equals 1 or 2. You'll run into this type of switch statement a lot in Java programs. If you're a C or C++ programmer, you've already seen a lot of this sort of thing, so you should feel right at home.
When you run this program, you'll see the same display as the one you saw with Applet6. In fact, from the user's point of view, the program works exactly the same as the previous version. The differences are completely internal.
In this post, you learn how your programs can analyze data in order to decide what parts of your program to execute. Until now, your applets have executed their statements in strict sequential order, starting with the first line of a method and working, line by line, to the end of the method. Now it's time to learn how you can control your program flow-the order in which the statements are executed-so that you can do different things based on the data your program receives.
Controlling Program Flow
Program flow is the order in which a program executes its statements. Most program flow is sequential, meaning that the statements are executed one by one in the order in which they appear in the program or method. However, there are Java commands that make your program jump forward or backward, skipping over program code not currently required. These commands are said to control the program flow.If the idea of computers making decisions based on data seems a little strange, think about how you make decisions. For example, suppose you're expecting an important letter. You go out to your mailbox and look inside. Based on what you find, you choose one of two actions:
- If there's mail in the mailbox, you take the mail into the house.
- If there's no mail in the mailbox, you complain about the postal system.
Computers use this same method to make decisions (except they never complain and they don't give a darn how late your mail is). You will see the word if used frequently in computer programs. Just as you might say to yourself, "If the mail is in the mailbox, I'll bring it in," a computer also uses an if statement to decide what action to take.
Program Flow and Branching
Most programs reach a point where a decision must be made about a piece of data. The program must then analyze the data, decide what to do about it, and jump to the appropriate section of code. This decision-making process is as important to computer programming as pollen is to a bee. Virtually no useful programs can be written without it.When a program breaks the sequential flow and jumps to a new section of code, it is called branching. When this branching is based on a decision, the program is performing conditional branching. When no decision-making is involved and the program always branches when it encounters a branching instruction, the program is performing unconditional branching. Unconditional branching is rarely used in modern programs, so this chapter deals with conditional branching.
The if statement
Most conditional branching occurs when the program executes an if statement, which compares data and decides what to do next based on the result of the comparison. For example, you've probably seen programs that print menus on-screen. To select a menu item, you often type the item's selection number. When the program receives your input, it checks the number you entered and decides what to do. You'd probably use an if statement in this type of program.A simple if statement includes the keyword if followed by a logical expression, which, as you learned in the previous chapter, is an expression that evaluates to either true or false. These expressions are surrounded by parentheses. You follow the parentheses with the statement that you want executed if the logical expression is true. For example, look at this if statement:
if (choice == 5)
g.drawString("You chose number 5.", 30, 30);
In this case, if the variable choice is equal to 5, Java will execute the call to drawString(). Otherwise, Java will just skip the call to drawString(). Example: The Form of an if Statement
The syntax of languages such as Java are tolerant of the styles of various programmers, enabling programmers to construct programs that are organized in a way that's best suited to the programmer and the particular problem. For example, the Java language is not particular about how you specify the part of an if statement to be executed. For example, the statement
if (choice == 1)
num = 10;
could also be written like this: In other words, although the parentheses are required around the logical expression, the code to be executed can be on the same line or the line after the if statement.if (choice == 1) num = 10;
In the case of an if statement that contains only one program line to be executed, you can choose to include or do away with the curly braces that usually mark a block of code. With this option in mind, you could rewrite the preceding if statement like Listing 9.1.
Listing 9.1 LST9_1.TXT: The if Statement with Braces.
if (choice == 1)
{
num = 10;
}
Another way you'll often see braces used with an if statement is shown here:
if (choice == 1) {
num = 10;
}
In this case, the opening brace is on the if statement's first line. | NOTE |
Logical expressions are also called Boolean expressions. That is, a Boolean expression is also an expression that evaluates to either true or false. Now you understand why Java has a boolean data type, which can hold the value true or false. Having the boolean data type enables you to assign the result of a logical expression to a variable. |
Multiple if Statements
You can use a number of if statements to choose between several conditions. For example, look at the group of if statements in Listing 9.2.Listing 9.2 LST9_2.TXT: A Group of if Statements.
if (choice == 1)
num = 1;
if (choice == 2)
num = 2;
if (choice == 3)
num = 3;
How do these if statements work? Let's say that when Java executes the program code in Listing 9.2, the variable choice equals 1. When the program gets to the first if statement, it checks the value of choice. If choice equals 1 (which it does, in this case), the program sets the variable num to 1 and then drops down to the next if statement. This time, the program compares the value of choice with the number 2. Because choice doesn't equal 2, the program ignores the following part of the statement and drops down to the next if statement. The variable choice doesn't equal 3 either, so the code portion of the third if statement is also ignored.
Suppose choice equals 2 when Java executes the code in Listing 9.2. When the program gets to the first if statement, it discovers that choice is not equal to 1, so it ignores the num = 1 statement and drops down to the next program line, which is the second if statement. Again, the program checks the value of choice. Because choice equals 2, the program can execute the second portion of the statement; that is, num gets set to 2. Program execution drops down to the third if statement, which does nothing because choice doesn't equal 3.
| NOTE |
The if statement, no matter how complex it becomes, always evaluates to either true or false. If the statement evaluates to true, the second portion of the statement is executed. If the statement evaluates to false, the second portion of the statement is not executed. |
Multiple-Line if Statements
Listings 9.1 and 9.2 demonstrate the simplest if statement. This simple statement usually fits your program's decision-making needs just fine. Sometimes, however, you want to perform more than one command as part of an if statement. To perform more than one command, enclose the commands within curly braces. Listing 9.3 is a revised version of Listing 9.2 that uses this technique.Listing 9.3 LST9_3.LST: Multiple-Line if Statements.
if (choice == 1)
{
num = 1;
num2 = 10;
}
if (choice == 2)
{
num = 2;
num2 = 20;
}
if (choice == 3)
{
num = 3;
num2 = 30;
}
| TIP |
Notice that some program lines in Listing 9.3 are indented. By indenting the lines that go with each if block, you can more easily see the structure of your program. Listing 9.3 also uses blank lines to separate blocks of code that go together. The compiler doesn't care about the indenting or the blank lines, but these features make your programs easier for you (or another programmer) to read. |
What's happening in Listing 9.3? Suppose choice equals 2. When Java gets to the first if statement, it compares the value of choice with the number 1. Because these values don't match (or, as programmers say, the statement doesn't evaluate to true), Java skips over every line until it finds the next if statement.
This brings Java to the second if statement. When Java evaluates the expression, it finds that choice equals 2, and it executes the second portion of the if statement. This time the second portion of the statement is not just one command, but two. The program sets the values of both num and num2.
This brings the program to the last if statement, which Java skips over because choice doesn't equal 3. Notice that, when you want to set up an if statement that executes multiple lines of code, you must use the curly braces-{ and }-to denote the block of instructions that should be executed.
The else Clause
You might think it's a waste of time for Listing 9.3 to evaluate other if statements after it finds a match for the value of choice. You'd be right, too. When you write programs, you should always look for ways to make them run faster; one way to make a program run faster is to avoid all unnecessary processing. But how, you may ask, do you avoid unnecessary processing when you have to compare a variable with more than one value?One way to keep processing to a minimum is to use Java's else clause. The else keyword enables you to use a single if statement to choose between two outcomes. When the if statement evaluates to true, the second part of the statement is executed. When the if statement evaluates to false, the else portion is executed. (When the if statement evaluates to neither true nor false, it's time to get a new computer!) Listing 9.4 demonstrates how else works.
Listing 9.4 LST9_4.LST: Using the else Clause.
if (choice == 1)
{
num = 1;
num2 = 10;
}
else
{
num = 2;
num2 = 20;
}
In Listing 9.4, if choice equals 1, Java sets num to 1 and num2 to 10. If choice is any other value, Java executes the else portion, setting num to 2 and num2 to 20. As you can see, the else clause provides a default outcome for an if statement. A default outcome doesn't help much, however, if an if statement has to deal with more than two possible outcomes (as in the original Listing 9.3). Suppose you want to rewrite Listing 9.3 so that it works the same but doesn't force Java to evaluate all three if statements unless it really has to. No problem. Listing 9.5 shows you how to use the else if clause:
Listing 9.5 LST9_5.LST: Using if and else Efficiently.
if (choice == 1)
{
num = 1;
num2 = 10;
}
else if (choice == 2)
{
num = 2;
num2 = 20;
}
else if (choice == 3)
{
num = 3;
num2 = 30;
}
When Java executes the program code in Listing 9.5, if choice is 1, Java will look at only the first if section and skip over both of the else if clauses. That is, Java will set num to 1 and num2 to 10 and then continue on its way to whatever part of the program followed the final else if clause. Note that, if choice doesn't equal 1, 2, or 3, Java must evaluate all three clauses in the listing but will not do anything with num or num2.
Example: Using the if Statement in a Program
Now that you've studied what an if statement looks like and how it works, you probably want to see it at work in a real program. Listing 9.6 is a Java program that uses the menu example you studied earlier in this chapter, whereas Listing 9.7 is the HTML document that runs the applet.Listing 9.6 Applet6.java: Using an if Statement in a Program.
import java.awt.*;
import java.applet.*;
public class Applet6 extends Applet
{
TextField textField1;
public void init()
{
textField1 = new TextField(5);
add(textField1);
g.drawString("3. Green", 40, 115);
String s = textField1.getText();
int choice = Integer.parseInt(s);
if (choice == 1)
g.setColor(Color.red);
else if (choice == 2)
g.setColor(Color.blue);
else if (choice == 3)
g.setColor(Color.green);
else
g.setColor(Color.black);
if ((choice >= 1) && (choice <= 3))
g.drawString("This is the color you chose.", 60, 140);
else
g.drawString("Invalid menu selection.", 60, 140);
}
public boolean action(Event event, Object arg)
{
repaint();
return true;
}
}
Tell Java that the program uses classes in the awt package.
Tell Java that the program uses classes in the applet package.
Derive the Applet6 class from Java's Applet class.
Declare a TextField object called textField1.
Override the Applet class's init() method.
Create the TextField object.
Add the TextField object to the applet.
Initialize the text in the TextField object to "1".
Override the Applet class's paint() method.
Display user instructions in the applet's display area.
Display the color menu on three lines.
Get the text from the TextField object.
Convert the text to an integer.
Select a color based on the value the user entered.
Display a message in the appropriate color.
Override the Applet class's action() method.
Tell Java to redraw the applet's display area.
Tell Java that the action() method finished successfully.
Listing 9.7 APPLET6.htmL: The HTML Document That Runs Applet6.
<title>Applet Test Page</title>
<h1>Applet Test Page</h1>
<applet
code="Applet6.class"
width=250
height=150
name="Applet6">
</applet>
If you were awake at all during the previous post you should already know how most of the Applet6 applet works. But, there's some new stuff in the paint() method that warrants a close look. First, after converting the user's typed selection from text to an integer, the program uses the integer in an if statement to match up each menu selection with the appropriate color. The setColor() method is part of the Graphics object; you call it to set the color of graphical elements, such as text, that the program draws in the applet's display area. The setColor() method's single argument is the color to set. As you can see, Java has a Color object that you can use to select colors. You'll learn more about the Color object in , "The Java Class Libraries." Notice that, if the user's selection does not match a menu selection, the color is set to black.
After the program sets the color, a second if statement determines which text to display, based on whether the user entered a valid selection. If the user's selection is valid, the program displays "This is the color you chose." in the selected color. Otherwise, the program displays "Invalid menu selection" in black.
The switch Statement
Another way you can add decision-making code to your programs is with the switch statement. The switch statement gets its name from the fact that it enables a computer program to switch between different outcomes based on a given value. The truth is, a switch statement does much the same job as an if statement, but it is more appropriate for situations where you have many choices, rather than only a few. Look at the if statement in Listing 9.8:Listing 9.8 LST9_8.TXT: A Typical if Statement.
if (x == 1)
y = 1;
if (x == 2)
y = 2;
if (x == 3)
y = 3;
else
y = 0;
You could easily rewrite the preceding if statement as a switch statement, as shown in Listing 9.9:
Listing 9.9 LST9_9.TXT: Changing an if to a switch.
switch(x)
{
case 1:
y = 1;
break;
case 2:
y = 2;
break;
case 3:
y = 3;
break;
default:
y = 0;
}
The first line of a switch statement is the keyword switch followed by the variable whose value will determine the outcome. This variable is called the control variable. Inside the main switch statement (which begins and ends with curly braces) are a number of case clauses, one for each possible value of the switch control variable (the x, in this case). In the above example, if x equals 1, Java jumps to the case 1 and sets y equal to 1. Then, the break statement tells Java that it should skip over the rest of the switch statement.
If x is 2, the same sort of program flow occurs, except Java jumps to the case 2, sets y equal to 2, and then breaks out of the switch. If the switch control variable is not equal to any of the values specified by the various case clauses, Java jumps to the default clause. The default clause, however, is optional. You can leave it out if you want, in which case Java will do nothing if there's no matching case for the control variable.
Example: Using the break Statement Correctly
One tricky thing about switch statements is the various ways that you can use the break statement to control program flow. Look at Listing 9.10:Listing 9.10 LST9_10.TXT: Using break to Control Program Flow.
switch(x)
{
case 1:
y = 1;
case 2:
y = 2;
break;
case 3:
y = 3;
break;
default:
y = 0;
}
In this example, funny things happen, depending on whether the control variable x equals 1 or 2. In the former case, Java first jumps to case 1 and sets y equal to 1. Then, because there is no break before the case 2 clause, Java continues executing statements, dropping through the case 2 and setting y equal to 2. Ouch! The moral of the story is: Make sure you have break statements in the right places.
If the outcome of Listing 9.10 was really what you wanted to happen, you'd probably rewrite the switch statement is to look like Listing 9.11:
Listing 9.11 LST9_11.TXT: Rewriting Listing 9.10.
switch(x)
{
case 1:
case 2:
y = 2;
break;
case 3:
y = 3;
break;
default:
y = 0;
}
Here, just as in Listing 9.10, y will end up equal to 2 if x equals 1 or 2. You'll run into this type of switch statement a lot in Java programs. If you're a C or C++ programmer, you've already seen a lot of this sort of thing, so you should feel right at home.
Example: Using the switch Statement in a Program
You've seen that a switch statement is similar in many ways to an if statement. In fact, if and switch statements can easily be converted from one to the other. Listing 9.12 is a new version of Applet6 (called Applet7) that incorporates the menu example by using a switch statement instead of an if statement.Listing 9.12 APPLET7.JAVA: Using a switch Statement in a Program.
import java.awt.*;
import java.applet.*;
public class Applet7 extends Applet
{
TextField textField1;
public void init()
{
textField1 = new TextField(5);
add(textField1);
textField1.setText("1");
}
public void paint(Graphics g)
{
g.drawString("Type a menu choice in the above box.", 20, 50);
g.drawString("1. Red", 40, 75);
g.drawString("2. Blue", 40, 95);
g.drawString("3. Green", 40, 115);
String s = textField1.getText();
int choice = Integer.parseInt(s);
switch(choice)
{
case 1:
g.setColor(Color.red);
break;
case 2:
g.setColor(Color.blue);
break;
case 3:
g.setColor(Color.green);
break;
default:
g.setColor(Color.black);
}
if ((choice >= 1) && (choice <= 3))
g.drawString("This is the color you chose.", 60, 140);
else
g.drawString("Invalid menu selection.", 60, 140);
}
public boolean action(Event event, Object arg)
{
repaint();
return true;
}
}
When you run this program, you'll see the same display as the one you saw with Applet6. In fact, from the user's point of view, the program works exactly the same as the previous version. The differences are completely internal.
Summary
Making decisions based on the state of data is an important part of a computer program, and now that you have this chapter behind you, you've made a giant leap forward in your Java programming career. You now have enough Java programming savvy to write simple, yet useful, applets. Of course, that's not to say that there isn't a lot left to learn. But by now you should have a good idea of what a Java applet looks like and how it works. The remainder of this book will fill out the details that make Java applets so powerful.Expressions
Without a doubt, expressions are the main building blocks of a program. This is because there are so many different kinds of expressions that a majority of the source-code lines in a program end up being-you guessed it-expressions. There are expressions that result in numerical values. There are expressions that result in strings. There are simple expressions, complex expressions, and all manner of expressions in between.
In the previous chapter, you got a quick look at some kinds of expressions as you put the mathematical operators to work. Now you'll learn not only more about those types of expressions, but also about logical expressions, which help a computer seem to be able to think and make choices. Along the way, you'll discover comparison and logical operators, which make logical expressions possible.
But no matter how complicated, all expressions can be classified into one of three main categories:
But, wait a second-you're not done yet. You can still find more sub-expressions. Look at the multiplication operation. Can you see that it's multiplying two expressions together? Those two expressions look like this:
Table 8.1 Java's Logical Operators.
The other logical expressions work similarly. Table 8.2 lists a number of logical expressions and the results they produce.
Table 8.2 Examples of Logical Expressions.
Table 8.3 Java's Logical Operators.
The AND (&&) operator requires all expressions to be true for the entire expression to be true. For example, the expression
The OR operator (||) requires only one expression to be true for the entire expression to be true. For example, the expressions
The exclusive OR operator (^) is used to determine if one and only one of the expressions being compared is true. Unlike a regular OR, with an exclusive OR, if both expressions are true, the result is false (weird, huh?). For example, the expression
Now, look at this expression:
Table 8.4 Comparison and Logical Operators' Order of Operations.
In the previous chapter, you got a quick look at some kinds of expressions as you put the mathematical operators to work. Now you'll learn not only more about those types of expressions, but also about logical expressions, which help a computer seem to be able to think and make choices. Along the way, you'll discover comparison and logical operators, which make logical expressions possible.
Types of Expressions
To put it simply, an expression is a line of code that can be reduced to a value or that assigns a value. For example, you know that the addition operator adds one expression to another, like this:In the preceding line, expr1 can be something as simple as the variable x or as complex as (4 + 5) * 2 * 5 / 7 + x / y. The same goes for expr2, of course. And, in fact, the first example containing expr1 and expr2 is an expression itself!sum = expr1 + expr2;
But no matter how complicated, all expressions can be classified into one of three main categories:
- Numerical expressions combine numbers, variables, or constants using mathematical operators. An example is 2 + 3 / x.
- Assignment expressions assign a value to a variable. An example is num = 3.
- Logical expressions are unique in that they result in a value of true or false. An example is x < 3 (which reads "x is less than 3").
Expressions Within Expressions
In the previous chapter, whether you were aware of it or not, you used lots of numerical and assignment expressions as you learned about mathematical operators. And if you look closely at some of those expressions, you'll make a neat discovery: Like a bunch of boxes that fit into each other, expressions often contain other simpler expressions. For example, look at the following assignment expression:This is an assignment expression because it assigns a value to the variable num. However, the stuff on either side of the equals sign contains these other expressions:num = (5 - x) * (2 + y);
Both of the above lines are numerical expressions because they can be reduced to a numerical value (assuming that you know the values of num, x, and y.num (5 - x) * (2 + y)
But, wait a second-you're not done yet. You can still find more sub-expressions. Look at the multiplication operation. Can you see that it's multiplying two expressions together? Those two expressions look like this:
And the above simplified expressions contain yet more sub-expressions. Those expressions are:(5 - x) (2 + y)
Expressions are what programmers like to call recursive, meaning that the definition of an expression keeps coming back on itself. An expression contains expressions that contain other expressions, which themselves contain other expressions. How deep you can dig depends on the complexity of the original expression. But, as you saw demonstrated, even the relatively simple expression num = (5 - x) * (2 + y) has four levels of depth.5 x 2 y
Comparison Operators
Now that you've dug into the secrets of expressions, it's time to learn about a new type of operator. So far, you've gotten some practice with mathematical operators, which enable you to build various types of numerical and assignment expressions. Another type of operator you can use to build expressions is the comparison operator. Comparison operators are used to create logical expressions, which, if you recall, result in a value of true or false. Table 8.1 lists the logical expressions used in Java programming. C and C++ programmers will find these operators very familiar.| Description | |
| Equal to | |
| Less than | |
| Greater than | |
| Less than or equal to | |
| Greater than or equal to | |
| Not equal to |
Example: Using Comparison Operators
Just how do you use comparison operators? As their name suggests, you use them to compare two expressions, with the result of the comparison being either true or false. For example, look at this logical expression:The result of the above expression is true because the == operator determines whether the expressions on either side are equal to each other. If you were to change the expression to3 == 2 + 1
the result would be false. That is, 3 does not equal 4. However, the previous sentence suggests a way to rewrite the expression, like this:3 == 2 + 2
This expression results in a value of true, because 3 does not equal 4.3 != 2 + 2
The other logical expressions work similarly. Table 8.2 lists a number of logical expressions and the results they produce.
| Expression | |
| 3 + 4 == 7 | |
| 3 + 4 != 7 | |
| 3 + 4 != 2 + 6 | |
| 3 + 4 < 10 | |
| 3 + 4 <= 10 | |
| 3 + 4 == 4 + 4 | |
| 3 + 4 > 10 | |
| 3 + 4 >= 7 | |
| 3 + 4 >= 8 |
Logical Operators
The comparison operators enable you to compare two expressions. But another type of operator-logical operators-supercharges comparison operators so that you can combine two or more logical expressions into a more complex logical expression. Even if you've never programmed a computer before, you're already familiar with logical operators because you use them in everyday speech. For example, when you say, "Do you have a credit card or ten dollars in cash?" you're using the logical operator OR. Similarly, when you say, "I have a dog and a cat," you're using the AND operator. Table 8.3 lists Java's logical operators and what they mean.| Description | |
| AND | |
| OR | |
| Exclusive OR | |
| NOT |
The AND (&&) operator requires all expressions to be true for the entire expression to be true. For example, the expression
is true because the expressions on both sides of the && are true. However, the expression(3 + 2 == 5) && (6 + 2 == 8)
is false because the expression on the left of the && is not true. Remember this when combining expressions with AND: If any expression is false, the entire expression is false.(4 + 3 == 9) && (3 + 3 == 6)
The OR operator (||) requires only one expression to be true for the entire expression to be true. For example, the expressions
and(3 + 6 == 2) || (4 + 4 == 8)
are both true because at least one of the expressions being compared is true. Notice that in the second case both expressions being compared are true, which also makes an OR expression true.(4 + 1 == 5) || (7 + 2 == 9)
The exclusive OR operator (^) is used to determine if one and only one of the expressions being compared is true. Unlike a regular OR, with an exclusive OR, if both expressions are true, the result is false (weird, huh?). For example, the expression
evaluates to true, whereas these expressions evaluate to false:(5 + 7 == 12) ^ (4 + 3 == 8)
The NOT (!) operator switches the value of (or negates) a logical expression. For example, the expression(5 + 7 == 12) ^ (4 + 3 == 7) (5 + 7 == 10) ^ (4 + 3 == 6)
is false; however, the expression(4 + 3 == 5)
is true.!(4 + 3 == 5)
Example: Using Logical Operators
Take a look at the following expression:Is this expression true or false? If you said true, you understand the way the logical operators work. The expressions on either side of the && are both true, so the entire expression is true. If you said false, you must go to bed without any dinner.(4 + 5 == 9) && !(3 + 1 = 3)
Example: Using Multiple Logical Operators
Just as with mathematical operators, you can use multiple logical operators to compare several logical expressions. For example, look at this expression:This expression gives a result of true because each expression to the left and right of each AND operator is true. However, this expression yields a value of false:(4 == 4) && (5 == 5) && (6 == 6)
Remember that, when using AND, if any sub-expression is false, the entire expression is false. This is kind of like testifying in court. To be true, it's got to be the truth, the whole truth, and nothing but the truth.(4 == 4) && (5 == 6) && (6 == 6)
Example: Combining Different Comparison and Logical Operators
Again, just like mathematical operators, there's no restriction on how you can combine the different comparison and logical operators, although if you build a very complex expression, you may have trouble evaluating it yourself. Check out this expression:Here you've used four different comparison and logical operators in the same complex expression. But because you're comparing the sub-expressions with the AND operator, and because each of the sub-expressions is true, the result of the above expression is true.(3 < 5) && (2 == 2) && (9 > 6)
Now, look at this expression:
Yep, things are getting tricky. Is the above expression true or false? (Hey, give it a shot. You've got a fifty-fifty chance.) Ready for the answer? The above expression is true. First, look at the parentheses. The outermost parentheses, on the left, group the two expressions being compared by the AND operator into a single expression, so evaluate it first. The value 3 is less than 5, but 2 does not equal 1, so the entire expression on the left of the OR operator is false. On the right of the OR operator, however, 7 does indeed equal 7, so this sub-expression is true. Because one of the expressions in the OR comparison is true, the entire expression is true. Here's how the expression breaks down, step-by-step:((3 < 5) && (2 == 1)) || (7 == 7)
((3 < 5) && (2 == 1)) || (7 == 7) ((true) && (false)) || (7 == 7) false || (7 == 7) false || true true
Writing Logical Expressions
You wouldn't write expressions such asin your programs. They would serve no purpose because you already know how the expressions evaluate. However, when you use variables, you have no way of knowing in advance how an expression may evaluate. For example, is the expression(4 + 5 == 9) && !(3 + 1 == 3)
true or false? You don't know without being told the value of the numerical variable num. By using logical operators, though, your program can do the evaluation, and, based on the result-true or false-take the appropriate action. In the next chapter, which is about if and switch statements, you'll see how your programs can use logical expressions to make decisions.(num < 9) && (num > 15)
Order of Operations
Like all operators, comparison and logical operators have an order of operations, or operator precedence. When you evaluate a complex expression, you must be sure to evaluate any sub-expressions in the correct order. As you learned in the previous example, however, you can use parentheses to group expressions so that they're easier to understand or to change the order of operations. Table 8.4 lists the comparison and logical operators in order of precedence.| Operators | Description |
| ! | NOT |
| < > <= >= | Relational |
| == != | Equality |
| ^ | Exclusive OR |
| && | Logical AND |
| || | Logical OR |
Summary
Expressions, which are lines of Java code that can be reduced to a value or that assign a value, come in several types. In this chapter, you not only experimented with numerical and assignment expressions, but you also learned about logical expressions, which you create using the comparison and logical operators. Now that you know how to use comparison and logical operators to build logical expressions, you're ready to discover how computers make decisions. You'll make that discovery in the next chapter, where you'll also start using the operators you learned in order to write actual applets. Before you turn to that chapter, however, test your knowledge of expressions, comparison operators, and logical operators by answering the following review questions and by completing the review exercises.Math Operators
In "Constants and Variables," you got a quick look at a few math operators, including the times (*), plus (+), and minus (-) signs. You even got a chance to use these operators in a few simple mathematical formulas. There's still a lot more to learn about math operators, though, as you'll discover as you read this chapter. Here, you'll not only learn a few more operators, but also learn about operator precedence, which determines the order in which operations are performed.
Be especially careful when you're performing more than one multiplication in a calculation. In such cases, numbers can really get out of hand if you're using the smaller data types like byte or short. Most Java programmers use the int data type for their integer variables, which ensures that their variables have plenty of room for large numbers.
Of course, as I've said before, you should choose the smallest data type that is large enough for the values you'll be using, since the computer must work harder, and thus slower, when it uses larger data types. Still, if you're not performing tons of calculations, using larger data types for safety sake probably won't make a noticeable change in the speed of your applet.
Now, look at these lines:
What if you want to increment a value by more than 1? The old-fashioned way would be to use a line like this:
Once you have all your values converted to the right form, you can go ahead and do the calculations as you learned in this chapter. But what about when you want to show the answers to your applet's user? Again, you need to perform a conversion, this time from numerical form back to string form. Listing 7.1 shows an applet called Applet5 that demonstrates how these conversion tasks work.
![]()
First, near the top of the program, Applet5 declares two TextField objects, like this:
Next, the program overrides the Applet class's init() method. In this method, it first creates two new TextField objects:
The paint() method is where all the action takes place. In paint(), the program first declares three integer variables:
After declaring its variables, paint() displays two lines of text on the applet's display area:
After converting the first string to an integer, paint() handles the second TextField object in exactly the same way:
Table 7.1 Operator Order of Operations.
As I mentioned previously, operator precedence comes into play when you use several different operators in the same calculation. For example, look at this line of Java source code:
If you really wanted to get 24 for an answer, you could use parentheses to change the order of operations, like this:
The Addition Operator
In case you were sleeping during second grade, you might like to know that the addition operator (+) is used to compute the sum of two values. As with all mathematical operations, Java performs these summing tasks just as you did in your second-grade homework. For example, the following line shows the general form of an addition operation in Java:Here, the values represented by expr1 and expr2 are added together (summed), with the result being assigned to the variable represented by result. The values expr1 and expr2 are actually expressions, which means that they can be anything from a literal number like 5 to a complex formula like 5*(3+7)^10. You'll get a closer look at expressions in the next chapter, "Expressions."result = expr1 + expr2;
Example: Using the Addition Operator
Suppose you want to sum the values of two variables. For example, you're writing a program that asks the user for two values and then prints the sum of the values. Assuming that the user's values get stored in two variables called value1 and value2, you might write a line of Java code that looks like this:In this example, if the user entered 12 as the value for value1 and 15 as the value for value2, after Java executed the line, sum would be equal to 27.sum = value1 + value2;
Example: Multiple Additions
In the previous example, you saw the simplest way you can use the addition operator. However, you are not limited to adding only two values. You can, in fact, add as many expressions as you like. To extend the previous example, suppose you have four values you need to sum. You can use a line of code like this:As you'll see in "Expressions," you can create all kinds of complicated mathematical formulas with Java.sum = value1 + value2 + value3 + value4;
The Subtraction Operator
You can use the subtraction operator, which looks like a minus sign (-), to subtract one value or expression from another. Although the subtraction operator yields a different result than the addition operator (thank heavens for that), it's used in exactly the same way, as you can see by this general example:Here, the value represented by expr2 is subtracted from expr1, with the result being assigned to the variable result. Just as you learned with the addition operator, the values expr1 and expr2 are expressions that can be anything that results in a numerical value.result = expr1 - expr2;
Example: Using the Subtraction Operator
Suppose you want to subtract the value of one variable from another. For example, the program you're writing requires that you subtract a customer's monthly payment from the balance he owes. You might write a line of Java code that looks like this:In this example, if the customer's current balance was $110 and he paid $25, after Java executed the line, new_balance would be equal to $85. (Of course, the subtraction is being done with the numbers 110 and 25, and the result is 85. The computer doesn't know anything about dollars, a fact that makes it tough for a computer to do its grocery shopping.)new_balance = current_balance - payment;
| NOTE |
Although the examples you've seen so far use integers, you can use mathematical operators with any type of numerical value, including floating-point. |
Example: Multiple Subtractions Using Mixed Data Types
You know from your experience with the addition operator that you can use more than one mathematical operator in a calculation. The same is true with the subtraction operator. You can also use different types of values in the calculation. For example, suppose you needed to subtract both an integer and a floating-point value from another integer. You could perform this task with a calculation like this:After Java executes the above line, the variable difference will be equal to 81.5. But do you see a potential problem? What type of value is 81.5? If you said "floating point," go to the head of the class. Because 81.5 is a floating-point value, difference must be a floating-point variable. If difference is an integer, Java's compiler will generate an error that tells you "Explicit cast needed to convert float to int." What Java is really saying here is, "If you want to have an integer result, you've got to tell me." In the next example, you see how to tell Java this important information.difference = 100 - 15 - 3.5f;
Example: Casting a Result to a Different Data Type
When you cast a value, you're telling Java that it's okay to convert one type of value to another. You do this by placing in front of the calculation, in parentheses, the data type you want. For example, look at this line of Java code:Because the calculation on the right side of the equals sign results in a floating-point number, difference must be a floating-point variable. After all, computers are very fussy. They refuse to do things like try to stuff a floating-point number into an integer. If difference is an integer, then the result of the calculation must also be an integer. In the above case, you can satisfy Java's compiler by using a type cast, which looks like this:difference = 100 - 15 - 3.5f;
Now, when Java executes the above line, it first calculates the result of 100-15-3.5f, which is 81.5. Then, it converts the result to an integer by dropping the decimal portion of the value. This gives a result of 81. Finally, Java assigns the value of 81 to difference, which is an integer variable. In short, when you use a type cast, you're telling the compiler, "Yes, I know what I'm doing. I want the result converted."difference = (int)(100 - 15 - 3.5f);
| NOTE |
Sometimes the minus sign is used as a negation operator, rather than a subtraction operator. For example, if you want to write a negative number, like negative ten, you'd use the negation operator like this: -10. This is a case where the same symbol is used to mean different things. Java can tell the difference between the negation and a subtraction operators by the context in which the operator is used. |
The Multiplication Operator
By now, you should be getting used to using mathematical operations in simple expressions. The multiplication operator (*) is no different from the addition and subtraction operators, except that it performs a different type of operation. When you want to multiply two numbers together, you use the multiplication operator like this:After Java executes this line, result contains the product of expr1 times expr2. The most important thing to remember about multiplication is that you can run into some pretty big numbers fast. If the result of a multiplication is larger than the data type of the variable that'll hold the answer, you've got trouble, as you'll see in the following example.result = expr1 * expr2;
Example: Multiplication and Data Types
Try to determine the result of the following calculation:If you said the answer is 400, you'd be both right and wrong. While it is true that 20 times 20 is 400, product is only a byte variable, which means it can only hold values from -128 to 127. Unfortunately, Java just goes ahead and stuffs the answer into product whether it fits or not. (The byte type-cast, in fact, converts the answer to a byte before it's stuffed into product, but that's a minor complication.) In the preceding case, you'd end up with an answer of -112.byte product = (byte)(20 * 20);
Be especially careful when you're performing more than one multiplication in a calculation. In such cases, numbers can really get out of hand if you're using the smaller data types like byte or short. Most Java programmers use the int data type for their integer variables, which ensures that their variables have plenty of room for large numbers.
Of course, as I've said before, you should choose the smallest data type that is large enough for the values you'll be using, since the computer must work harder, and thus slower, when it uses larger data types. Still, if you're not performing tons of calculations, using larger data types for safety sake probably won't make a noticeable change in the speed of your applet.
| TIP |
When a mathematical calculation gives you an answer that seems way out of whack, check to make sure that you're using data types that are large enough to hold the values used in the calculation. This is especially true for the result of the calculation. Many hard-to-find program bugs result from using the wrong data types for large values. |
The Division Operator
As you may have guessed, the next operator on the list is the division operator (/), which enables you to divide one value by another. The division operator is used exactly like the other operators you've studied so far, as you can see by this line:Here, result ends up as the result of expr1 divided by expr2. As with multiplication, there's a trap lurking here, but this time it doesn't have as much to do with the size of the numbers as it does in the division operation itself. The problem is that almost all division calculations end up with floating-point values as answers. The following example demonstrates this potential problem.result = expr1 / expr2;
Example: Integer Versus Floating-Point Division
Look at this calculation:When you divide 3 by 2, you may start out with integers, but you end up with 1.5 for an answer, and 1.5 is, of course, a floating-point number. But when Java performs the division shown above, it performs integer division. That is, it drops any decimal portion in the answer, leaving result equal to 1. There are times when this is the type of division you want to perform. But if you want the precise answer to 3 / 2, you're going to have to change something. Maybe changing result to a floating-point variable will make a difference:int result = 3 / 2;
When Java performs this calculation, you still end up with 1 as the answer. Why? Because, as I mentioned before, Java performs integer division on integer values like 3 and 2. To solve the problem, you must also convert 3 and 2 to floating-point values, like this:float result = 3 / 2;
Now, you'll get the correct result of 1.5. Actually, only one of the numbers to the right of the equals sign needs to be floating-point in order to get a floating-point answer. This line will work, too:float result = 3f / 2f;
float result = 3f / 2;
The Modulo Operator
In the previous section, you learned that integer division gives you a result that's equal to the number of times one number fits into another, regardless of the remainder. For example, you now know that, in Java, the answer to "3 divided by 2" is 1, meaning that 2 fits into 3 only once. Integer division throws away the remainder, but what if it's the remainder you're looking for? Then, you can use the modulo operator (%) like this:This line results in the remainder of expr1 divided by expr2. For example, the calculationresult = expr1 % expr2;
makes result equal to 2, because 3 goes into 11 three times with a remainder of 2. You probably won't use the modulo operator much, but it can be handy for special types of calculations.int result = 11 % 3;
The Increment Operator
Many times in a program, you want to increase a value by a specific amount. For example, if you were using the variable count to keep track of how many times a part of your program executed, you need to add 1 to count each time you reached that part of the program. Programmers used to do this kind of incrementing like this:Here, the computer takes the value stored in count, increases it by 1, and then assigns the new value to count. If you've ever programmed in C or C++, you know that those languages have a shortcut way of incrementing a value. Because Java is much like C++, its creators also included this shortcut operator. Using the increment operator (++), you can replace the previous line with this one:count = count + 1;
Another way to write the preceding line is like this:++count;
There is, however, a subtle difference in the way the increment operator works when it's placed before (pre-increment) or after (post-increment) the value it's incrementing. The difference crops up when you use the operator in expressions. For example, look at these lines of Java program code:count++;
Here, Java first sets the variable num1 to 1. In the second line, Java increments num1 to 2 and then assigns 2 to num2.int num1 = 1; int num2 = ++num1;
Now, look at these lines:
This time, num2 ends up as 1. Why? In the second line, Java doesn't increment num1 until after it assigns the current value of num1 (1) to num2. Watch out for this little detail when you get started writing your own applets.int num1 = 1; int num2 = num1++;
What if you want to increment a value by more than 1? The old-fashioned way would be to use a line like this:
Java has a special shortcut operator that handles the above situation, too. You use the shortcut operator like this:num = num + 5;
The above line just says, "Add 5 to num."num += 5;
The Decrement Operator
In computer programs, you don't always count forwards. Often, you need to count backwards as well. That's why Java has the decrement operator (- -), which works just like the increment operator, except it subtracts 1 instead of adding it. You use the decrement operator like this:The above example uses the pre-decrement version of the operator. If you want to decrement the value after it's been used in an expression, use the post-decrement version, like this:- -num;
The set of operators wouldn't be complete without a decrement operator that enables you to subtract any value from a variable. The following linenum- -;
tells Java to decrement num by 5.num -= 5;
Example: Using Mathematical Calculations in an Applet
It's one thing to learn about mathematical operators and how they're used to perform calculations. It's quite another to actually use these operators in an actual program. This is because, when performing calculations in programs, you frequently have to do a lot of conversions from numerical values to strings and vice versa. For example, suppose you ask the user for a number that you need in order to perform a calculation. When you retrieve the number from the user, it's still in string form. You can't use the text character "3" in a calculation. You need to convert the string form of "3" to the numerical form.Once you have all your values converted to the right form, you can go ahead and do the calculations as you learned in this chapter. But what about when you want to show the answers to your applet's user? Again, you need to perform a conversion, this time from numerical form back to string form. Listing 7.1 shows an applet called Applet5 that demonstrates how these conversion tasks work.
Listing 7.1 Applet5.java: Source Code for the Applet5 Applet.
import java.awt.*;
import java.applet.*;
public class Applet5 extends Applet
{
TextField textField1;
TextField textField2;
public void init()
{
textField1 = new TextField(5);
textField2 = new TextField(5);
add(textField1);
add(textField2);
textField1.setText("0");
textField2.setText("0");
}
public void paint(Graphics g)
{
int value1;
int value2;
int sum;
g.drawString("Type a number in each box.", 40, 50);
g.drawString("The sum of the values is:", 40, 75);
String s = textField1.getText();
value1 = Integer.parseInt(s);
s = textField2.getText();
value2 = Integer.parseInt(s);
sum = value1 + value2;
s = String.valueOf(sum);
g.drawString(s, 80, 100);
}
public boolean action(Event event, Object arg)
{
repaint();
return true;
}
}
Tell Java that the program uses classes in the awt package.Use the procedures you learned in the previous chapter to compile and run the Applet5 applet. Remember that to do this, you must follow these steps:
Tell Java that the program uses classes in the applet package.
Derive the Applet5 class from Java's Applet class.
Declare TextField objects called textField1 and textField2.
Override the Applet class's init() method.
Create the two TextField objects.
Add the two TextField objects to the applet.
Initialize the text in both TextField objects to "0".
Override the Applet class's paint() method.
Declare three integers called value1,value2, and sum.
Display two text strings in the applet's display area.
Get the text from first TextField object.
Convert the text to an integer.
Get the text from the second TextField object.
Convert the text to an integer.
Add the two converted values together.
Convert the sum to a string.
Draw the text string on the applet's surface.
Override the Applet class's action() method.
Tell Java to redraw the applet's display area.
Tell Java that the action() method finished successfully.
- Type and save the program (or copy it from the CD-ROM).
- Compile the applet.
- Write an HTML document to test the applet.
- Use Appletviewer to display the HTML document containing the applet.
How Applet5 Works
Although Applet5's source code is a little longer than other applets you've seen, it's really not much more complicated. It simply uses a few more variables in order to store the values needed to perform its calculations.First, near the top of the program, Applet5 declares two TextField objects, like this:
These TextField objects represent the text boxes in which the user types the values to be summed.TextField textField1; TextField textField2;
Next, the program overrides the Applet class's init() method. In this method, it first creates two new TextField objects:
The program then adds the TextField objects to the applet:textField1 = new TextField(5); textField2 = new TextField(5);
Finally, in order to be sure the program doesn't try to sum two non-existent values, init() initializes the text contained in the TextField objects to "0":add(textField1); add(textField2);
textField1.setText("0");
textField2.setText("0");
The TextField class's setText() method sets the text contained in the control to the text string given as the method's single argument. | NOTE |
Overriding a method is the process of replacing a method found in the base class with a version specific to the new class. In other words, the Applet class from which Applet5 is derived also has an init() method. If you didn't override init() in Applet5, Java would call the original version in Applet instead. |
The paint() method is where all the action takes place. In paint(), the program first declares three integer variables:
int value1; int value2; int sum;
| NOTE |
Because it takes a certain amount of time for a computer to allocate memory for variables, it's not always a good idea to declare variables inside the paint() method, which must run as quickly as possible. I chose to use this generally frowned upon practice in order to keep the programming examples simple and easy-to-understand. However, keep in mind that the paint() method must do as little processing as possible in order to keep it up to speed. |
After declaring its variables, paint() displays two lines of text on the applet's display area:
g.drawString("Type a number in each box.", 40, 50);
g.drawString("The sum of the values is:", 40, 75);
Then, the program extracts the text from the first TextField object and converts that text from a string to a numerical value (in this case, an integer): You've seen the TextField class's getText() method before. The second line above, however, introduces you to a new class and method. The Integer class offers many methods that make working with integers easier. For example, the parseInt() method used in the second line above enables you to convert the contents of a string to an integer (assuming, of course, that the string contains numerical digits).String s = textField1.getText(); value1 = Integer.parseInt(s);
After converting the first string to an integer, paint() handles the second TextField object in exactly the same way:
Now the program has two integer values, stored in the variables value1 and value2, that it can sum, which it does like this:s = textField2.getText(); value2 = Integer.parseInt(s);
After Java executes the above lines, the answer to the calculation is stored in sum. The program now needs to display the answer to the applet's user. However, before it can do that, it must convert the numerical value in sum to a text string that can be displayed on the screen. You know that the String class's valueOf() method handles this task. The last thing paint() does, then, is convert sum to a string and display the string on the screen:sum = value1 + value2;
The last method in Applet3 is action(), which you learned about in the previous chapter. To review, Java calls action() whenever the user performs some action with the applet's controls. In this case, action() responds when the user presses Enter in one of the TextField objects.s = String.valueOf(sum); g.drawString(s, 80, 100);
The Order of Operations
Now that you know how to use mathematical operators, you need to know about the complications you can run into when you use different operators in the same calculation. The order of operations, which is also called operator precedence, determines the order in which mathematical computations are performed. If you've ever taken algebra, you know that mathematicians long ago set up a standard set of symbols for mathematical operations as well as defined the order in which they're performed. These mathematical rules are also observed in programming languages like Java. Table 7.1 lists Java's mathematical operators in order of precedence.| Description | |
| Negation | |
| Increment | |
| Decrement | |
| Multiplication | |
| Division | |
| Modulus | |
| Addition | |
| Subtraction | |
| Assignment |
As I mentioned previously, operator precedence comes into play when you use several different operators in the same calculation. For example, look at this line of Java source code:
Go ahead and do the calculation. What did you get for an answer? If you got 18, you already know how operator precedence works. If you're new to this sort of thing, you probably got 24 for an answer, which is incorrect. The reason 18 is the correct answer is because operator precedence dictates that the multiplication be performed before the addition. If you look at Table 7.1, you can see that multiplication comes before addition.answer = 3 + 5 * 3;
If you really wanted to get 24 for an answer, you could use parentheses to change the order of operations, like this:
Now, the answer would be 24, because the parentheses tell Java to do the addition first.answer = (3 + 5) * 3;
Example: Order of Operations
If you've never dealt with order of operations before, you'll probably need a little practice to get the hang of it. Look at this calculation:You should get 13 for an answer. Because addition and subtraction have the same order of precedence in this calculation (yes, I know the table lists subtraction after addition, but if you do the subtraction first, you'll still get 13 for an answer), you can just work from left to right to solve this problem.answer = 5 + 3 - 2 + 7;
Example: More Order of Operations
The previous example was pretty easy. Ready to try something a little tougher? Look at this calculation:What do you get for an answer? You should have gotten 22. If you got 12, you forgot that multiplication and division are performed before addition.answer = 4 * 5 + 4 / 2;
Example: Still More Order of Operations
Suppose I change the previous example to this:You should get 18 for an answer, because the added parentheses tell you to perform the addition first.answer = 4 * (5 + 4) / 2;
Example: One Last Order of Operations
Okay, now you're going to get a chance to prove that you really know your stuff. Solve this calculation:The answer is 12. You solve the problem as shown below:answer = 2 * 3 + 6 * 3 - (4 + 2) * 2;
answer = 2 * 3 + 6 * 3 - (4 + 2) * 2;
answer = 2 * 3 + 6 * 3 - 6 * 2;
answer = 6 + 6 * 3 - 6 * 2;
answer = 6 + 18 - 6 * 2;
answer = 6 + 18 - 12;
answer = 12;
Summary
Almost all computer programs perform mathematical calculations. So that you can specify the types of calculations you want performed, computer languages such as Java feature mathematical operators for standard operations such as addition, subtraction, multiplication, and division. However, when using these operators, always remember operator precedence (or order of operations), which determines the order in which calculations are completed.Constants and Variables
If there's one thing that every computer program has in common, it's that they always process data input and produce some sort of output based on that data. And because data is so important to a computer program, it stands to reason that there must be plenty of different ways to store data so that programs can do their processing correctly and efficiently. In order to keep track of data, programs use constants and variables. In this chapter, you discover what constants and variables are, as well as learn to use them in the Java language.
Such values as the numeral 2 and the string constant "Java" are sometimes called hard-coded values because the values that represent the constants are placed literally in the program code. For example, suppose you were writing a program and wanted to calculate the amount of sales tax on a purchase. Suppose further that the total purchase in question is $12.00 and the sales tax in your state is 6 percent. The calculation that'll give you the sales tax would look like this:
To avoid these situations, programmers often use something called symbolic constants, which are simply words that represent values in a program. In the case of your sales tax program, you could choose a word like SALESTAX (no spaces) to represent the current sales tax percentage for your state. Then, at the beginning of your program, you set SALESTAX to be equal to the current state sales tax. In the Java language, such a line of program code might look like this:
After defining the symbolic constant SALESTAX, you can rewrite any lines that use the current sales tax value to use the symbolic constant rather than the hard-coded value. For example, the calculation for the sales tax on that $12.00 purchase might now look something like this:
Now, when your state changes the sales tax to 7 percent, you need only change the value you assign to the symbolic constant and the rest of the program automatically fixes itself. The change would look like this:
Why do programs need variables? Think back to the sales tax program from the previous section. You may recall that you ended up with a program line that looked like this:
Do you see another place where a variable is necessary? How about the hard-coded value 12? Such a hard-coded value makes a program pretty useless because every person that comes into your store to buy something isn't going to spend exactly $12.00. Because the amount of each customer's purchase will change, the value used in your sales tax calculation must change, too. That means you need another variable. How about creating a variable named purchase? With such a variable, you can rewrite the calculations like this:
Math-savvy readers may have already figured that the preceding two lines can be easily simplified into one, like this:
Although adding comments to the program lines helps a little, the code is still pretty confusing, because you don't really know what the variables a, b, c, and d stand for. After a while (probably when mathematicians weren't the only programmers), someone came up with the idea of allowing more than one character in a variable name, which would enable the programmer to create mathematical expressions that read more like English. Thus, the confusing example above would be written as Listing 5.2.
By using carefully chosen variable names, you can make your programs self documenting, which means that the program lines themselves tell whoever might be reading the program what the program does. If you strip away the comments from the preceding example, you can still see what calculations are being performed.
Of course, there are rules for choosing constant and variable names (also known as identifiers because they identify a program object). You can't just type a bunch of characters on your keyboard and expect Java to accept them. First, every Java identifier must begin with one of these characters:
Following the first character, the rest of the identifier can use any of these characters:
Using the rules given, the following are valid identifiers in a Java program:
Now, you need to come up with the mathematical formula that'll give you the answer you want. First, you know that the total number of vehicles in the garage is equal to the sum of the number of cars, trucks, and vans in the garage. Stating the problem in this way not only clarifies what form the calculation must take, but also suggests a set of good identifiers for your program. Those identifiers are cars, trucks, vans, and total_vehicles. So, in Java, your first calculation looks like this:
The first integer type, byte, takes up the least amount of space in a computer's memory. When you declare a constant or variable as byte, you are limited to values in the range -128 to 127. Why would you want to limit the size of a value in this way? Because the smaller the data type, the faster the computer can manipulate it. For example, your computer can move a byte value, which consumes only eight bits of memory, much faster than an int value, which, in Java, is four times as large.
In Java, you declare a byte value like this:
The next biggest type of Java integer is short. A variable declared as short can hold a value from -32,768 to 32,767. You declare a short value like this:
Next in the integer data types is int, which can hold a value from -2,147,483,648 to 2,147,483,647. Now you're getting into some big numbers! The int data type can hold such large numbers because it takes up 32 bits (four bytes) of computer memory. You declare int values like this:
Java includes two floating-point types, which are float and double. Each type allows greater precision in calculations. What does this mean? Floating-point numbers can become very complex when they're used in calculations, particularly in multiplication and division. For example, when you divide 3.9 by 2.7, you get 1.44444444. In actuality, though, the fractional portion of the number goes on forever. That is, if you were to continue the division calculation, you'd discover that you keep getting more and more fours in the fractional part of the answer. The answer to 3.9 divided by 2.7 is not really 1.44444444, but rather something more like 1.4444444444444444. But even that answer isn't completely accurate. A more accurate answer would be 1.44444444444444444444444444444444. The more 4s you add to the answer the more accurate the answer becomes-yet, because the 4s extend on into infinity, you can never arrive at a completely accurate answer.
Dealing with floating-point values frequently means deciding how many decimal places in the answer is accurate enough. That's where the difference between the float and double data types shows up. In Java, a value declared as float can hold a number in the range from around -3.402823 x 10 38 to around 3.402823 x 10 38. These types of values are also known as single-precision floating-point numbers and take up 32 bits (four bytes) of memory. You declare a single-precision floating-point number like this:
The second type of floating-point data, double, represents a double-precision value, which is a much more accurate representation of floating-point numbers because it allows for more decimal places. A double value can be in the range from -1.79769313486232 x 10 308 to 1.79769313486232 x 10 308 and is declared like this:
In order to provide storage for character values, Java features the char data type, which is 16 bits. However, the size of the char data type has little to do with the values it can hold. Basically, you can think of a char as being able to hold a single character. (The 16 bit length accommodates Unicode characters, which you don't need to worry about in this book.) You declare a char value like this:
Some characters cannot be written with only a single symbol. For example, the tab character is represented in Java as \t, which is a backslash followed by a lowercase t. There are several of these special characters, as shown in Table 5.1.
Table 5.1 Special Character Literals.
Although the special characters in Table 5.1 are represented by two symbols, the first of which is always a backslash, you still use them as single characters. For example, to define a char variable as a backspace character, you might write something like the following in your Java program:
Table 5.2 summarizes Java's various data types. Take some time now to look over the table and make sure you understand how the data types differ from each other. You might also want to think of ways you might use each data type in an actual program.
Table 5.2 Summary of Java's Data Types.
Now you're probably wondering, "What the devil is a program block?" Generally, a program block is a section of program code that starts with an opening curly brace ({) and ends with a closing curly brace (}). (Sometimes, the beginning and ending of a block are not explicitly defined, but you don't have to worry about that just yet.) Specifically, program blocks include things like classes, functions, and loops, all of which you'll learn about later in this book.
Of course, things aren't quite as simple as all that (you're dealing with computers, after all). The truth is that you can have program blocks within other program blocks. When you have one block inside another, the inner block is considered to be nested. Figure 5.1 illustrates the concept of nested program blocks.
Block 1 encloses both Block 2 and Block 3. That is, Block 2 and Block 3 are nested within Block 1, because these blocks occur after Block 1's opening brace but before Block 1's closing brace. If you wanted, you could also create a Block 4 and nest it within Block 2 or Block 3, and thus create even another level of nesting. As you'll see when you start writing full-length Java programming, all programs have a lot of nesting going on.
The ability to nest program blocks adds a wrinkle to the idea of variable scope. Because a variable remains in scope from the beginning of its block to the end of its block, such a variable is also in scope in any blocks that are nested in the variable's block. For example, looking back at Figure 5.1, a variable that's defined in Block 1 is accessible in not just Block 1, but also in Block 2 and Block 3. However, a variable defined inside Block 2 is accessible only in Block 2, because such a variable goes into scope at the start of Block 2 and goes out of scope at the end of Block 2. If you're a little confused, the following example ought to clear things up.
Now look at the variables being used in this program. The first variable defined in the program is value1, which is found right after the main block's opening brace. This means that value1 is accessible in all three blocks, as you can see by looking at the Block2 and Block3 blocks, both of which assign new values to value1.
The second variable in the program, value2, is defined inside the Block2 block, where it's both declared and assigned the value 4.5f. In the Block3 block, the program tries to assign a value to value2. If you tried to compile this program, you'd see that this line creates an error message, as shown in Figure 5.2. In the figure, the compiler is insisting that value2 in the Block3 block is undefined, which, of course, is true as far as the Block3 block is concerned. You'd get a similar message if you tried to access value2 anywhere but within the scope of the Block2 block.
You can use variable scope to simplify the access of variables in a program. For example, you will usually declare variables that you need in many places, so that they are in scope in the entire class. That way, you can access the variables without having to pass them as arguments to functions. (If you don't know about argument passing just yet, you will after you read "Functions.") On the other hand, you'll have lots of variables that you use only inside one particular program block. You can keep your program uncluttered by being sure to declare these types of variables only in the blocks in which they're used. You'll learn more about setting up variables with the proper scope as you write Java programs later in this book.
Constants
If you think about the term "constant" for a few moments, you might conclude that constants must have something to do with data that never changes. And your conclusion would be correct. A constant is nothing more than a value, in a program, that stays the same throughout the program's execution. However, while the definition of a constant is fairly simple, constants themselves can come in many different guises. For example, the numeral 2, when it's used in a line of program code, is a constant. If you place the word "Java" in a program, the characters that comprise the word are also constants. In fact, these constant characters taken together are often referred to as a string constant.| NOTE |
To be entirely accurate, I should say that text and numerals that are placed in program code are actually called literals, because the value is literally, rather than symbolically, in the program. If this literal and symbolic stuff is confusing you, you'll probably have it figured out by the end of this chapter. For now, just know that I'm lumping literals in with constants to simplify the discussion. |
Such values as the numeral 2 and the string constant "Java" are sometimes called hard-coded values because the values that represent the constants are placed literally in the program code. For example, suppose you were writing a program and wanted to calculate the amount of sales tax on a purchase. Suppose further that the total purchase in question is $12.00 and the sales tax in your state is 6 percent. The calculation that'll give you the sales tax would look like this:
Suppose now that you write a large program that uses the sales tax percentage in many places. Then, after you've been happily using your program for a few months, the state suddenly decides to raise the sales tax to seven percent. In order to get your program working again, you have to go through every line of code, looking for the .06 values that represent the sales tax and changing them to .07. Such a modification can be a great deal of work in a large program. Worse, you may miss one or two places in the code that need to be changed, leaving your program with some serious bugs.tax = 12 * .06;
To avoid these situations, programmers often use something called symbolic constants, which are simply words that represent values in a program. In the case of your sales tax program, you could choose a word like SALESTAX (no spaces) to represent the current sales tax percentage for your state. Then, at the beginning of your program, you set SALESTAX to be equal to the current state sales tax. In the Java language, such a line of program code might look like this:
In the preceding line, the word final tells Java that this data object is going to be a constant. The float is the data type, which, in this case, is a floating point. (You'll learn more about data types later in this chapter.) The word SALESTAX is the symbolic constant. The equals sign tells Java that the word on the left should be equal to the value on the right, which, in this case, is 0.06.final float SALESTAX = 0.06;
After defining the symbolic constant SALESTAX, you can rewrite any lines that use the current sales tax value to use the symbolic constant rather than the hard-coded value. For example, the calculation for the sales tax on that $12.00 purchase might now look something like this:
tax = 12 * SALESTAX;
| TIP |
In order to differentiate symbolic constants from other values in a program, programmers often use all uppercase letters when naming these constants. |
Now, when your state changes the sales tax to 7 percent, you need only change the value you assign to the symbolic constant and the rest of the program automatically fixes itself. The change would look like this:
final float SALESTAX = 0.07;
Variables
If constants are program values that cannot be changed throughout the execution of a program, what are variables? Variables are values that can change as much as needed during the execution of a program. Because of a variable's changing nature, there's no such thing as a hard-coded variable. That is, hard-coded values in a program are always constants (or, more accurately, literals).Why do programs need variables? Think back to the sales tax program from the previous section. You may recall that you ended up with a program line that looked like this:
In this line, the word tax is a variable. So, one reason you need variables in a program is to hold the results of a calculation. In this case, you can think of the word tax as a kind of digital bucket into which the program dumps the result of its sales tax calculation. When you need the value stored in tax, you can just reach in and take it out-figuratively speaking, of course. As an example, to determine the total cost of a $12.00 purchase, plus the sales tax, you might write a line like this:tax = 12 * SALESTAX;
In this line, the word total is yet another variable. After the computer performs the requested calculation, the variable total will contain the sum of 12 and whatever value is stored in tax. For example, if the value 0.72 is stored in tax, after the calculation, total would be equal to 12.72.total = 12 + tax;
Do you see another place where a variable is necessary? How about the hard-coded value 12? Such a hard-coded value makes a program pretty useless because every person that comes into your store to buy something isn't going to spend exactly $12.00. Because the amount of each customer's purchase will change, the value used in your sales tax calculation must change, too. That means you need another variable. How about creating a variable named purchase? With such a variable, you can rewrite the calculations like this:
Now you can see how valuable variables can be. Every value in the preceding lines is represented by a variable. (Although you're using SALESTAX as a symbolic constant, because of Java's current lack of true constants, it's really a variable, too.) All you have to do to get the total to charge your customer is plug the cost of his purchase into the variable purchase, something you'll see how to do in "Simple Input and Output."tax = purchase * SALESTAX; total = purchase + tax;
Math-savvy readers may have already figured that the preceding two lines can be easily simplified into one, like this:
This revised line of code, however, is not as easy to understand as the original two lines were. In programming, you must constantly decide between longer, simpler code and shorter, more complex code. I tend to go for the longer, easy-to-understand approach, except when the longer code might bog down the program.total = purchase + (purchase * SALESTAX);
Naming Constants and Variables
The first computer languages were developed by mathematicians. For that reason, the calculations and the variables used in those calculations were modeled after the types of equations mathematicians were already accustomed to working with. For example, in the old days, the lines in your tax program might have looked like this:As you can see, this type of variable-naming convention left a lot to be desired. It's virtually impossible to tell what type of calculations are being performed. In order to understand their own programs, programmers had to use tons of comments mixed in with their source code so they could remember what the heck they were doing from one programming session to the next. Such a section of source code in Java might look like Listing 5.1.a = b * c; d = b + a;
Listing 5.1 LST5_1.TXT: An Example of Mathematician's Variables.
// Calculate the amount of sales tax. a = b * c; // Add the sales tax to the purchase amount. d = b + a;
Although adding comments to the program lines helps a little, the code is still pretty confusing, because you don't really know what the variables a, b, c, and d stand for. After a while (probably when mathematicians weren't the only programmers), someone came up with the idea of allowing more than one character in a variable name, which would enable the programmer to create mathematical expressions that read more like English. Thus, the confusing example above would be written as Listing 5.2.
Listing 5.2 LST5_2.TXT: Using English-like Variable Names.
// Calculate the amount of sales tax. tax = purchase * SALESTAX; // Add the sales tax to the purchase amount. total = purchase + tax;
By using carefully chosen variable names, you can make your programs self documenting, which means that the program lines themselves tell whoever might be reading the program what the program does. If you strip away the comments from the preceding example, you can still see what calculations are being performed.
Of course, there are rules for choosing constant and variable names (also known as identifiers because they identify a program object). You can't just type a bunch of characters on your keyboard and expect Java to accept them. First, every Java identifier must begin with one of these characters:
A-ZThe preceding characters are any uppercase letter from A through Z, any lowercase letter from a through z, an underscore, and the dollar sign.
a-z
_
$
Following the first character, the rest of the identifier can use any of these characters:
A-ZAs you may have noticed, this second set of characters is very similar to the first. In fact, the only difference is the addition of the digits from 0 through 9.
a-z
_
$
0-9
| NOTE |
Java identifiers can also use Unicode characters above the hexadecimal value of 00C0. If you don't know about Unicode characters, don't panic; you won't be using them in this book. Briefly put, Unicode characters expand the symbols that can be used in a character set to include characters that are not part of the English language. |
Using the rules given, the following are valid identifiers in a Java program:
The following identifiers are not valid in a Java program:number number2 amount_of_sale $amount
1number amount of sale &amount item#
Example: Creating Your Own Identifiers
Suppose that you're now ready to write a program that calculates the total number of parking spaces left in a parking garage. You know that the total number of spaces in the garage is 100. You further know that the vehicles in the garage are classified as cars, trucks, and vans. The first step is to determine which values would be good candidates for constants. Because a constant should represent a value that's not likely to change from one program run to another, the number of vehicles that the garage can hold would make a good constant. Thinking hard (someone smell wood burning?), you come up with an identifier of TOTALSPACES for this value. In Java, the constant's definition looks like this:In this line, the keyword int represents the data type, which is integer. You should be able to understand the rest of the line.final int TOTALSPACES = 100;
Now, you need to come up with the mathematical formula that'll give you the answer you want. First, you know that the total number of vehicles in the garage is equal to the sum of the number of cars, trucks, and vans in the garage. Stating the problem in this way not only clarifies what form the calculation must take, but also suggests a set of good identifiers for your program. Those identifiers are cars, trucks, vans, and total_vehicles. So, in Java, your first calculation looks like this:
The next step is to subtract the total number of vehicles from the total number of spaces that the garage holds. For this calculation, you need only one new identifier to represent the remaining spaces, which is the result of the calculation. Again, stating the problem leads to the variable name, which might be remaining_spaces. The final calculation then looks like this:total_vehicles = cars + trucks + vans;
remaining_spaces = TOTALSPACES - total_vehicles;
Data Types
In attempting to give you a quick introduction to constants and variables, the preceding sections skipped over a very important attribute of all constants and variables: data type. You may remember my mentioning two data types already, these being floating point (represented by the float keyword) and integer (represented by the int keyword). Java has eight different data types, all of which represent different kinds of values in a program. These data types are byte, short, int, long, float, double, char, and boolean. In this section, you'll learn what kinds of values these various data types represent.Integer Values
The most common values used in computer programs are integers, which represent whole number values such as 12, 1988, and -34. Integer values can be both positive or negative, or even the value 0. The size of the value that's allowed depends on the integer data type you choose. Java features four integer data types, which are byte, short, int, and long. Although some computer languages allow both signed and unsigned integer values, all of Java's integers are signed, which means they can be positive or negative. (Unsigned values, which Java does not support, can hold only positive numbers.)The first integer type, byte, takes up the least amount of space in a computer's memory. When you declare a constant or variable as byte, you are limited to values in the range -128 to 127. Why would you want to limit the size of a value in this way? Because the smaller the data type, the faster the computer can manipulate it. For example, your computer can move a byte value, which consumes only eight bits of memory, much faster than an int value, which, in Java, is four times as large.
In Java, you declare a byte value like this:
In the preceding line, byte is the data type for the value, and identifier is the variable's name. You can also simultaneously declare and assign a value to a variable like this:byte identifier;
After Java executes the preceding line, your program will have a variable named count that currently holds the value of 100. Of course, you can change the contents of count at any time in your program. It only starts off holding the value 100.byte count = 100;
The next biggest type of Java integer is short. A variable declared as short can hold a value from -32,768 to 32,767. You declare a short value like this:
orshort identifier;
In the preceding line, value can be any value from -32,768 to 32,767, as described previously. In Java, short values are twice as big in memory-16 bits (or two bytes)-as byte values.short identifier = value;
Next in the integer data types is int, which can hold a value from -2,147,483,648 to 2,147,483,647. Now you're getting into some big numbers! The int data type can hold such large numbers because it takes up 32 bits (four bytes) of computer memory. You declare int values like this:
orint identifier;
The final integer data type in the Java language is long, which takes up a whopping 64 bits (eight bytes) of computer memory and can hold truly immense numbers. Unless you're calculating the number of molecules in the universe, you don't even have to know how big a long number can be. I'd figure it out for you, but I've never seen a calculator that can handle numbers that big. You declare a long value like this:int identifier = value;
orlong identifier;
long identifier = value;
| TIP |
How do you know which integer data type to use in your program? Choose the smallest data type that can hold the largest numbers you'll be manipulating. Following this rule keeps your programs running as fast as possible. However, having said that, I should tell you that most programmers (including me) use the int data type a lot, even when they can get away with a byte. |
Floating-Point Values
Whereas integer values can hold only whole numbers, the floating-point data types can hold values with both whole number and fractional parts. Examples of floating-point values include 32.9, 123.284, and -43.436. As you can see, just like integers, floating-point values can be either positive or negative.Java includes two floating-point types, which are float and double. Each type allows greater precision in calculations. What does this mean? Floating-point numbers can become very complex when they're used in calculations, particularly in multiplication and division. For example, when you divide 3.9 by 2.7, you get 1.44444444. In actuality, though, the fractional portion of the number goes on forever. That is, if you were to continue the division calculation, you'd discover that you keep getting more and more fours in the fractional part of the answer. The answer to 3.9 divided by 2.7 is not really 1.44444444, but rather something more like 1.4444444444444444. But even that answer isn't completely accurate. A more accurate answer would be 1.44444444444444444444444444444444. The more 4s you add to the answer the more accurate the answer becomes-yet, because the 4s extend on into infinity, you can never arrive at a completely accurate answer.
Dealing with floating-point values frequently means deciding how many decimal places in the answer is accurate enough. That's where the difference between the float and double data types shows up. In Java, a value declared as float can hold a number in the range from around -3.402823 x 10 38 to around 3.402823 x 10 38. These types of values are also known as single-precision floating-point numbers and take up 32 bits (four bytes) of memory. You declare a single-precision floating-point number like this:
orfloat identifier;
In the second line, value must be a value in the range given in the previous paragraph, followed by an upper- or lowercase F. However, you can write floating-point numbers in a couple of ways, using regular digits and a decimal point or using scientific notation. This value is the type of floating-point number you're used to seeing:float identifier = value;
356.552Now, here's the same number written using Java's rules, in both the number's normal form and in the form of scientific notation:
356.552fBoth of the preceding values are equivalent, and you can use either form in a Java program. The e2 in the second example is the equivalent of writing x 102 and is a short form of scientific notation that's often used in programming languages.
3.56552e2f
| NOTE |
If you're not familiar with scientific notation, the value 3.402823 x 10 38 is equal to 3.402823 times a number that starts with a 1 and is followed by 38 zeroes. Computer languages shorten this scientific notation to 3.402823e38. |
The second type of floating-point data, double, represents a double-precision value, which is a much more accurate representation of floating-point numbers because it allows for more decimal places. A double value can be in the range from -1.79769313486232 x 10 308 to 1.79769313486232 x 10 308 and is declared like this:
ordouble identifier;
Floating-point values of the double type are written exactly as their float counterparts, except you use an upper- or lowercase D as the suffix, rather than an F. Here's a few examples:double identifier = value;
3.14d
344.23456D
3.4423456e2d
| TIP |
When using floating-point numbers in your programs, the same rule that you learned about integers applies: Use the smallest data type you can. This is especially true for floating-point numbers, which are notorious for slowing computer programs to a crawl. Unless you're doing highly precise programming, such as 3-D modeling, the single-precision float data type should do just fine. |
Character Values
Often in your programs, you'll need a way to represent character values rather than just numbers. A character is a symbol that's used in text. The most obvious examples of characters are the letters of the alphabet, in both upper- and lowercase varieties. There are, however, many other characters, including not only things such as spaces, exclamation points, and commas, but also tabs, carriage returns, and line feeds. The symbols 0 through 9 are also characters when they're not being used in mathematical calculations.In order to provide storage for character values, Java features the char data type, which is 16 bits. However, the size of the char data type has little to do with the values it can hold. Basically, you can think of a char as being able to hold a single character. (The 16 bit length accommodates Unicode characters, which you don't need to worry about in this book.) You declare a char value like this:
orchar c;
In the second example, you're not only declaring the variable c as a char, but also setting its value to an uppercase A. Notice that the character that's being assigned is enclosed in single quotes.char c = 'A';
Some characters cannot be written with only a single symbol. For example, the tab character is represented in Java as \t, which is a backslash followed by a lowercase t. There are several of these special characters, as shown in Table 5.1.
| Character | |
| Backslash | |
| Backspace | |
| Carriage return | |
| Double quote | |
| Form feed | |
| Line feed | |
| Single quote | |
| Tab |
Although the special characters in Table 5.1 are represented by two symbols, the first of which is always a backslash, you still use them as single characters. For example, to define a char variable as a backspace character, you might write something like the following in your Java program:
When Java's compiler sees the backslash, it knows that it's about to encounter a special character of some type. The symbol following the backslash tells the compiler which special character to use. Because the backslash is used to signify a special character, when you want to specify the backslash character yourself, you must use two backslashes, which keeps the compiler from getting confused. Other special characters that might confuse the compiler because they are used as part of the Java language are single and double quotes. When you want to use these characters in your program's data, you must also precede them with a backslash.char backspace = '\b';
Boolean Values
Many times in a program, you need a way to determine if a specific condition has been met. For example, you might need to know whether a part of your program executed properly. In such cases, you can use Boolean values, which are represented in Java by the boolean data type. Boolean values are unique in that they can be only one of two possible values: true or false. You declare a boolean value like this:orboolean identifier;
In the second example, value must be true or false. In an actual program, you might write something like this:boolean identifier = value;
Boolean values are often used in if statements, which enable you to do different things depending on the value of a variable. You'll learn about if statements in Chapter 9, "The if and switch Statements."boolean file_okay = true;
Table 5.2 summarizes Java's various data types. Take some time now to look over the table and make sure you understand how the data types differ from each other. You might also want to think of ways you might use each data type in an actual program.
| Type | Value |
| byte | -128 to 127 |
| short | -32,768 to 32,767 |
| int | -2,147,483,648 to 2,147,483,647 |
| long | Huge |
| float | -3.402823e38 to 3.402823e38 |
| double | -1.79769313486232e308 to 1.79769313486232e308 |
| char | Symbols used in text |
| boolean | True or false |
Variable Scope
When you write your Java programs, you can't just declare your variables willy-nilly all over the place. You first have to consider how and where you need to use the variables. This is because variables have an attribute known as scope, which determines where in your program variables can be accessed. In Java, a variable's scope is determined by the program block in which the variable first appears. The variable is "visible" to the program only from the beginning of its program block to the end of the program block. When a program's execution leaves a block, all the variables in the block disappear, a phenomenon that programmers call "going out of scope."Now you're probably wondering, "What the devil is a program block?" Generally, a program block is a section of program code that starts with an opening curly brace ({) and ends with a closing curly brace (}). (Sometimes, the beginning and ending of a block are not explicitly defined, but you don't have to worry about that just yet.) Specifically, program blocks include things like classes, functions, and loops, all of which you'll learn about later in this book.
Of course, things aren't quite as simple as all that (you're dealing with computers, after all). The truth is that you can have program blocks within other program blocks. When you have one block inside another, the inner block is considered to be nested. Figure 5.1 illustrates the concept of nested program blocks.
Block 1 encloses both Block 2 and Block 3. That is, Block 2 and Block 3 are nested within Block 1, because these blocks occur after Block 1's opening brace but before Block 1's closing brace. If you wanted, you could also create a Block 4 and nest it within Block 2 or Block 3, and thus create even another level of nesting. As you'll see when you start writing full-length Java programming, all programs have a lot of nesting going on.
The ability to nest program blocks adds a wrinkle to the idea of variable scope. Because a variable remains in scope from the beginning of its block to the end of its block, such a variable is also in scope in any blocks that are nested in the variable's block. For example, looking back at Figure 5.1, a variable that's defined in Block 1 is accessible in not just Block 1, but also in Block 2 and Block 3. However, a variable defined inside Block 2 is accessible only in Block 2, because such a variable goes into scope at the start of Block 2 and goes out of scope at the end of Block 2. If you're a little confused, the following example ought to clear things up.
Example: Determining a Variable's Scope
Suppose you've written the small Java program shown in Listing 5.3. (Nevermind, at this point, that you don't know much about writing Java programs. Such minor details will be remedied by the time you complete this book.) The program shown in the listing follows the same program structure as that shown in Figure 5.1. That is, there is one large main block that contains two nested blocks. The main block begins with the opening brace on the second line and ends with the closing brace at the end of the program. The first inner block begins with the opening brace after the line labeling Function1 and ends with the closing brace three lines below the opening brace. The second inner block is defined similarly, with its own opening and closing braces.Listing 5.3 LST5_3.TXT: Determining Variable Scope.
public class Block1 extends Applet
{
int value1 = 32;
void Block2()
{
float value2 = 4.5f;
value1 = 45;
}
void Block3()
{
value1 = 100;
// The following line causes an error.
value2 = 55.46f;
}
}
Now look at the variables being used in this program. The first variable defined in the program is value1, which is found right after the main block's opening brace. This means that value1 is accessible in all three blocks, as you can see by looking at the Block2 and Block3 blocks, both of which assign new values to value1.
The second variable in the program, value2, is defined inside the Block2 block, where it's both declared and assigned the value 4.5f. In the Block3 block, the program tries to assign a value to value2. If you tried to compile this program, you'd see that this line creates an error message, as shown in Figure 5.2. In the figure, the compiler is insisting that value2 in the Block3 block is undefined, which, of course, is true as far as the Block3 block is concerned. You'd get a similar message if you tried to access value2 anywhere but within the scope of the Block2 block.
You can use variable scope to simplify the access of variables in a program. For example, you will usually declare variables that you need in many places, so that they are in scope in the entire class. That way, you can access the variables without having to pass them as arguments to functions. (If you don't know about argument passing just yet, you will after you read "Functions.") On the other hand, you'll have lots of variables that you use only inside one particular program block. You can keep your program uncluttered by being sure to declare these types of variables only in the blocks in which they're used. You'll learn more about setting up variables with the proper scope as you write Java programs later in this book.
Summary
All computers must manipulate data in order to produce output. Java, like all programming languages, features many data types that you can use for constants and variables in your programs. These data types enable you to store everything from simple integers like 23 and -10 to strings and complex floating-point numbers. There's a lot to know about variables, so your head may be spinning a bit at this point. Rest assured, however, that once you start writing programs and using variables, all the theoretical stuff will make sense.
Subscribe to:
Comments (Atom)