Calling and returning from a method.
Conditional execution: either run some code or don’t based on some condition.
Looping: run some code repeatedly, while some condition holds.
whileThe most primitive style of loop.
while (running) {
doSomething();
}
Like an if the code inside the {}s only
runs if the expression inside the ()s evaluates to
true.
But it runs repeatedly until the condition is false.
while
while (condition) {body}
The condition has to evaluate to a boolean.
The body can consist of any code.
The body needs to change something so the condition will eventually become false or the loop will repeat infinitely.
while (true) {
String command = readCommand();
execute(command);
}
Many while loops are written following this pattern:
int i = 0;
while (i < 10) {
System.out.println(i);
i++;
}
forCaptures this common pattern.
int i = 0;
while (i < 10) {
System.out.println(i);
i++;
}
becomes
for (int i = 0; i < 10; i++) {
System.out.println(i);
}
You will soon be able to write this loop header in your sleep.
If you start at 0 and loop while
< n the loop runs n times.
for (initializer; condition;
updater) {body}
Note the three clauses in the loop header are separated by semicolons.
returnpublic boolean hasX (String s) {
for (int i = 0; i < s.length(); i++) {
if (s.substring(i, i + 1).equals("X")) {
return true;
}
}
return false;
}
The return causes us to return immediately from the
method.
The remaining iterations of the loop are abandoned.
Note the return false after the loop.
Use for when you know how many times the loop needs to
run.
Use while when you don’t.
(Roughly speaking)
while

for
