Sams Teach Yourself Java 2 in 24 Hours
- Table of Contents
- Copyright
- About the Author
- About the Technical Editor
- Acknowledgments
- We Want to Hear from You!
- Reader Services
- Introduction
- Hour 1. Becoming a Programmer
- Hour 2. Writing Your First Program
- Hour 3. Vacationing in Java
- Hour 4. Understanding How Java Programs Work
- Part II: Learning the Basics of Programming
- Hour 5. Storing and Changing Information in a Program
- Hour 6. Using Strings to Communicate
- Hour 7. Using Conditional Tests to Make Decisions
- Hour 8. Repeating an Action with Loops
- Part III: Working with Information in New Ways
- Hour 9. Storing Information with Arrays
- Hour 10. Creating Your First Object
- Hour 11. Describing What Your Object Is Like
- Hour 12. Making the Most of Existing Objects
- Part IV: Programming a Graphical User Interface
- Hour 13. Building a Simple User Interface
- Hour 14. Laying Out a User Interface
- Hour 15. Responding to User Input
- Hour 16. Building a Complex User Interface
- Part V: Creating Multimedia Programs
- Hour 17. Creating Interactive Web Programs
- Hour 18. Handling Errors in a Program
- Hour 19. Creating a Threaded Program
- Hour 20. Reading and Writing Files
- Part VI: Creating Multimedia Programs
- Hour 21. Using Fonts and Color
- Hour 22. Playing Sound Files
- Hour 23. Working with Graphics
- Hour 24. Creating Animation
- Part VII: Appendixes
- Appendix A. Tackling New Features of Java 2 Version 1.4
- Appendix B. Using the Java 2 Software Development Kit
- Appendix C. Programming with the Java 2 Software Development Kit
- Appendix D. Using Sun ONE Studio
- Appendix E. Where to Go from Here: Java Resources
- Appendix F. This Book's Web Site
if Statements
If you want to test a condition in a Java program, the most basic way is with an if statement. As you learned previously, the boolean variable type is used to store only two possible values: true or false. The if statement works along the same lines, testing to see whether a condition is true or false, and taking action only if the condition is true.
You use if along with a condition to test, as in the following statement:
if (account < 0.01)
System.out.println("Hear that bouncing noise? It's your checks");
Although this code is listed on two lines, it's one statement. The first part uses if to determine whether the account variable is less than 0.01 (1 cent) by using the < operator. The second part displays the text Hear that bouncing noise? It's your checks.
The second part of an if statement will be run only if the first part is true. In the preceding example, if the account variable has a value of 0.01 or higher, the println statement will be ignored. Note that the condition you test with an if statement must be surrounded by parentheses, as in (account < 0.01).
The less-than operator, <, is one of several different operators you can use with conditional statements. You'll become more familiar with the if statement as you use it with some of the other operators.
Less Than and Greater Than Comparisons
In the preceding section, the < operator is used the same way it was used in math class: as a less-than sign. There is also a greater-than conditional operator: >. This operator is used in the following statements:
if (elephantWeight > 780)
System.out.println("Elephant too fat for tightrope act.");
if (elephantTotal > 12)
cleaningExpense = cleaningExpense + 150;
The first if statement tests whether the value of the elephantWeight variable is greater than 780. The second if statement tests whether the elephantTotal variable is greater than 12.
One thing to understand about if statements is that they often cause nothing to happen in your programs. If the two preceding statements are used in a program where elephantWeight is equal to 600 and elephantTotal is equal to 10, the rest of the if statements will be ignored.
There will be times when you want to determine whether something is less than or equal to something else. You can do this with the <= operator, as you might expect; use the >= operator for greater-than-or-equal-to tests. Here's an example:
if (account <= 0)
System.out.println("Hear that bouncing noise? It's your checks");
This revision of the checkbook example mentioned previously should be a bit easier to understand. It tests whether account is less than or equal to the value 0, and taunts the user if it is.
Equal and Not Equal Comparisons
Another condition to check in a program is equality. Is a variable equal to a specific value? Is one variable equal to the value of another? These questions can be answered with the == operator, as in the following statements:
if (answer == rightAnswer)
studentGrade = studentGrade + 10;
if (studentGrade == 100)
System.out.println("Such a show off!");
You can also test inequality—whether something is not equal to something else. This is accomplished with the != operator, as shown in the following example:
if (answer != rightAnswer)
score = score - 5;
You can use the == and != operators reliably with every type of variable except one: strings. To see whether one string has the value of another, use the equals() method described during Hour 6, "Using Strings to Communicate."
Organizing a Program with Block Statements
Up to this point, all of the if statements have been followed with a single instruction, such as the println() method. In many cases, you will want to perform more than one action in response to an if statement. To do this, you'll use the { and } characters to create a block statement. I believe the technical term for these characters is "squiggly bracket marks."
Block statements are statements that are organized into a group. Previously, you have seen how block statements are used to mark the beginning and end of the main() block of a Java program. Each statement within the main() block is handled when the program is run. Listing 7.1 is an example of a Java program with a block statement used to denote the main() block. The block statement begins with the opening bracket { on Line 2 and ends with the closing bracket } on Line 11. Load your word processor and enter the text of Listing 7.1 as a new file.
Example 7.1. The Game Program
1: class Game {
2: public static void main(String[] arguments) {
3: int total = 0;
4: int score = 7;
5: if (score == 7)
6: System.out.println("You score a touchdown!");
7: if (score == 3)
8: System.out.println("You kick a field goal!");
9: total = total + score;
10: System.out.println("Total score: " + total);
11: }
12: }
Save this file as Game.java and compile it. If you're using the SDK, you can compile it by typing the following command:
javac Game.java
When you run the program, the output should resemble Listing 7.2.
Example 7.2. The Output of the Game Program
You score a touchdown! Total score: 7
You also can use block statements in conjunction with if statements to make the computer do more than one thing if a conditional statement is true. The following is an example of an if statement that includes a block statement:
if (playerScore > 9999) {
playerLives++;
System.out.println("Extra life!");
difficultyLevel = difficultyLevel + 5;
}
The brackets are used to group all statements that are part of the if statement. If the variable playerScore is greater than 9,999, three things will happen:
- The value of the playerLives variable increases by one (because the increment operator ++ is used).
- The text Extra life! is displayed.
- The value of the difficultyLevel variable is increased by 5.
If the variable playerScore is not greater than 9,999, nothing will happen. All three statements inside the if statement block will be ignored.
if-else Statements | Next Section

Account Sign In
View your cart