0% found this document useful (0 votes)
46 views22 pages

CS 152 04 If - Statements

This document contains lecture notes on if and else if statements in Java from the CS 152 Computer Programming Fundamentals course. Key points include: - The if statement executes code only if a logical expression evaluates to true - An else if statement allows executing different code if the if statement's expression is false - It is not possible for both the if statement block and else block to execute in an if-else statement - An else statement ensures a variable is initialized even if none of the if or else if blocks execute

Uploaded by

CK
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)
46 views22 pages

CS 152 04 If - Statements

This document contains lecture notes on if and else if statements in Java from the CS 152 Computer Programming Fundamentals course. Key points include: - The if statement executes code only if a logical expression evaluates to true - An else if statement allows executing different code if the if statement's expression is false - It is not possible for both the if statement block and else block to execute in an if-else statement - An else statement ensures a variable is initialized even if none of the if or else if blocks execute

Uploaded by

CK
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/ 22

CS 152

Computer Programming
Fundamentals
The if-else Statement
Instructor:
Joel Castellanos
e-mail: [email protected]
Web: http://cs.unm.edu/~joel/
Office: Electrical and Computer
Engineering building (ECE).
Room 233

8/31/2017

Quiz:
public class Tmp
{

a)
public static void main(String[] args)
{

}
System.out.println("Pick Me");
Which is
}
the
public class Tmp
{
Correct
public static void main(String[] args) Formatting
b) {
System.out.println("No, Me"); in
}
} CS-152?
public class Tmp
{
public static void main(String[] args)
c) {
System.out.println("Ooh, Ooh");
}
2 }

1
Java Primitive Type: boolean

public class Toy_3_2


{
public static void main(String[] args)
{
boolean a = true;
boolean b = (5*(-5)) > 0;

System.out.println(a);
System.out.println(b);
}
}
Output:
true
false
3

Logical Expressions
1. public class Hello
2. { public static void main(String[] args)
3. {
4. int a = 1; int b = 3;
5. System.out.println( a+b + 14 );
6. System.out.println( a+b < 14 );
7. System.out.println( a+b > 14 );
8. System.out.println( a+b <= a*b );
9. System.out.println( a+b > a*b );
10. } Output: 18
11. } true
false
false
true
4

2
Logical Expressions
1. public class Hello
2. { public static void main(String[] args)
3. {
4. int a = 3;
5. int b = 5;
6. int c = 7;
7. System.out.println( c > a && c > b );
8. System.out.println( b > a && b > c );
9. System.out.println( b > c && b > a );
10. System.out.println( b > a || b > c );
11. }
12. } Output: true
false
false
5 true

Using a boolean Variable to hold Results


1) public class Hello
2) { public static void main(String[] args)
3) { Output: false
4) int a = -3; false
5) int b = 9; true
6) int c = 5;
7) System.out.println((a+b>c) && (a*b>c));
8)
9) boolean r1 = a+b > c; //true
10) boolean r2 = a*b > c; //false
11) System.out.println( r1 && r2 );
12) System.out.println( r1 || r2 );
13) }
14)}
6

3
Quiz: Logical Expressions
What is the output of the println statement?
int a = 3;
int b = 5;
int c = 7;
System.out.println( (b < a && b < c)
+ " " + (b < a || b < c)
+ " " + (b > c || a > c) );
a) false true false
b) false false true
c) true false false
d) false true true
7
e) true true false

Quiz: Logical Expressions


What is the output of the println statement?
int a = 3;
int b = 5;
int c = 11;
System.out.println(
(a+b > c && a*b > c) + " " +
(a+b > c || a*b > c) + " " +
(a+b < c || a*b < c));
a) false true false
b) false false true
c) true false false
d) false true true
8
e) true true false

4
The if Statement
The if statement tells your program to execute a certain
section of code only if a particular test evaluates to true.
if (grade >= 90) System.out.println("Cash Award");

