0% found this document useful (0 votes)
5 views40 pages

Slides 3 - If Statements, Relations, Logical Operators

The document covers fundamental concepts of control flow in Java, including sequence, conditional statements (if, if-else, switch), and repetition statements (loops). It explains the syntax and logic of if statements, relational operators, and logical operators, along with examples to illustrate their usage. Additionally, it discusses the importance of flowcharts, string comparisons, and precedence rules in programming.
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)
5 views40 pages

Slides 3 - If Statements, Relations, Logical Operators

The document covers fundamental concepts of control flow in Java, including sequence, conditional statements (if, if-else, switch), and repetition statements (loops). It explains the syntax and logic of if statements, relational operators, and logical operators, along with examples to illustrate their usage. Additionally, it discusses the importance of flowcharts, string comparisons, and precedence rules in programming.
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/ 40

COMP 248:

OBJECT ORIENTED PROGRAMMING I

If statements, Relations, Logical Operators

The content on these slides was provided by Dr.


Nora Houari.
Flow of Control

1. Sequence:
• Unless specified otherwise, the order of statement execution is linear/sequential
• one statement after the other, in sequence
2. Conditional statements:
• a statement may or may not be executed depending on some condition

3. Repetition statements (loops):


• a statement is executed over and over, repetitively, until some condition becomes true
or false

§ These decisions are based on a boolean expression (also called a condition)


that evaluates to true or false
§ The order of statement execution is called the flow of control

n 2
Contents

1. The if statement
2. The if-else statement
3. Relations Operators
4. Logical operators

n 3
Conditional statements

§ let us choose which statement will be executed next


§ sometimes called selection statements

§ Java has 3 conditional statements:


ü the if statement
ü the if-else statement
ü the switch statement

n 4
Flowchart

A flowchart is a graphical way of representing an algorithm


Use the following symbols:

Assignment Start/end

Input/Output Flow control

Decision Connector
n 5
1- The if statement

§ syntax:
The condition is a boolean expression.
if is a Java (evaluates to either true or false)
reserved word

if ( condition )
statement;

If the condition is true, the statement is executed.


If it is false, the statement is skipped.

n 6
Logic of an if statement

condition
evaluated

true false

statement

n 7
Example: Age.java

System.out.print("Enter the sum: ");


int sum = myKeyboard.nextInt();
int delta = 0;

if (sum >= 100)


delta = 5;

System.out.println("Delta is " + delta);


Output

n 8
Example: Age.java

final int MINOR = 18;


System.out.print("Enter your age: ");
int age = myKeyboard.nextInt();

if (age < MINOR)


System.out.println("wonderful");
System.out.println("Oh well!");

Output

n 9
2- The if-else statement
§ An else clause can be added to an if statement to
make an if-else statement

if ( condition )
statement1;
else
statement2;

n If the condition is true, statement1 is executed


n If the condition is false, statement2 is executed
n One or the other will be executed, but not both

n 10
Logic of an if-else statement

condition
evaluated

true false

statement1 statement2

n 11
Example: Wages.java
final double RATE = 10.0; // regular pay rate
final int STANDARD = 40; // standard hours
double pay = 0;
System.out.print("Number of hours worked: ");
int hours = myKeyboard.nextInt();

// Pay overtime at "time and a half“


if (hours > STANDARD)
pay = STANDARD*RATE + (hours-STANDARD) * (RATE*1.5);
else
pay = hours * RATE;
System.out.println("Pay: " + pay);
Output

n 12
What is output?
int speed = 25;

if (speed > 50)

System.out.println(″Going too fast – School zone″);

if (speed > 30)

System.out.println(″Going at the right speed″);

else

System.out.println(″You can go a bit faster″);

Output
n 13
What is output?

int speed = 55;


if (speed > 50)
System.out.println(″Going too fast – School zone″);
if (speed > 30)
System.out.println(″Going at the right speed″);
else
System.out.println(″You can go a bit faster″);

A. Going too fast – School zone

B. Going at the right speed

C. You can go a bit faster

D. Neither of the above choices

n 14
What is output?

A. line A
int num = 4;
line B
if (num > 5) line C
System.out.println("line A"); line D

else B. line A
line C
System.out.println("line B"); line D
if (num < 10) C. line B
System.out.println("line C"); line C
System.out.println("line D"); line D
D. line B
line C
See how much harder it is to read if not indented
properly … E. line B
line D
n 15
What is output?

int someInt = 10; 1. Curly


if (someInt > 30) 2. Larry Curly
System.out.println("Moe ");
3. Moe
System.out.print("Larry ") Larry Curly
System.out.print("Curly");
4. no output; there is
a compile-time
error
5. no output; there is
a run-time error

n 16
What is output?

int someInt = 10; 1. Curly


if (someInt > 30) 2. Larry Curly
System.out.println("Moe ");
3. Moe
System.out.print("Larry "); Larry Curly
System.out.print("Curly");
4. no output; there
is a compile-time
error
5. no output; there
is a run-time
error
n 17
3- Relational operators

§ needed in control structures (ex. if)


§ to write conditions (boolean expressions)
§ return boolean results (evaluates to true or false)

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

Note the difference between == and = n 18


Example - IncomeTax.java

if (age == 18)
System.out.println("you are 18");
else
System.out.println("you are not 18");
Output

if (age = 18)
System.out.println("you are 18");
else
System.out.println("you are not 18");
Output

n 19
A note on comparing floats

§ be careful when comparing 2 floating point values


(float or double) for equality
§ do not use the equality operator (==)
§ because floats are approximated
§ you want to see if two floats are "close enough"

if (Math.abs(f1 - f2) < 0.00001)


System.out.println ("Essentially equal.");

n 20
Part of the Unicode Character Set (ASCII)

