0% found this document useful (0 votes)
18 views24 pages

C Mps 161 Class Notes Chap 03

Uploaded by

Avinash R Gowda
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views24 pages

C Mps 161 Class Notes Chap 03

Uploaded by

Avinash R Gowda
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Chapter 3

Selections

3.1 Introduction

• Java provides selections that let you choose actions with two or more alternative
courses.
• Selection statements use conditions. Conditions are Boolean expressions.
• Java has several types of selection statements:
o if Statements, if … else statements, nested if statements
o switch Statements
o Conditional Expressions

3.2 boolean Data Type

• Often in a program you need to compare two values, such as whether i is greater than
j. Java provides six comparison operators (also known as relational operators) that
can be used to compare two values. The result of the comparison is a Boolean value:
true or false.

TABLE 3.1 Comparison Operators


Operator Name
< less than
<= less than or equal to
> greater than
>= greater than or equal to
== equal to
!= not equal to

• Examples
System.out.println(1 < 2); // Displays true

boolean b = (1 > 2);


System.out.println("b is " + b); // Displays b is false

CMPS161 Class Notes (Chap 03) Page 1 /24 Kuo-pao Yang


3.3 Problem: A Simple Math Learning Tool

• This example creates a program to let a first grader practice additions. The program
randomly generates two single-digit integers number1 and number2 and displays a
question such as “What is 7 + 9?” to the student. After the student types the answer,
the program displays a message to indicate whether the answer is true or false.
• LISTINT 3.1 AdditionQuiz.java

import java.util.Scanner;

public class AdditionQuiz {


public static void main(String[] args) {
int number1 = (int)(System.currentTimeMillis() % 10);
int number2 = (int)(System.currentTimeMillis() * 7 % 10);

// Create a Scanner
Scanner input = new Scanner(System.in);

System.out.print(
"What is " + number1 + " + " + number2 + "? ");

int answer = input.nextInt();

System.out.println(
number1 + " + " + number2 + " = " + answer + " is " +
(number1 + number2 == answer));
}
}

What is 1 + 7? 8
1 + 7 = 8 is true

What is 4 + 8? 9
4 + 8 = 9 is false

CMPS161 Class Notes (Chap 03) Page 2 /24 Kuo-pao Yang


3.4 if Statements

• Java has several types of selection statements:


o if Statements, if … else statements, nested if statements
o switch Statements
o Conditional Expressions

3.4.1 One-Way if Statements


if (booleanExpression) {
statement(s);
} // execution flow chart is shown in Figure (A)

Example
if (radius >= 0) {
area = radius * radius * PI;
System.out.println("The area for the circle of radius " +
radius + " is " + area);
} // if the Boolean expression evaluates to T, the statements in the
block are executed as shown in figure (B)

false false
Boolean (radius >= 0)
Expression

true true

Statement(s) area = radius * radius * PI;


System.out.println("The area for the circle of " +
"radius " + radius + " is " + area);

(A) (B)

FIGURE 3.1 An if statement executes statements if the Boolean Expression evaluates as


true

CMPS161 Class Notes (Chap 03) Page 3 /24 Kuo-pao Yang


• Note:
o The Boolean expression is enclosed in parentheses for all forms of the if
statement. Thus, the outer parentheses in the previous if statements are required.
o The braces can be omitted if they enclose a single statement.

Outer parentheses required Braces can be omitted if the block contains a single
statement

if ((i > 0) && (i < 10)) { Equivalent if ((i > 0) && (i < 10))
System.out.println("i is an " + System.out.println("i is an " +
+ "integer between 0 and 10"); + "integer between 0 and 10");
}
(a)
(b)

• Write a program that prompts the user to enter an integer. If the number is a multiple
of 5, print HiFive. If the number is divisible by 2, print HiEven.
• LISTING 3.2 SimpleIfDemo.java
import java.util.Scanner;

public class SimpleIfDemo {


public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter an integer: ");
int number = input.nextInt();

if (number % 5 == 0)
System.out.println("HiFive");

if (number % 2 == 0)
System.out.println("HiEven");
}
}

Enter an integer: 4
HiEven

Enter an integer: 30
HiFive
HiEven

CMPS161 Class Notes (Chap 03) Page 4 /24 Kuo-pao Yang


3.5 Problem: Guessing Birthdays

• The program can guess your birth date.


= 19