Logical One statement or one block { }.


expression Executed only if logical
expression is true
When the “then” part is more than one statement, brackets
are needed.
if (grade >= 90)
{ System.out.println("Cash Award");
cash = cash + 100.0;
9
}

if-else Statement Flow Chart


1) if (balance >= 0)
2) { balance = balance + (INTEREST * balance)/12;
3) }
4) else
5) { balance = balance - OVERDRAWN_PENALTY;
6) }
Start

balance >= 0
true false

balance = balance + balance = balance -


(INTEREST * balance)/12; OVERDRAWN_PENALTY;
10

5
Quiz: Identifiers in All Caps
public class BankBalance
{
public static final double OVERDRAWN_PENALTY = 8.00;
public static final double INTEREST_RATE = 0.02;

public static void main(String[] args)


{
In the code segment from listing 3.1 shown above,
OVERDRAWN_PENALTY and INTEREST_RATE in are in all caps:
a) because they are outside main, and, therefore the code would
not actually compile.
b) because they are declared static.
c) because they are declared final.
d) because they are global class variables.
11 e) because later they are used in different branches of an if.

if and else Statements

1) public class Toy_3_1


2) {
3) public static void main(String[] args)
4) {
5) int x = 5;
6)
Logical "is equal to" Operator
7)
8) if (x == (2+3)) x = x + 10;
9) else x = x * 2;
10)
Assignment Operator
11)
12) System.out.println(x);
13) }
14)} Output: 15
12

6
if and else Statements
Either statement 2 or statement 5 will execute.
It is impossible for both to execute.
1) if (testscore >= 90)
2) { System.out.println("Great Job!");
3) }
4) else
5) { System.out.println("Work Harder");
6) }
Since the “then” part is only one statement,
curly brackets are not needed.
However, when the code does not fit on a
single line, the CS-259 coding standard dictates
that the curly brackets be used.
13

if, else if, else


1) public class HelloWorld
2) { public static void main(String[] args)
3) {
4) int x = 1;
5)
6) if (x == 1) ¡¡¡No semicolon!!!
7) { System.out.println("x is 1");
8) }
9) else if (x == 2) ¡¡¡No semicolon!!!
10) { System.out.println("x is 2");
11) }
12) else ¡¡¡No semicolon!!!
13) { System.out.println("x is special");
14) }
14 15) }
16)}

7
Use of else if
1) public class HelloWorld
2) { public static void main(String[] args)
3) { int testscore = 76;
4) char grade = 'F';
5)
6) if (testscore >= 90) grade = 'A';
7) else if (testscore >= 80) grade = 'B';
8) else if (testscore >= 70) grade = 'C';
9) else if (testscore >= 60) grade = 'D';
10)
11) System.out.println("Grade = " + grade);
12) }
13)}
With testscore = 76, the logical expressions in
lines 8 and 9 would both evaluate to true.
15 However, since 8 is true, execution never reaches 9.

Find the Syntax Error


1) public class HelloWorld
2) { public static void main(String[] args)
3) { int testscore = 76;
4) char grade;
5)
6) if (testscore >= 90) grade = 'A';
7) else if (testscore >= 80) grade = 'B';
8) else if (testscore >= 70) grade = 'C';
9) else if (testscore >= 60) grade = 'D';
10)
11) System.out.println("Grade = " + grade);
12) }
13)}

Local variable grade may not have been initialized.


16

8
else: Ensuring grade is Initialized
1) public class HelloWorld
2) { public static void main(String[] args)
3) { int testscore = 76;
4) char grade;
5)
6) if (testscore >= 90) grade = 'A';
7) else if (testscore >= 80) grade = 'B';
8) else if (testscore >= 70) grade = 'C';
9) else if (testscore >= 60) grade = 'D';
10) else grade = 'F';
11) System.out.println("Grade = " + grade);
12) }
13)}
The compiler recognizes there is no path to line
11 in which grade is not initialized.
17