n 21
A note on comparing characters

§ We can use the relational operators to compare 2 characters


§ The results are based on the Unicode character set

if ('+' < 'J')


System.out.println("+ is less than J in Unicode");

char userAnswer = 'n';


if (userAnswer == 'N')
System.out.println("the user said no");

n 22
A note on comparing strings

§ We cannot use the relational operators to compare


strings (<, ==, …)

§ use the equals() method


• to determine if two strings have the same content

• ex: firstString.equals(secondString)

• returns a boolean:
o true if firstString has the same content as
secondString
o false otherwise

n 23
A note on comparing strings

§ use the compareTo() method


• to determine if one string comes before another (based on the
Unicode character set)

• ex: firstString.compareTo(secondString)returns an int:

o negative if firstString is lexicographically before


secondString
o positive if firstString is lexicographically after
secondString
o 0 if the 2 strings have the same content

n 24
Example 1 StringComparison.java

String s1 = "Java isn't just for breakfast.";


String s2 = "JAVA isn't just for breakfast.";

if (s1.equals(s2))
System.out.println("The two lines are equal.");
else
System.out.println("The two lines are not equal.");

if (s2.equals(s1))
System.out.println("The two lines are equal.");
else
System.out.println("The two lines are not equal.");
n 25
Example 1 StringComparison.java

String s1 = "Java isn't just for breakfast.";


String s2 = "JAVA isn't just for breakfast.";

if (s1.equalsIgnoreCase(s2))
System.out.println("But the lines are equal, "
+ " ignoring case.");
else
System.out.println("Lines are not equal, "
+ " even ignoring case.");

n 26
Example 2
Syntax Output?
Error?

System.out.println("aBcD" < "abcd");

System.out.println('aBcD' < 'abcd');

System.out.println("a" < "b");

System.out.println('a' < 'b');

System.out.println("aBcD".equals("abcd"));

n 27
Example 2 …

Syntax Output?
Error?
System.out.println("aBcD".equalsIgnoreCase("aBcD"));

System.out.println("aBcD".compareTo("aBcD"));

System.out.println("aBcD".compareTo("aBcC"));

System.out.println("abc".compareTo("ab"));

System.out.println("abc".compareTo("abcd"));

n 28
4- Logical operators

§ To combine multiple boolean expressions into a more complex


one
! Logical NOT (unary operator)
&& Logical AND (binary operator))
|| Logical OR (binary operator)
§ They all take boolean operands and produce boolean results
a !a
§ !a is false if a is true
§ !a is true if a is false true

false

n 29
4- Logical operators

§ a && b is true only if both a and b are true


§ a && b is false if a or b or both are false

a b a && b

true true

true false

false true

false false

n 30
4- Logical operators

§ a || b is true if a or b or both are true


§ a || b is false if both a and b are false

a b a || b

true true
true false
false true
false false

n 31
Just checking …
When using a compound Boolean expression joined by an && (AND) in
an if statement:

A. Both expressions must evaluate to true for the statement to


execute.

B. The first expression must evaluate to true and the second


expression must evaluate to false for the statement to execute.

C. The first expression must evaluate to false and the second


expression must evaluate to true for the statement to execute.

D. Both expressions must evaluate to false for the statement to


execute.
n 32
Just checking …

If p is a Boolean variable, which of the following logical expressions


always has the value false?

A. p && p
B. p || p
C. p && !p
D. p || !p
E. b and d above

n 33
Precedence and Associativity Rules

§ Boolean and arithmetic expressions need not be fully parenthesized

§ If parentheses are omitted, Java follows precedence and


associativity rules to determine the order of operations
• If one operator has higher precedence
o it is grouped with its operands before the operator of lower
precedence
• If two operators have the same precedence
o then associativity rules determine which is grouped first

n 34
Precedence and Associativity Rules

Precedence Operator Associativity


highest (evaluated 1st) postfix ++, postfix -- right to left

unary +, unary -, prefix ++, prefix --, ! right to left


type casts
binary *, / % left to right
binary +, - left to right
binary >, <, >=, <= left to right

binary ==, != left to right

binary & left to right


binary | left to right
binary && left to right
binary || left to right
conditional operator ?: right to left
lowest (evaluated last) assignment operators: =, *= /=, %=, +=, -=, &=, |= right to left
n 35
By the way …

int a = 10;
int b = ++a++;
Which is the correct option?
A. a = 12 and b = 12
B. b = 12 and b = 11
C. Compiler error
D. Syntax error

n 36
Logical operators

if (total < MAX+5 && !found)


System.out.println ("Processing…");

if ((total < (MAX+5)) && (!found))


System.out.println ("Processing…");

Precedence:
q all logical operators have lower precedence than the relational
or arithmetic operators

q logical NOT has higher precedence than logical AND and logical
OR

n 37
Short-circuit evaluation

if (count!=0 && total/count > MAX)


System.out.println ("Testing…");

if (count!=0)is false… no point in evaluating (total/count>MAX)

if (isChild || height < 1.5)


System.out.println ("half price");
if (isChild) is true… no point in evaluating (height < 1.5)

§ The processing of logical AND and logical OR is “short-circuited”


§ also called lazy evaluation
§ If the left operand is sufficient to determine the result of the entire
condition, the right operand is not evaluated.
n 38
Just checking

Does the following sequence produce a division by zero?

int j = -1;
if ((j > 0) && (1/(j+1) > 10))
System.out.println(j);

A. Yes, this sequence produces a division by zero.


B. No, this sequence does not produce division by zero.
C. We have no way of knowing
D. No this sequence does not produce division by zero, because it has a
syntax error

n 39
Complete evaluation

§ To force both expressions to be evaluated


• use & instead of &&
• use | instead of ||

§ Rarely used …

n 40

You might also like