Page 235 - IT-802_class_12
P. 235
Returns true if value of a false, true
! Logical NOT !a false
otherwise
3.4 controL FLow
Remember that a program is nothing more than a list of instructions. Java executes the instructions one after the other,
in a sequential fashion. However, there are situations when you may find yourself in this situation.
However, there are situations when you may want to run an instruction only if a condition is met. You might also wish
to repeat a series of instructions until a condition is met. Java provides selection structures, while for the latter, it
provides repetition structures.
3.4.1 Selection Structures
In real life, you frequently choose your actions based on whether or not a condition is true. If it’s raining outside, let
say for example, you’ll bring an umbrella; otherwise, you won’t.
Looking Outside
the Window
True Is it False
Raining?
Carry an Don’t Carry an
Umbrella Umbrella
Similarly, you might wish to run a section of a program based on the value of an expression. For executing a block of
code conditionally, Java includes two statements: the if else statement and the switch statement. (A block of code is a
sequence of statements contained in curly braces.)
3.4.2 The if-else Statement
The if statement in Java lets us execute a block of code depending upon whether an expression evaluates to true or
false. The syntax of the Java if statement is as below:
if (expression)
{
statements
}
After the if keyword, the expression in the round brackets is a condition, which is an expression made up of relational
and logical operators. If the condition evaluates to true, the following block of code is performed; otherwise, it is not.
The curly braces are optional if the block contains only one statement after the if. Let’s make our Percentage Calculator
application even better. We will declare the student passed if the percentage obtained by the student is greater than
or equal to 40%.
As a result, we write, in our percentage calculator application,
if (percentage >= 40)
{
Fundamentals of Java Programming 233