Quiz: if and else if


1) int testscore = 88;
2) char grade = 'F';
3)
4) if (testscore >= 60) grade = 'D';
5) else if (testscore >= 70) grade = 'C';
6) else if (testscore >= 80) grade = 'B';
7) else if (testscore >= 90) grade = 'A';
8)
9) System.out.println(grade);

What would be the output of the above Java code?


a) B b) D c) F d) FB e) FDCB

18

9
Control Flow and Program State
1) public class HelloWorld
2) { public static void main(String[] args)
3) { int x = 5;
4) int a = 0; start x a
5) if (x < 10) a=1; of line
6) if (x < 6) a=2; line 3
7) if (x < 1) a=3; line 4 5
8) System.out.println(a); line 5 5 0
9) } line 6 5 1
10)} line 7 5 2
line 8 5 2
Table of program state at the
Output:
start of each line in the order of
2
execution.
19

Control Flow and Program State


1) public static void main(String[] args)
2) { int x = 5;
3) int a = 0; start x a
of line
4) if (x < 10)
line 2
5) { a=1;
6) } line 3 5
7) if (x < 6) line 4 5 0
8) { a=2; line 5 5 0
9) } line 7 5 1
10) if (x < 1) line 8 5 1
11) { a=3; line 10 5 2
12) } line 13 5 2
13) System.out.println(a);
Output:
14)}
2
20

10
Control Flow: if & else if
1) public static void main(String[] args)
2) { int x = 5;
3) int a = 0; start x a
4) if (x < 10) of line
5) { a=1; 2)
6) } 3) 5
7) else if (x < 6)
4) 5 0
8) { a=2;
5) 5 0
9) }
13) 5 1
10) else if (x < 1)
11) { a=3;
12) }
13) System.out.println(a);
Output:
14)}
1
21

Quiz: if, else if, else


1) public static void main(String[] args)
2) {
3) int x = 1;
4)
5) if (x == 1)
6) { System.out.println("x is 1"); Look carefully
7) } This code does
8) else if (x == 2) not do what it was
9) { System.out.println("x is 2"); probably intended
10) } to do.
11) else x = 3;
12) { System.out.println("wild: x=" + x);
13) }
14) }
The output is:
a) x is 1 b) x is 1 c) x is 2 d) wild: x=1 e) wild: x=3
wild: x=1
22

11
if, else if, else
1) public static void main(String[] args)
2) {
3) int x = 4; Only Change
4)
5) if (x == 1)
6) { System.out.println("x is 1");
7) }
8) else if (x == 2)
9) { System.out.println("x is 2");
10) }
11) else x = 3;
12) { System.out.println("x is " + x);
13) }
14) } Output: x is 3
23

Example: if, else if, else


1) int x=3, y=7;
2) if (x*x < x+y)
Output:
3) { System.out.print("B");
4) } BES
5) if (x > 0)
6) { System.out.print("E");
7) }
8) else if (y > 0)
9) { System.out.print("A");
10) }
11) else
12) { System.out.print("T");
13) }
14) if (x*y > 0)
15) { System.out.print("S");
24 16) }

12
Quiz: if & else if
1) public static void main(String[] args)
2) {
3) int x = 50;
4) if (x > 20)
5) { System.out.print("A");
6) }
7) else if (x > 30)
8) { System.out.print("B");
9) }
10) else if (x > 40)
11) { System.out.print("C");
12) }
13) System.out.println("D");
14) }

The output is:


a) ABCD b) ABD c) CD d) C e) AD
25

Quiz: if, else if


1) int a = 3, b = 4, c = 5;
2)
3) if (a+b > c) System.out.print("A");
4)
5) else if (a*b > c) System.out.print("B");
6)
7) if (a*a > c) System.out.print("C");
8)
9) else if (b*b > c) System.out.print("D");
10)
11) else if (b*b >= c*a) System.out.print("E");
12)
13) System.out.println("F");

