You are on page 1of 11

Conditionals in

Java
Why Conditionals?
• Up until now, we have only considered
programs where all statements are executed
all the time.
• It is useful to add statements to a program
that sometimes are executed and sometimes
not.
• Such statements are called conditional
The if statement
if (condition)
statement;
• If the condition is found to be true, execute the
statement, otherwise skip it.
• Condition must be in parentheses.
• The condition must have a boolean value.
• Note there is no semicolon after the condition
– If you put one there, will mean the empty statement
comes after the if.
– The next statement will always execute.
• Traditionally the statement dependant on the if is
indented.
Comparison Operators
• The following operators are commonly used in
conditions.
– Greater than (>) or less than (<)
– Greater than or equal to (>=) or less than or equal to
(<=)
– Equal to (==). Note two equal signs.
– Not equal to (!= )
• Single equal sign (=) means assignment. It is not a
comparison operator.
Blocks
• Java is a “block-structured” language
– Supports blocks, groups of statements executed
together.
– Surrounded by curly brackets
• When the first character after the condition of an if
is a curly bracket, the entire block is dependant on
the if.
– I.e. if the condition is true, entire block executes in
order.
– If false, entire block is skipped.
– Of course the block can contain another if...
Some examples
• If m is greater than 0, print it:
if (m>0)
System.out.print(m);
• If y is equal to z, set x equal to y and a equal to b.
if (y==z) {
x=y;
a=b;
}
– Note that there is no semicolon after the close bracket.
Else
• The if/else statement provides not only a statement
to execute when the condition is true, but also a
different one to execute when the condition is
false.
if (condition)
statement;
else
statement;
• Either statement can be a block (without a
semicolon)
Indenting Ifs
• Dependant statements if (a==b)
– Must be on subsequent a=a+1;
lines
– Must be indented
if (a==b) {
-OR-
• Open brackets may be on if (a==b)
the same line or the next {

if (a==b)
• Each level uses the same if (b==c)
number of spaces c=c+1;
Indenting Ifs cont’d
• Else statements must be if (a==b)
indented the same as the a=a+1;
corresponding if else
b=b+1;
• Statements dependent on if (a==b) {
the same if or else must a=a+1;
be indented the same b=b+1;
• Close curly brackets }
must be indented the
same as their if or else
Indenting Ifs cont’d
• The if should be even a=a+1;
with the statement before if (a==b)
it b=b+1;
Summary
• The if statement supports conditionals
– Condition is boolean
– Statement executed only if condition is true
• Relational operators frequently used in the
condition.
• Surround multiple statements with curly brackets.
• If/else lets program choose between two
statements or blocks
• Best to use curly brackets when nesting ifs.

You might also like