The Department of Computer Science & Engineering
cse@buffalo
STUART C. SHAPIRO: CSE 115 C

CSE 115
Introduction To Computer Science for Majors I
Lecture C
Lecture Notes
Stuart C. Shapiro
Spring, 2001


Conditionals

Reading
Brown U. Notes, Chapter 8
Barnes, Chapter 6

If you have set of basic operations/actions/behaviors, how can you combine them to make a more complex operation/action/behavior?

According to a theorem proved by Corrado Böhm and Giuseppe Jacopini (CACM, 1966), all you need is:

  1. Sequence: Do one action, and then another, and then another, etc.
  2. Selection: Do one action or another, based on some condition.
  3. Loop: Repeatedly do an action as long as some condition holds.

Sequence
You have already written methods that consist of a sequence of statements. They are executed in the order they appear in the program.

A block is a sequence of statements surrounded by braces (curly brackets), { ... }.
Anywhere a statement is legal, a block may be used.

Selection (Conditionals)
A conditional statement in Java is
     if (condition) statement1
     [else statement2]
(Remember, either statement could be a block.)

condition is a Java expression that evaluates to a boolean value (true or false).

If the condition evaluates to true, statement1 is executed.
If the condition evaluates to false, statement1 is not executed, and if the else clause is present, statement2 is executed.

A conditional expression in Java is
     (condition ? expression1 : expression2)
The parentheses are optional.

If the condition evaluates to true, the conditional expression evaluates to the value of expression1.
If the condition evaluates to false, the conditional expression evaluates to the value of expression2.

boolean is a Java primitive (base) type like int and double.
It has only two values, true and false.

boolean operators:

not:

p!p
truefalse
falsetrue

and, or, exclusive or, equivalent, not equivalent:

pqp && qp || qp ^ qp == qp != q
truetruetruetruefalsetruefalse
truefalsefalsetruetruefalsetrue
falsetruefalsetruetruefalsetrue
falsefalsefalsefalsefalsetruefalse

Relational operators:
Operate on two numbers, evaluates to a boolean.

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

See Example code.

Switch Statement
Read about it in the readings.

First Previous Next

Copyright © 2001 by Stuart C. Shapiro. All rights reserved.

Stuart C. Shapiro <shapiro@cse.buffalo.edu>