The output of this Java code segment is:


a) AF b) ACF c) ABCF d) ACDF e) ACDEF
26

13
Logical Operators
== Equals
!= Not Equal
< Less than
> Grater than
<= Less than or Equal to
>= Greater than or Equal to
|| Logical OR The bitwise operators are not
covered in CS-259.
&& Logical AND | bitwise OR
! Logical NOT & bitwise AND
^ bitwise exclusive OR
~ bitwise NOT
27

Truth Tables for AND, OR and NOT


1) public class TruthTables
2) {
3) public static void main(String[] args)
4) {
5) System.out.println( true && true ); true
6) System.out.println( true && false ); false
7) System.out.println( false && true); false
8) System.out.println( false && false ); false
9)
10) System.out.println( true || true ); true
11) System.out.println( true || false ); true
12) System.out.println( false || true ); true
13) System.out.println( false || false ); false
14)
15) System.out.println(!true); false
16) System.out.println(!false); true
17) }
28 18)}

14
The Logical AND Operator: &&
true when both parts are true

1) if ((pressure >= min) && (pressure <= max))


2) { System.out.println("Pressure is OK");
3) }
4) else
5) { System.out.println(
6) "Warning: Pressure is out of range.");
7) }
The order of operations, in Java, makes these equivalent:
if ((pressure >= min) && (pressure <= max))
if ( pressure >= min && pressure <= max )
29

The Logical AND Operator: ||

true when both parts are true


true when either part is true

1) if ((pressure < min ) || (pressure > max ))


2) { System.out.println(
3) "Warning: Pressure is out of range.");
4) }
5) else
6) { System.out.println("Pressure is OK");
7) }

30

15
What Happens on Line 4?
1) public class TruthTable
2) { public static void main(String[] args)
3) {
4) System.out.println(xor(true, true)); false
5) System.out.println(xor(true, false));
6) System.out.println(xor(false, true));
7) System.out.println(xor(false, false));
8) }
9)
10) public static boolean xor(boolean a, boolean b)
11) {
12) return ( a || b) && !(a && b); Truth Table for
13) } Exclusive OR
( T || T) && !(T && T)
14) } T T = F
( T ) && !( T )
T F = T
T && F
F T = T
F
F F = F
31

Trace of What Happens on Line 5


1) public class TruthTable
2) { public static void main(String[] args)
3) {
4) System.out.println(xor(true, true));
5) System.out.println(xor(true, false)); true
6) System.out.println(xor(false, true));
7) System.out.println(xor(false, false));
8) }
9)
10) public static boolean xor(boolean a, boolean b)
11) {
12) return ( a || b) && !(a && b); Truth Table for
13) } Exclusive OR
( T || F) && !(T && F)
14) } T T = F
( T ) && !( F )
T F = T
T && T
F T = T
T
F F = F
32

16
Which of the if statements have
identical truth tables?
1) public class TruthTable
2) { public static void main(String[] args)
3) {
4) foo(true,true); CAT DOG
5) foo(true,false); CAT BAT DOG
6) foo(false,true); CAT BAT DOG
7) foo(false,false); ANT BAT
8) }
9)
10) public static void foo(boolean a, boolean b)
11) {
12) if ( a || b) System.out.print("CAT ");
13) if ( !a && !b) System.out.print("ANT ");
14) if (!( a && b)) System.out.print("BAT ");
15) if (!(!a && !b)) System.out.print("DOG ");
16) System.out.println();
17) }
33 18)}

“Short circuit” Evaluation


What is meant by “this expression is safe”.
if (x != 0.0 && 1.0/x > x + y)

exp1 exp2

The expression: (exp1 && exp2)


can only be true if both exp1 and exp2 are true.
Thus, if exp1 is false, Java does not evaluate exp2.
Thus, if x = 0, then 1.0/x is not evaluated.
34

