Conditionals and Loops
Conditionals and Loops
Programs rarely run in a straight line. You often need to make decisions or repeat some code. In Java you use conditionals and loops for this.
if and else
javaint score = 75; if (score >= 70) { System.out.println(\"Passed\"); } else { System.out.println(\"Failed\"); }
else if
javaif (score >= 90) { System.out.println(\"Excellent\"); } else if (score >= 70) { System.out.println(\"Good\"); } else { System.out.println(\"Needs improvement\"); }
switch
javaint day = 3; switch (day) { case 1 -> System.out.println(\"Monday\"); case 2 -> System.out.println(\"Tuesday\"); default -> System.out.println(\"Other day\"); }
for loop
javafor (int i = 0; i < 5; i++) { System.out.println(\"i = \" + i); }
while loop
javaint j = 0; while (j < 3) { System.out.println(j); j++; }
In the next lesson you will see how to group behaviour into reusable methods.