Ok.. i made this wile loop in main—
public static void main(String[] args){
int age=0;
outer:
while (age<21) {
age++;
if(age==16){
System.out.println("Get your licence");
continue outer;
}
System.out.println("Another year");
}
}
This produces the desired result–
Another year
Another year
Another year
Another year
Another year
Another year
Another year
Another year
Another year
Another year
Another year
Another year
Another year
Another year
Another year
Get your licence
Another year
Another year
Another year
Another year Another year
but if i shift the incrementer to the last line in the for loop.. something unexpected happens ….. IT LEADS TO AN INFINITE LOOP
public static void main(String[] args){
int age=0;
outer:
while (age<21) {
if(age==16){
System.out.println("Get your licence");
continue outer;
}
System.out.println("Another year");
age++;
}
}
Results in…
Get your licence
Get your licence
Get your licence
Get your licence
Get your licence
Get your licence
Get your licence
Get your licence
Get your licence
Get your licence
Get your licence
Get your licence
Get your licence
Get your licence…. till infinity
What is the reason for this behavior?
When you reach this point:
You return to the start of the loop, without incrementing
ageand therefore you are going inside this condition (age == 16) over and over again.