1 3 5 7 2 3 6 7 4 5 6 7 8 9 10 11 16 17 18 19
9 11 13 15 10 11 14 15 12 13 14 15 12 13 14 15 20 21 22 23
17 19 21 23 18 19 22 23 20 21 22 23 24 25 26 27 24 25 26 27
25 27 29 31 26 27 30 31 28 29 30 31 28 29 30 31 28 29 30 31
Set1 Set2 Set3 Set4 Set5

Note: 19 is 10011 in binary. 7 is 111 in binary. 23 is 11101 in binary


10000
10000 00110 1000
10 10 100
+ 1 + 1 + 1
10011 00111 11101

19 7 23
Is your birthday in Set1?
1 3 5 7
• LISTING 3.3 GuessBirthday.java 9 11 13 15
17 19 21 23
import java.util.Scanner; 25 27 29 31
Enter 0 for No and 1 for Yes: 1
public class GuessBirthday {
Is your birthday in Set2?
public static void main(String[] args) {
2 3 6 7
String set1 = 10 11 14 15
" 1 3 5 7\n" + 18 19 22 23
" 9 11 13 15\n" + 26 27 30 31
"17 19 21 23\n" + Enter 0 for No and 1 for Yes: 1
"25 27 29 31";
Is your birthday in Set3?
String set2 = 4 5 6 7
" 2 3 6 7\n" + 12 13 14 15
20 21 22 23
"10 11 14 15\n" +
28 29 30 31
"18 19 22 23\n" + Enter 0 for No and 1 for Yes: 0
"26 27 30 31"; Ï
Is your birthday in Set4?
String set3 = 8 9 10 11
" 4 5 6 7\n" + 12 13 14 15
"12 13 14 15\n" + 24 25 26 27
"20 21 22 23\n" + 28 29 30 31
"28 29 30 31"; Enter 0 for No and 1 for Yes: 0
Ï
String set4 = Is your birthday in Set5?
" 8 9 10 11\n" + 16 17 18 19
20 21 22 23
"12 13 14 15\n" + 24 25 26 27
"24 25 26 27\n" + 28 29 30 31
"28 29 30 31"; Enter 0 for No and 1 for Yes: 1
Ï
String set5 = Your birthday is 19!
"16 17 18 19\n" +

CMPS161 Class Notes (Chap 03) Page 5 /24 Kuo-pao Yang


"20 21 22 23\n" +
"24 25 26 27\n" +
"28 29 30 31";

int day = 0;

// Create a Scanner
Scanner input = new Scanner(System.in);

// Prompt the user to answer questions


System.out.print("Is your birthday in Set1?\n");
System.out.print(set1);
System.out.print("\nEnter 0 for No and 1 for Yes: ");
int answer = input.nextInt();

if (answer == 1)
day += 1;

// Prompt the user to answer questions


System.out.print("\nIs your birthday in Set2?\n");
System.out.print(set2);
System.out.print("\nEnter 0 for No and 1 for Yes: ");
answer = input.nextInt();

if (answer == 1)
day += 2;

// Prompt the user to answer questions


System.out.print("Is your birthday in Set3?\n");
System.out.print(set3);
System.out.print("\nEnter 0 for No and 1 for Yes: ");
answer = input.nextInt();

if (answer == 1)
day += 4;

// Prompt the user to answer questions


System.out.print("\nIs your birthday in Set4?\n");
System.out.print(set4);
System.out.print("\nEnter 0 for No and 1 for Yes: ");
answer = input.nextInt();

if (answer == 1)
day += 8;

// Prompt the user to answer questions


System.out.print("\nIs your birthday in Set5?\n");
System.out.print(set5);
System.out.print("\nEnter 0 for No and 1 for Yes: ");
answer = input.nextInt();

if (answer == 1)
day += 16;

System.out.println("\nYour birthday is " + day + "!");


}
}

CMPS161 Class Notes (Chap 03) Page 6 /24 Kuo-pao Yang


3.6 Two-Way if Statements
if (booleanExpression) {
statement(s)-for-the-true-case;
}
else {
statement(s)-for-the-false-case;
}

true false
Boolean
Expression

Statement(s) for the true case Statement(s) for the false case

FIGURE 3.3 An if … else executes statements for the true case if the Boolean expression evaluations are
true; otherwise, statements for the false case are executed.

• if...else Example

