# Chapter 5

33 views5 pages
Published on 8 Jul 2011
School
Ryerson University
Department
Information Technology Management
Course
ITM 200
Chapter 5 – The “if-else statement
5.1 An exam-mark recording problem
If some students have been given their marks for an exam (out of 100) and need to know
whether they have passed (scored 40 or more)
You would have to write the following pseudoccode first
o1. Get the mark from the student
o2. IF it is greater than the pass mark, tell them they have passed
ELSE tell them they have failed
o3. Thank them for using the system
5.2 Boolean expressions
A Boolean expression is one which evaluates to a Boolean value
There are only 2 possible values for Boolean expressions: true and false
Simple Boolean expressions from the relational operations are
o< less than (5<6)
o> greater than (m>n)
o<= less than or equal (5<=(a+1))
o>= greater than or equal (a >= 7)
o== equals (a+1) == (b+1)
o!= not equals (5 != 6)
Operator precedence
Precedence (priority) determines the order in which operations are evaluated
For example, 2+3*4
oYou evaluate 3*4 first then add 2
You do this because ‘*’ has a higher precedence than ‘+
www.notesolution.com
Unlock document

This preview shows pages 1-2 of the document.
Unlock all 5 pages and 3 million more documents.

Here is the order of precedence from highest to lowest
o1. ( )
o2. * / %
o3. + -
o4. < <= = >= > !=
If 2 operators are at the same level of precedence then they are evaluated from left to right
For example, 3 * 2/4
oEvaluates to 1 not 0
5.3 The if-else statement – the details
Syntax of the Java if-else statement is
oIf (<TEST>)
<Statement S1>
oElse
<Statement S2>
If and else are Java reserved words which give the if-else statement its structure and tell
the compiler that this is an if-else statement
<TEST> is a Boolean expression, must be closed in parentheses ()
<Statement S1> and <Statement S2> is any Java statement
Semantics of the if-else statement
When Java Virtual Machine comes to an if-else statement, first thing that happens is that
<TEST> is evaluated
If <TEST> is true then <Statement S1> is performed
If <TEST> is false then <Statement S2> is performed
5.4 Compound statements
By default, if-else statement contains just 1 statement to be performed
www.notesolution.com
Unlock document

This preview shows pages 1-2 of the document.
Unlock all 5 pages and 3 million more documents.