Loops allow us to repeat the same set of instructions a number of times until a certain pre-specified condition is met. There are different looping statements in Java.
for loop
public static void main(String[] args){ for (int i = 1; i <= 3; i++){ System.out.println("I: " + i); } }
Output
I: 1 I: 2 I: 3
while loop
public class Main { public static void main(String[] args){ int i = 1; while(i<= 3){ System.out.println("I: " + i); i++; } } }
Output
I: 1 I: 2 I: 3
do…while loop
public class Main { public static void main(String[] args){ int i = 1; do{ System.out.println("I: " + i); i++; }while(i<=3); } }
Output
I: 1 I: 2 I: 3
No Comments