Java Programming for Beginners: From Introduction To Your First Java Project

Concepts: Introduce for, while, and do-while loops to repeat actions. Explain when to use each type of loop.

 

Code example:

public class LoopsExample {
public static void main(String[] args) {
System.out.println(“For loop:”);
for (int i = 0; i < 3; i++) {
System.out.println(“i is: ” + i);
}

System.out.println(“While loop:”);
int j = 0;
while (j < 3) {
System.out.println(“j is: ” + j);
j++;
}
}
}

Switch Statements

Statements you can use the switch statement, instead of many if..else.
The switch statement selects one of many code blocks to be executed:

Code example:

switch(expression) {
  case x:
    // code block
    break;
  case y:
    // code block
    break;
  default:
    // code block
}

 

Quiz: Identify correct loop structures and predict the number of iterations for a given loop.