17
Order of Evaluation

double x = 2.0;
double y = -2.0;
if (x != 0.0 && 1.0/x > x + y)
1) x != 0.0
2) 1.0/x
3) x + y

4) 0.5 > 0.0

5) true && true

35
6) true

Comparing Strings
1) String myColor = "red"
2) System.out.println(myColor);
3) System.out.println(myColor == "red");
4) System.out.println(myColor.equals("red"));

?
36

18
Comparing Addresses verses Strings
String myColor;
//Some code that puts data in myColor.

myColor == "red"
true if and only if the memory location of
myColor is the same as the memory location
of "red"

myColor.equals("red")
true if and only if the data in myColor is "red" .
37

Possible Null Pointer Exception


1) String str = JOptionPane.showInputDialog(null,
2) "Enter red");
3) if (str.equals(""))
4) { System.out.println("Clicked OK with no data");
5) }
6) if (str == null)
7) { System.out.println("Clicked Cancel");
8) }

A Null Pointer Exception occurs when code attempts to access a


member of an object using an object reference that is not pointing
anywhere.

In line 3, equals is a method that is a member of a String object.

However, if str is null, then, even though str was declared as being a
reference to a String object, it doesn't, in fact, point to anything.
38

19
Does This Fix the Problem?
1) String str = JOptionPane.showInputDialog(null,
2) "Enter red");
3) if (str == null)
4) { System.out.println("Clicked Cancel");
5) }
6) if (str.equals(""))
7) { System.out.println("Clicked OK with no data");
8) }

39

Checking Input: All Golden


1) String str = JOptionPane.showInputDialog(
2) null, "Enter red");
3) if (str == null)
4) { System.out.println("Clicked Cancel");
5) }
6) else if (str.equals(""))
7) { System.out.println("OK with no data");
8) }

1) String str = JOptionPane.showInputDialog(


2) null, "Enter red");
3) if (str == null)
4) { System.out.println("Clicked Cancel");
5) System.exit(0);
6) }
7) if (str.equals(""))
8) { System.out.println("OK with no data");
40 9) }

20
How can this be coded in Java?
 Let X be a course with 3 grades: a midterm, a final exam
and a final project. Each counts as 1/3 of the course grade.
Example: t1=90, t2=70, p=80  grade = 80.0

 However, if a student does better on the final than on the


midterm, then the final is counted with twice the weight as
the midterm.
Example: t1=0, t2=90, p=90  grade = 70.0

 A student who gets a 95% or more on the final project can


drop his or her final exam score and count the final project
as 2/3 and the midterm as 1/3 of the course grade.
Example: t1=90, t2=0, p=90  grade = 90.0

41

Example Calculation: Count Final 2x Midterm

Case 1 grade = (t1 + t2 + p)/3

Paper & Pencil


Given:
before code!
grade = (w)t1 + (2w)t2 + (1/3)p
w + 2w + 1/3 = 1

Case 2
w + 2w = 2/3
Counting t2
with twice the 3w = 2/3
weight as t1 w = 2/9
grade = (2/9)t1 + (4/9)t2 + (1/3)p
42

21
Java Code for Conditional Grade
1) Scanner in = new Scanner(System.in);
2) double t1 = in.nextDouble(); Could or
3) double t2 = in.nextDouble(); Should the
4) double p = in.nextDouble(); order of the
5) two if
6) double grade = (t1 + t2 + p) / 3.0; statements
7) be switched?
8) if (t2 > t1)
9) { grade = t1*(2.0/9.0) + t2*(4.0/9.0) + p/3.0;
10) }
Could or Should this be changed to else if?
11)
12) if (p >= 95)
13) { double tmp = (t1/3.0) + (p*2.0/3.0);
14) if ( tmp > grade) grade = tmp;
15) }
43
16) System.out.println("Grade="+grade);

22

You might also like