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

java
int score = 75; if (score >= 70) { System.out.println(\"Passed\"); } else { System.out.println(\"Failed\"); }

else if

java
if (score >= 90) { System.out.println(\"Excellent\"); } else if (score >= 70) { System.out.println(\"Good\"); } else { System.out.println(\"Needs improvement\"); }

switch

java
int day = 3; switch (day) { case 1 -> System.out.println(\"Monday\"); case 2 -> System.out.println(\"Tuesday\"); default -> System.out.println(\"Other day\"); }

for loop

java
for (int i = 0; i < 5; i++) { System.out.println(\"i = \" + i); }

while loop

java
int j = 0; while (j < 3) { System.out.println(j); j++; }

In the next lesson you will see how to group behaviour into reusable methods.