if (radius >= 0) {
area = radius * radius * PI;

System.out.println("The area for the “


+ “circle of radius " + radius +
" is " + area);
}
else {
System.out.println("Negative input");// braces may be omitted
}
Note: If radius >= 0 is true, area is computed and displayed; if it is false, the
message “Negative input” is printed.

• Using the if … else statement, you can rewrite the following code for determining
whether a number is even or odd, as follows:

if (number % 2 == 0)
System.out.println(number + “ is even.”);
if (number % 2 != 0)
System.out.println(number + “is odd.”);

// rewriting the code using else


if (number % 2 == 0)
System.out.println(number + “ is even.”);
else
System.out.println(number + “is odd.”);
Note: This is more efficient because whether number % 2 is 0 is tested only once.

CMPS161 Class Notes (Chap 03) Page 7 /24 Kuo-pao Yang


3.7 Nested if Statements

• The statement in an if or if ... else statement can be any legal Java statement,
including another if or if ... else statement. The inner if statement is said to be nested
inside the outer if statement.
• The inner if statement can contain another if statement.
• There is no limit to the depth of the nesting.

if (i > k) {
if (j > k)
System.out.println(“i and j are greater than k”);
}
else
System.out.println(“i is less than or equal to k”);
// the if (j > k) is nested inside the if (i > k)

• The nested if statement can be used to implement multiple alternatives.

if (score >= 90)


grade = ‘A’;
else
if (score >= 80)
grade = ‘B’;
else
if (score >= 70)
grade = ‘C’;
else
if (score >= 60)
grade = ‘D’;
else
grade = ‘F’;

• The preceding if statement is equivalent to the following preferred format because


it is easier to read:
if (score >= 90)
grade = ‘A’;
else if (score >= 80)
grade = ‘B’;
else if (score >= 70)
grade = ‘C’;
else if (score >= 60)
grade = ‘D’;
else
grade = ‘F’;

CMPS161 Class Notes (Chap 03) Page 8 /24 Kuo-pao Yang


Tip
• Often new Programmers write that assigns a test condition to a Boolean variable like
the code in (a).
if (number % 2 == 0) Equivalent
even = true; boolean even
else = number % 2 == 0;
even = false;
(a) (b)

• The code can be simplified by assigning the test value directly to the variable, as
shown in (b).

CMPS161 Class Notes (Chap 03) Page 9 /24 Kuo-pao Yang


3.8 Common Errors in Selection Statements

• Common Error 1: Forgetting Necessary Braces

if (radius >= 0) if (radius >= 0){


area = radius * radius * PI; area = radius * radius * PI;
System.out.println("The area " System.out.println("The area "
+ " is " + area); + " is " + area);
}

(a) Wrong (b) Correct

• Common Error 2: Wrong Semicolon at the if Line


o Adding a semicolon at the end of an if clause is a common mistake.
o This mistake is hard to find, because it is not a compilation error or a runtime
error, it is a logic error.
o This error often occurs when you use the next-line block style.

if (radius >= 0) ; if (radius >= 0) { } ;


{ {
area = radius * radius * PI; Equivalent area = radius * radius * PI;
System.out.println("The area " ========== System.out.println("The area "
+ " is " + area); + " is " + area);
} }

(a) (b)

• Common Error 3: Redundant Testing of Boolean Values


o To test whether a Boolean variable is true or false in a test condition, it is
redundant to use the equality comparison operator like this:

Equivalent if (even)
if (even == true)
System.out.println( System.out.println(
"It is even."); "It is even.");
(a) (b)

Caution
o What’s wrong with the following?

if (even = true)
System.out.println(“It is even.”);

This statement does not have syntax errors. It assigns true to even so that even is
always true.

CMPS161 Class Notes (Chap 03) Page 10 /24 Kuo-pao Yang


• Common Error 4: Dangling else Ambiguity
o The else clause matches the most recent unmatched if clause in the same block.
For example, the following statement:

int i = 1; int j = 2; int k = 3;


if (i > j)
if (i > k)
System.out.println("A");
else
System.out.println("B");

is equivalent to:

int i = 1; int j = 2; int k = 3;


if (i > j)
if (i > k)
System.out.println("A");
else
System.out.println("B");

o Nothing is printed from the preceding statement because the compiler ignores
indentation. To force the else clause to match the first if clause, you must add a
pair of braces:

int i = 1; int j = 2; int k = 3;


if (i > j) {
if (i > k)
System.out.println("A");
}
else
System.out.println("B");

This statement prints B.

CMPS161 Class Notes (Chap 03) Page 11 /24 Kuo-pao Yang


3.9 Problem: An Improved Math Learning Tool (Page 82)

• This example creates a program to teach a first grade child how to learn subtractions.
The program randomly generates two single-digit integers number1 and number2
with number1 > number2 and displays a question such as “What is 9 – 2?” to the
student, as shown in the figure. After the student types the answer in the input dialog
box, the program displays a message dialog box to indicate whether the answer is
correct.
• LISTING 3.4 SubtractionQuiz.java

import java.util.Scanner;

public class SubtractionQuiz {


public static void main(String[] args) {
// 1. Generate two random single-digit integers
int number1 = (int)(Math.random() * 10);
int number2 = (int)(Math.random() * 10);

// 2. If number1 < number2, swap number1 with number2


if (number1 < number2) {
int temp = number1;
number1 = number2;
number2 = temp;
}

// 3. Prompt the student to answer “what is number1 – number2?”


System.out.print
("What is " + number1 + " - " + number2 + "? ");
Scanner input = new Scanner(System.in);
int answer = input.nextInt();

// 4. Grade the answer and display the result


if (number1 - number2 == answer)
System.out.println("You are correct!");
else
System.out.println("Your answer is wrong.\n" + number1 + " - "
+ number2 + " should be " + (number1 - number2));
}
}

What is 6 - 6? 0
You are correct!

What is 9 - 2? 5
Your answer is wrong.
9 - 2 should be 7

CMPS161 Class Notes (Chap 03) Page 12 /24 Kuo-pao Yang


3.10 Problem: Computing Body Mass Index (Page 84)

• Body Mass Index (BMI) is a measure of health on weight. It can be calculated by


taking your weight in kilograms and dividing by the square of your height in meters.
The interpretation of BMI for people 16 years or older is as follows:

BMI Interpretation

below 16 serious underweight


16-18 underweight
18-24 normal weight
24-29 overweight
29-35 seriously overweight
above 35 gravely overweight

Enter weight in pounds: 146


• LISTING 3.5 ComputeBMI.java Enter height in inches: 70
Your BMI is 20.95
import java.util.Scanner; You are normal weight

public class ComputeAndInterpretBMI {


public static void main(String[] args) {
Scanner input = new Scanner(System.in);

// Prompt the user to enter weight in pounds


System.out.print("Enter weight in pounds: ");
double weight = input.nextDouble();

// Prompt the user to enter height in inches


System.out.print("Enter height in inches: ");
double height = input.nextDouble();

final double KILOGRAMS_PER_POUND = 0.45359237; // Constant


final double METERS_PER_INCH = 0.0254; // Constant

// Compute BMI
double weightInKilograms = weight * KILOGRAMS_PER_POUND;
double heightInMeters = height * METERS_PER_INCH;
double bmi = weightInKilograms /
(heightInMeters * heightInMeters);

// Display result
System.out.printf("Your BMI is %5.2f\n", bmi);
if (bmi < 16)
System.out.println("You are seriously underweight");
else if (bmi < 18)
System.out.println("You are underweight");
else if (bmi < 24)
System.out.println("You are normal weight");
else if (bmi < 29)
System.out.println("You are overweight");
else if (bmi < 35)
System.out.println("You are seriously overweight");
else
System.out.println("You are gravely overweight");
}
}

CMPS161 Class Notes (Chap 03) Page 13 /24 Kuo-pao Yang


3.11 Problem: Computing Taxes (Page 85)

• The US federal personal income tax is calculated based on the filing status and
taxable income. There are four filing statuses: single filers, married filing jointly,
married filing separately, and head of household. The tax rates for 2009 are shown
below.

TABLE 3.2 2009 U.S. Federal Personal Tax Rates

import java.util.Scanner;

