2. Outline
• Overview of Java statements
• If statement
• Switch statement
• While, Do while loop
• For loop
2
3. Overview of Java statements
• In programming, a statement is an instruction to
do something.
• It controls the sequence of execution of a
program.
• In Java, a statement is terminated with a
semicolon and multiple statements can be
written on a single line.
Example: x = y + 1; z = y + 2;
• In Java, an empty statement is legal and does
nothing:
Example: ;
3
4. Cont…
• You can have a block of statements enclosed
between braces.
• If the value of expression is true, all the
statements enclosed in the block will be
executed.
• Without the braces, the code no longer has a
statement block
4
5. 5-5
The if Statement
• The if statement has the following syntax:
if ( condition )
statement;
if is a Java
reserved word
The condition must be a
boolean expression. It must
evaluate to either true or false.
If the condition is true, the statement is executed.
If it is false, the statement is skipped.
6. 5-6
Logic of an if statement
condition
evaluated
statement
true
false
7. 5-7
Logic of an if-else statement
condition
evaluated
statement1
true false
statement2
8. 5-8
Boolean Expressions
• A condition often uses one of Java's equality
operators or relational operators, which all
return boolean results:
== equal to
!= not equal to
< less than
> greater than
<= less than or equal to
>= greater than or equal to
9. 5-9
The if Statement
• An example of an if statement:
if (sum > MAX)
delta = sum - MAX;
System.out.println ("The sum is " + sum);
• First the condition is evaluated -- the value of sum is either greater
than the value of MAX, or it is not
• If the condition is true, the assignment statement is executed -- if it
isn’t, it is skipped.
• Either way, the call to println is executed next
10. Example
if (age < 0) output=“error”;
else if(age<=8) output=“too young”;
else if(age<=17) output=“ok”;
else if(age<=24) output=“too old”;
else output=“really really old”;
if(age < 0) output=“error”;
if(age<=8) output=“too young”;
if(age<=17) output=“ok”;
if(age<=24) output=“too old”;
else output=“really really old”;
Nested approach
Note: indentation is not
needed, its there for program
readability
Alternate approach – what is
Wrong with this code?
If you are 16, what
will output be?
We could solve this problem by reordering the
if statements in the opposite order, but the
new code would be inefficient – why? 10
11. The Switch Statement
• An alternate approach to using the nested if-else
structure is an instruction called switch
• We will use the switch statement if we are testing
a single variable against a list of values
• Structure:
– switch (variable)
{
case val1 : statement1;
case val2 : statement2;
case val3 : statement3;
…
case vallast : statementlast;
default : defaultstatement;
}
Compare variable with val1, val2,
… and pick which statement to
execute based on which value the
variable matches
11
12. Switch Example
switch (grade)
{
case ‘A’ :
comment = "gold star";
break;
case ‘B’ :
comment = "silver star";
break;
case ‘C’ :
comment = "bronze star";
break;
case ‘D’ :
comment = "no star";
break;
case ‘F’ :
comment = "demerit";
break;
default :
comment = "error, illegal letter grade! ";
}
In this example, comment is a
String which is assigned a value
based on the student’s letter grade
default is used as an error
checking mechanism here – if
reached, then the grade is an
illegal grade
NOTE: the word break is used
to exit the switch statement,
default is used as a final else
clause for the switch
12
13. Which Statement Should You Use?
• When it comes to
selection, you have
five possibilities:
– if statement
– if-else statement
– group of if
statements
– nested if-else
statement
– switch statement
• If there is only one action, then use
the if statement
• If two actions, one if the condition
is true, one if the condition is false,
then use the if-else statement
• If you have a series of possibilities,
which should you use?
– Switch statement if the possibility is
based on a single variable and the
variable is an integral data type
(integer, character or a user defined
type that is ordinal)
– Otherwise, use the nested if-else
statement
13
14. Repetition
• What happens if we want to do some action multiple
times?
– For instance, we want to count the number of times it takes when
rolling a 6-sided die until we roll a 6
• We write a program that rolls the 6-sided die once and outputs the
result, and then we could run the program over and over until we get a
6, but this is both tiresome and requires that the user count the number
of times we ran the program
– The better approach is to use a repetition statement which would
keep running the same random number instruction over and over
until it it a 6, so we will use a repetition control statement
– There are three forms of repetition statements in Java:
• While loops
• Do loops
• For loops
14
15. The While Statement
• The while statement evaluates a
condition
– if that condition is true, the body of the
while statement is executed and the
process is repeated
– If the condition is false, the rest of the
statement is skipped and control
continues with the next instruction after
the while statement
while ( condition )
statement;
while is a
reserved word
If the condition is true, the statement is executed.
Then the condition is evaluated again.
statement
true
condition
evaluated
false
15
16. Example
import java.util.Random;
public class SixRoller {
public static void main(String[] args) {
int count=1, die;
Random g = new Random();
die=g.nextInt(6)+1;
System.out.println("The first roll is a " + die);
while(die!=6) {
die=g.nextInt(6)+1;
count++;
System.out.println("The next roll is a " + die);
}
System.out.println("It took " + count + " rolls to get a 6");
}
}
16
17. Sum Example
Scanner in = new Scanner(System.in);
int value, sum;
…
sum = 0;
System.out.print(“Enter a positive integer, negative to quit: ”);
value = in.nextInt( );
while (value >= 0)
{
sum += value;
System.out.print(“Enter another positive integer, negative to quit: ”);
value = in.nextInt( );
}
System.out.println("The sum of the numbers you entered is " + sum);
value < 0 is our
sentinel for the loop
Notice that we repeated these
Instructions – why?
Initialize sum before we enter the loop
17
18. Infinite Loops
• Careless (and even careful) programmers will write
infinite loops
• This is a major problem when using the while loop
– The basic idea behind the loop is to continue executing
while a condition is true
• If that condition is based on an input value, then the program
must input a new value during each iteration so that the user can
change the value to one that exits the loop
• Otherwise, the value never changes and the loop never stops!
• Exiting an infinite loop
– if you suspect that your program is caught in an infinite
loop, about your only recourse is to stop the program
• Press control-C on the keyboard
18
19. The do Loop
• The do loop is similar to the while loop
but is a post-test loop, the while loop is a
pre-test loop
• The Do loop starts with the reserved
word do followed by the loop body and
then the reserved word while and the
condition
– The difference is the flow of control – here,
the condition is not evaluated until after the
body of the loop executes
do
{
statement;
}
while ( condition )
Uses both
the do and
while
reserved
words
true
condition
evaluated
statement
false
19
20. While vs. Do
• The only difference between
these two statements is when
the condition is evaluated
– While: evaluated before
executing the loop body
– Do: evaluated after executing
the loop body
• If you want to automatically
execute the loop body at least
once, use the Do loop
• If you don’t want to do the body if
the condition is not true, use the
While loop
statement
true
condition
evaluated
false
true
condition
evaluated
statement
false
20
21. Using Loops to Verify Input
• Consider a situation where we want
the user to input one of a set of
values that constitute a legal input
• What if the user enters an illegal
input?
– Example: input a non-negative
integer and take the square root
– If x < 0, we would get a run-time error
when the sqrt operation is invoked!
• A solution to this problem is
to place the prompt and
input statements inside a
loop that only terminates
once the user has entered
the right value
– We will use a do statement for
this since we will want the
user to input the value at least
one time
System.out.print(“Enter a non-negative number ”);
x = in.nextInt( );
y = Math.sqrt((double) x);
do
{
System.out.print(“Enter a non-negative number ”);
x = in.nextInt( );
} while (x < 0);
y = Math.sqrt((double) x);
21
22. Block Statements
• Several statements can be grouped together
into a block statement delimited by braces
• A block statement can be used wherever a
statement is called for in the Java syntax rules
if (total > MAX)
{
System.out.println ("Error!!");
errorCount++;
}
22
23. 5-23
Block Statements
• In an if-else statement, the if portion, or the
else portion, or both, could be block statements
if (total > MAX)
{
System.out.println ("Error!!");
errorCount++;
}
else
{
System.out.println ("Total: " + total);
current = total*2;
}
24. 5-24
Comparing Characters
• In Unicode, the digit characters (0-9) are contiguous
and in order
• Likewise, the uppercase letters (A-Z) and lowercase
letters (a-z) are contiguous and in order
Characters Unicode Values
0 – 9 48 through 57
A – Z 65 through 90
a – z 97 through 122
25. 5-25
Comparing Strings
• Remember that in Java a character string is an
object
• The equals method can be called with strings
to determine if two strings contain exactly the
same characters in the same order
• The equals method returns a boolean result
if (name1.equals(name2))
System.out.println ("Same name");
26. 5-26
Comparing Strings
• We cannot use the relational operators to compare strings
• The String class contains a method called compareTo
to determine if one string comes before another
• A call to name1.compareTo(name2)
– returns zero if name1 and name2 are equal (contain the same
characters)
– returns a negative value if name1 is less than name2
– returns a positive value if name1 is greater than name2
27. 5-27
Comparing Strings
if (name1.compareTo(name2) < 0)
System.out.println (name1 + "comes first");
else
if (name1.compareTo(name2) == 0)
System.out.println ("Same name");
else
System.out.println (name2 + "comes first");
• Because comparing characters and strings is based on a character
set, it is called a lexicographic ordering
28. 5-28
Comparing Objects
• The == operator can be applied to objects – it returns
true if the two references are aliases of each other
• The equals method is defined for all objects, but
unless we redefine it when we write a class, it has the
same semantics as the == operator
• It has been redefined in the String class to compare
the characters in the two strings
• When you write a class, you can redefine the equals
method to return true under whatever conditions are
appropriate
30. for ( int counter = 1; counter <= 10; counter++ )
Initial value
of control variable
Increment
of control variable
Control variable
name
Final value
of control variable
for
keyword
Loop-continuation condition
Components of a typical for structure header.
for Loop
31. 31
The for Repetition Structure (cont.)
for ( expression1; expression2; expression3
)
statement;
can usually be rewritten as:
expression1;
while ( expression2 ) {
statement;
expression3;
}
32. 32
Examples Using the for Structure
• Varying control variable in for structure
– Vary control variable from 1 to 100 in increments
of 1
• for ( int i = 1; i <= 100; i++ )
– Vary control variable from 100 to 1 in decrements
of –1
• for ( int i = 100; i >= 1; i-- )
– Vary control variable from 7 to 77 in steps of 7
• for ( int i = 7; i <= 77; i += 7 )