The Conditional Operator and the 'switch' Statement

Read this chapter, which discusses the switch and '?' operators to write conditional statements. As you read this tutorial, you will learn that sometimes it is better to use a 'switch' statement when there are multiple choices to choose from. Under such conditions, an if/else structure can become very long, obscure, and difficult to comprehend. Once you have read the tutorial, you will understand the similarity of the logic used for the 'if/else' statement, '?', and 'switch' statements and how they can be used alternately.

1. More Ways to Make Decisions

Nested if and else statements can be used to choose between any number of options. But, using nested statements is sometimes awkward. This chapter discusses two other statements that choose between several options.

Neither of these two statements does anything that can't be done with ifs and elses. But they are sometimes useful, and you will need to know them to understand programs written by other programmers.

Some programmers avoid using these statements. Neither statement is used in the AP Computer Science test. This entire chapter may be skipped. These statements are not used in the chapters that follow.

Chapter Topics:

      • The conditional operator ?
      • The switch statement

Question 1:

  • What is the absolute value of -9?
  • What is the absolute value of +9?


Source: Bradley Kjell, http://programmedlessons.org/Java9/chap34/ch34_01.html
Creative Commons License This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 License.