public class ComputeTax {


public static void main(String[] args) {
// Create a Scanner
Scanner input = new Scanner(System.in);

// Prompt the user to enter filing status


System.out.print(
"(0-single filer, 1-married jointly,\n" +
"2-married separately, 3-head of household)\n" +
"Enter the filing status: ");
int status = input.nextInt();

// Prompt the user to enter taxable income


System.out.print("Enter the taxable income: ");
double income = input.nextDouble();

// Compute tax
double tax = 0;

if (status == 0) { // Compute tax for single filers


if (income <= 8350)
tax = income * 0.10;
else if (income <= 33950)
tax = 8350 * 0.10 + (income - 8350) * 0.15;
else if (income <= 82250)
tax = 8350 * 0.10 + (33950 - 8350) * 0.15 +
(income - 33950) * 0.25;
else if (income <= 171550)

CMPS161 Class Notes (Chap 03) Page 14 /24 Kuo-pao Yang


tax = 8350 * 0.10 + (33950 - 8350) * 0.15 +
(82250 - 33950) * 0.25 + (income - 82250) * 0.28;
else if (income <= 372950)
tax = 8350 * 0.10 + (33950 - 8350) * 0.15 +
(82250 - 33950) * 0.25 + (171550 - 82250) * 0.28 +
(income - 171550) * 0.35;
else
tax = 8350 * 0.10 + (33950 - 8350) * 0.15 +
(82250 - 33950) * 0.25 + (171550 - 82250) * 0.28 +
(372950 - 171550) * 0.33 + (income - 372950) * 0.35;
}
else if (status == 1) { // Compute tax for married file jointly
// Left as exercise
}
else if (status == 2) { // Compute tax for married separately
// Left as exercise
}
else if (status == 3) { // Compute tax for head of household
// Left as exercise
}
else {
System.out.println("Error: invalid status");
System.exit(0);
}

// Display the result


System.out.println("Tax is " + (int)(tax * 100) / 100.0);
}
}

(0-single filer, 1-married jointly,


2-married separately, 3-head of household)
Enter the filing status: 0
Enter the taxable income: 40000
Tax is 6187.5

CMPS161 Class Notes (Chap 03) Page 15 /24 Kuo-pao Yang


3.12 Logical Operators

• Logical operators, also known as Boolean operators, operate on Boolean values to


create a new Boolean value.

TABLE 3.3 Boolean Operators


Operator Name Description
! not logical negation
&& and logical conjunction
|| or logical disjunction
^ exclusive or logical exclusion

• Examples
&& (and) (1 < x) && (x < 100)
|| (or) (lightsOn) || (isDayTime)
! (not) !(isStopped)

TABLE 3.4 Truth Table for Operator !

p !p Example
true false !(1 > 2) is true, because (1 > 2) is false.
false true !(1 > 0) is false, because (1 > 0) is true.

TABLE 3.5 Truth Table for Operator &&

p1 p2 p1 && p2 Example

