Controlling the program flow
Flow control changes the order in which your program runs. Decide with conditions, repeat with loops and jump with break and continue.
Decide
Only when a condition holds
ifelseswitchRepeat
One block, many times
forwhiledo-whileJump
Cut or skip laps
breakcontinuenota = 85nota >= 90nota >= 70elsenota = 85(nota >= 70)condition
"Passed"if true
"Failed"if false
resultado = "Passed"dia = 3case 1βMondaycase 2βTuesdaycase 3βWednesdaybreakdefaultβInvalid dayWithout break, execution falls into the next case
case 1 ->"Monday"case 2 ->"Tuesday"case 3 ->"Wednesday"default ->"Invalid day"dia = 3
nombreDia = "Wednesday"Console menu
1Add personcargarPersona()2List peoplelistarPersonas()0Quitprintln("β¦")defaultInvalid optionprintln("β¦")case 1 -> { β¦ } for Laps known in advance
start Β· condition Β· step while Checks before the block
may never run do-while Checks after the block
at least once Start
int i = 1Condition
i <= 5Step
i++i = 1i = 2i = 3i = 4i = 5i = 66 <= 5 false: exits
while (contador < 3)contador = 00 < 3 true
contador = 11 < 3 true
contador = 22 < 3 true
contador = 33 < 3 false: exits
Block
runs first
numero < 5checked at the end
10 < 5 = false
the loop ends
Result
suma = 2550if / else if / else ternary switch for while do-while for-each break continue CursoDeJava Β· l03_control_de_flujo_y_bucles
43 solved exercises
prime numbers sum of digits discounts and salaries password checks Flow control changes the order in which your program runs.
Decide with conditions, repeat with loops and jump with break and continue.
Flow control changes the order in which your program runs. Decide with conditions, repeat with loops and jump with break and continue.
if runs a block only when its condition is true.
else if tests another condition and else covers everything else.
if runs a block only when its condition is true. else if tests another condition and else covers everything else.
int nota = 85; if (nota >= 90) {System.out.println("Excellent");} else if (nota >= 70) {System.out.println("Passed");} else {System.out.println("Failed");} With nota = 85 the 90 is not reached, but the 70 is.
The first true block runs and the rest is ignored: it prints Passed.
With nota = 85 the 90 is not reached, but the 70 is. The first true block runs and the rest is ignored: it prints Passed.
int nota = 85; if (nota >= 90) {System.out.println("Excellent");} else if (nota >= 70) {System.out.println("Passed");} else {System.out.println("Failed");} The ternary operator is a one-line if that assigns a value.
Condition, ?, value if true, :, value if false.
The ternary operator is a one-line if that assigns a value. Condition, ?, value if true, :, value if false.
int nota = 85;String resultado = (nota >= 70) ? "Passed" : "Failed"; switch compares one variable against several possible values.
Each case is a candidate value and default handles any other.
switch compares one variable against several possible values. Each case is a candidate value and default handles any other.
int dia = 3; switch (dia) {case 1:System.out.println("Monday");break;case 2:System.out.println("Tuesday");break;case 3:System.out.println("Wednesday");break;default:System.out.println("Invalid day");break;} With dia = 3 the third case matches and Wednesday is printed.
Cases 1 and 2 do not match and are skipped.
With dia = 3 the third case matches and Wednesday is printed. Cases 1 and 2 do not match and are skipped.
int dia = 3; switch (dia) {case 1:System.out.println("Monday");break;case 2:System.out.println("Tuesday");break;case 3:System.out.println("Wednesday");break;default:System.out.println("Invalid day");break;} break ends the switch; without it, execution falls into the next case.
That is why every classic case ends with break.
break ends the switch; without it, execution falls into the next case. That is why every classic case ends with break.
int dia = 3; switch (dia) {case 1:System.out.println("Monday");break;case 2:System.out.println("Tuesday");break;case 3:System.out.println("Wednesday");break;default:System.out.println("Invalid day");break;} Modern Java: a switch can return a value with ->.
Each case brings its result directly and needs no break.
Modern Java: a switch can return a value with ->. Each case brings its result directly and needs no break.
String nombreDia = switch (dia) {case 1 -> "Monday";case 2 -> "Tuesday";case 3 -> "Wednesday";default -> "Invalid day";}; Arrows also run actions, as in a console menu.
Each case runs only its own statement, without falling through.
If you need several statements, use a block.
Arrows also run actions, as in a console menu. Each case runs only its own statement, without falling through. If you need several statements, use a block.
switch (opcion) {case 1 -> cargarPersona(leer, personas);case 2 -> listarPersonas(personas);case 0 -> System.out.println("End of program");default -> System.out.println("Invalid option. Choose 0, 1 or 2.");} A loop repeats a block of code while a condition holds.
There are three forms: for, while and do-while.
A loop repeats a block of code while a condition holds. There are three forms: for, while and do-while.
for is used when you know in advance how many laps it takes.
It has a start, a condition and a step, all on the same line.
for is used when you know in advance how many laps it takes. It has a start, a condition and a step, all on the same line.
for (int i = 1; i <= 5; i++) {System.out.println("Iteration number: " + i);} It prints i from 1 to 5 and then exits.
Each lap checks, runs the block and moves on with i++.
It prints i from 1 to 5 and then exits. Each lap checks, runs the block and moves on with i++.
for (int i = 1; i <= 5; i++) {System.out.println("Iteration number: " + i);} java BucleForIteration number: 1Iteration number: 2Iteration number: 3Iteration number: 4Iteration number: 5 while evaluates the condition before running the block.
contador++ avoids an infinite loop: at 3, the condition fails.
while evaluates the condition before running the block. contador++ avoids an infinite loop: at 3, the condition fails.
int contador = 0;while (contador < 3) {System.out.println("Counter: " + contador);contador++;} java BucleWhileCounter: 0Counter: 1Counter: 2 do-while runs the block first and checks the condition at the end.
Even if numero < 5 is false from the start, the block runs once.
do-while runs the block first and checks the condition at the end. Even if numero < 5 is false from the start, the block runs once.
int numero = 10;do {System.out.println("It runs at least once");} while (numero < 5); java BucleDoWhileIt runs at least once while checks first, do-while checks last and for packs it all in one line.
Choose by how many laps you know and whether the block must run at least once.
while checks first, do-while checks last and for packs it all in one line. Choose by how many laps you know and whether the block must run at least once.
break stops the loop immediately; continue skips the current iteration.
This loop walks i from 1 to 10. Let us see what happens at 5 and at 8.
break stops the loop immediately; continue skips the current iteration. This loop walks i from 1 to 10. Let us see what happens at 5 and at 8.
With i = 1, 2, 3 and 4 each value is printed and the loop goes on.
At i == 5, continue skips the rest of the lap and moves to i = 6.
With i = 1, 2, 3 and 4 each value is printed and the loop goes on. At i == 5, continue skips the rest of the lap and moves to i = 6.
i = 6 and 7 are printed. At i == 8, break ends the loop entirely.
Numbers 9 and 10 never run. Final output: 1 2 3 4 6 7.
i = 6 and 7 are printed. At i == 8, break ends the loop entirely. Numbers 9 and 10 never run. Final output: 1 2 3 4 6 7.
Challenge: add up all the even numbers between 1 and 100 with a loop.
Print the final result. Try it before looking at the solution.
Challenge: add up all the even numbers between 1 and 100 with a loop. Print the final result. Try it before looking at the solution.
A for with i += 2 walks only the even numbers and adds them to suma.
The sum of the even numbers from 1 to 100 is 2550.
A for with i += 2 walks only the even numbers and adds them to suma. The sum of the even numbers from 1 to 100 is 2550.
int suma = 0;for (int i = 2; i <= 100; i += 2) {suma += i;}System.out.println("Sum of even numbers: " + suma); javac SumaPares.javajava SumaParesSum of even numbers: 2550 You saw conditionals, switch, loops and control with break and continue.
Reinforce it all with the 43 solved exercises in the course repository.
You saw conditionals, switch, loops and control with break and continue. Reinforce it all with the 43 solved exercises in the course repository.