false false false (2 > 3) && (5 > 5) is false, because either (2 > 3)
and (5 > 5) is false.
false true false
(3 > 2) && (5 > 5) is false, because (5 > 5) is false.
true false false
true true true (3 > 2 && (5>= 5) is true, b/c (3 > 2) and (5 >= 5)
are both true.

TABLE 3.6 Truth Table for Operator ||

p1 p2 p1 || p2 Example

false false false (2 > 3) || (5 > 5) is false, because (2 > 3)


and (5 > 5) are both false.
false true true
true false true (3 > 2) || (5 > 5) is true, because (3 > 2)
is true.
true true true

CMPS161 Class Notes (Chap 03) Page 16 /24 Kuo-pao Yang


TABLE 3.7 Truth Table for Operator ^
p1 p2 p1 ^ p2
Example
false false false (2 > 3) ^ (5 > 1) is true, because (2 > 3)
false true true is false and (5 > 1) is true.
true false true (3 > 2) ^ (5 > 1) is false, because both (3
true true false > 2) and (5 > 1) are true.

• LISTING 3.7 TestBooleanOperators.java

import java.util.Scanner;

public class TestBooleanOperators {


public static void main(String[] args) {
// Create a Scanner
Scanner input = new Scanner(System.in);

// Receive an input
System.out.print("Enter an integer: ");
int number = input.nextInt();

System.out.println("Is " + number + " divisible by 2 and 3? " +


((number % 2 == 0) && (number % 3 == 0)));

System.out.println("Is " + number + " divisible by 2 or 3? " +


((number % 2 == 0) || (number % 3 == 0)));

System.out.println("Is " + number +


" divisible by 2 or 3, but not both? " +
((number % 2 == 0) ^ (number % 3 == 0)));
}
}

Enter an integer: 18
Is 18 divisible by 2 and 3? true
Is 18 divisible by 2 or 3? true
Is 18 divisible by 2 or 3, but not both? false

CMPS161 Class Notes (Chap 03) Page 17 /24 Kuo-pao Yang


3.13 Problem: Determining Leap Year

• This program first prompts the user to enter a year as an int value and checks if it is a
leap year.
• A year is a leap year if it is divisible by 4 but not by 100, or it is divisible by 400.

(year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)

• LISTING 3.8 LeapYear.java

import java.util.Scanner;

public class LeapYear {


public static void main(String args[]) {
// Create a Scanner
Scanner input = new Scanner(System.in);
System.out.print("Enter a year: ");
int year = input.nextInt();

// Check if the year is a leap year


boolean isLeapYear =
(year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);

// Display the result in a message dialog box


System.out.println(year + " is a leap year? " + isLeapYear);
}
}

Enter a year: 2008


2008 is a leap year? true

Enter a year: 2002


2002 is a leap year? false

CMPS161 Class Notes (Chap 03) Page 18 /24 Kuo-pao Yang


3.14 Problem: Lottery

• Write a program that randomly generates a lottery of a two-digit number, prompts the
user to enter a two-digit number, and determines whether the user wins according to
the following rule:
o If the user input matches the lottery in exact order, the award is $10,000.
o If the user input match all the digits in the lottery, the award is $3,000.
o If one digit in the user input matches a digit in the lottery, the award is $1,000.

• LISTING 3.9 LeapYear.java


import java.util.Scanner;

public class Lottery {


public static void main(String[] args) {
// Generate a lottery
int lottery = (int)(Math.random() * 100);

// Prompt the user to enter a guess


Scanner input = new Scanner(System.in);
System.out.print("Enter your lottery pick (two digits): ");
int guess = input.nextInt();

// Get digits from lottery


int lotteryDigit1 = lottery / 10;
int lotteryDigit2 = lottery % 10;

// Get digits from guess


int guessDigit1 = guess / 10;
int guessDigit2 = guess % 10;

System.out.println("The lottery number is " + lottery);

// Check the guess


if (guess == lottery)
System.out.println("Exact match: you win $10,000");
else if (guessDigit2 == lotteryDigit1
&& guessDigit1 == lotteryDigit2)
System.out.println("Match all digits: you win $3,000");
else if (guessDigit1 == lotteryDigit1
|| guessDigit1 == lotteryDigit2
|| guessDigit2 == lotteryDigit1
|| guessDigit2 == lotteryDigit2)
System.out.println("Match one digit: you win $1,000");
else
System.out.println("Sorry, no match");
}
}

Enter your lottery pick (two digits): 45


The lottery number is 12
Sorry, no match

Enter your lottery pick (two digits): 23


The lottery number is 34
Match one digit: you win $1,000

CMPS161 Class Notes (Chap 03) Page 19 /24 Kuo-pao Yang


3.15 switch Statements

• One can write a switch statement to replace a nested if statement. For example,

switch (status) {
case 0: compute taxes for single filers;
break;
case 1: compute taxes for married file jointly;
break;
case 2: compute taxes for married file separately;
break;
case 3: compute taxes for head of household;
break;
default: System.out.println("Errors: invalid status");
System.exit(0);
} // checks if status matches the values 0, 1, 2, or 3 respectively.

status is 0
Compute tax for single filers break

status is 1
Compute tax for married file jointly break

status is 2
Compute tax for married file separatly break

status is 3
Compute tax for head of household break

default
Default actions

Next Statement

FIGURE 3.5 The switch statement checks all cases and executes the statement in
matched cases

The switch Statement Rules:


• The switch-expression must yield a value of char, byte, short, or int type and must
always be enclosed in parentheses.
• The value1... and valueN must have the same data type as the value of the switch-
expression. value1... and valueN are constant expressions, meaning that they cannot
contain variables in the expression, such as 1 + x.
• When the value in a case statement matches the value of the switch-expression, the
statements starting from this case are executed until either a break statement or the
end of the switch statement is reached.

CMPS161 Class Notes (Chap 03) Page 20 /24 Kuo-pao Yang


• The keyword break is optional. The break statement immediately ends the switch
statement.
• The default case, which is optional, can be used to perform actions when none of
the specified cases matches the switch-expression.
• The cases statements are checked in sequential order, but the order of the cases
(including the default case) does not matter. However, it is a good programming style
to follow the logical sequence of the cases and place the default case at the end.

Caution
• Do not forget to use a break statement when one is needed. For example, the
following code prints character a three times if ch is ‘a’:

switch (ch) {
case ‘a’: System.out.println(ch);
case ‘b’: System.out.println(ch);
case ‘c’: System.out.println(ch);
}

CMPS161 Class Notes (Chap 03) Page 21 /24 Kuo-pao Yang


3.16 Conditional Expressions

• Conditional expressions are in different style, which no explicit if in the statement.


The syntax is shown below:

BooleanExpression ? exprssion1 : exprssion2;

The result of this conditional expression expression1 if BooleanExpression is true;


otherwise the result is expression2.
• For example:
if (x > 0)
y = 1
else
y = -1;

is equivalent to

y = (x > 0) ? 1 : -1;

• For example:
if (num % 2 == 0)
System.out.println(num + “is even”);
else
System.out.println(num + “is odd”);

is equivalent to
System.out.println((num % 2 == 0)? num + “is even” : num + “is
odd”);

• For example:
Max = (num1 > num2)? num1 : num2;

Note
• The symbols ? and : appear together in a conditional expression. They form a
condition operator. The operator is called a ternary operator because it uses three
operands.

CMPS161 Class Notes (Chap 03) Page 22 /24 Kuo-pao Yang


3.17 Formatting Console Output

• Use printf statement to format the output.


System.out.printf(format, item);

Where format is a string that may consist of substrings and format specifiers.
A format specifier specifies how an item should be displayed.
An item may be a numeric value, character, boolean value, or a string. Each specifier
begins with a percent sign.

TABLE 3.8 Frequently Used Specifiers


Specifier Output Example
%b a boolean value true or false
%c a character 'a'
%d a decimal integer 200
%f a floating-point number 45.460000
%e a number in standard scientific notation 4.556000e+01
%s a string "Java is cool"
int count = 5;
double amount = 45.56;
System.out.printf("count is %2d %4.2f", count, amount);

displays
count is 5 45.56

• Items must match the specifiers in order, on number, and in exact type. By default, a
floating-point value is displayed with 6 digits after the decimal points.

int count = 5;
items
double amount = 45.56;
System.out.printf("count is %d and amount is %f", count, amount);

display count is 5 and amount is 45.560000

• Creating Formatted Strings

String.format(format, item1, item2, ..., itemk)

• Example

String s = String.format("count is %d and amount is %f", 5, 45.56));

CMPS161 Class Notes (Chap 03) Page 23 /24 Kuo-pao Yang


3.18 Operator Precedence and Associativity
How to evaluate?

3 + 4 * 4 > 5 * (4 + 3) - 1

• The precedence rule defines precedence for operators as shown below.


• If operators with the same precedence are next to each other, their associativity
determines the order of evaluation.
• All binary operators except assignment operators are left-associative. For example:

a – b + c – d is equivalent to ((a – b) + c) – d

Assignment operators are right-associative. Therefore, the expression

a = b += c = 5 is equivalent to a = (b += (c = 5))

TABLE 3.10 Operator Precedence Chart


var++, var--
+, - (Unary plus and minus), ++var,--var
(type) Casting
! (Not)
*, /, % (Multiplication, division, and modulus)
+, - (Binary addition and subtraction)
<, <=, >, >= (Comparison)
==,!= (Equality)
& (Unconditional AND)
^ (Exclusive OR)
| (Unconditional OR)
&& (Conditional AND) Short-circuit AND
|| (Conditional OR) Short-circuit OR
=, +=, -=, *=, /=, %= (Assignment operator)

• Example
Applying the operator precedence and associativity rule, the expression 3 + 4 * 4 > 5
* (4 + 3) - 1 is evaluated as follows:

3 + 4 * 4 > 5 * (4 + 3) - 1
(1) inside parentheses first
3 + 4 * 4 > 5 * 7 – 1
(2) multiplication
3 + 16 > 5 * 7 – 1
(3) multiplication
3 + 16 > 35 – 1
(4) addition
19 > 35 – 1
(5) subtraction
19 > 34
(6) greater than
false

CMPS161 Class Notes (Chap 03) Page 24 /24 Kuo-pao Yang

You might also like