Is there a goto statement in Java?
No, Java does not have a goto
statement. The goto
statement is a control flow statement that is used to transfer the control of a program to a specific line of code within the same function. It is often used to create a loop or to jump out of a loop.
In Java, the break
and continue
statements are used to control the flow of a loop, and the return
statement is used to exit a method. The throw
and throws
statements are used to throw and handle exceptions.
Here is an example of using break
and continue
to control the flow of a loop in Java:
for (int i = 0; i < 10; i++) {
if (i == 5) {
break;
}
System.out.println(i);
}
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
continue;
}
System.out.println(i);
}
The break
statement is used to exit the loop, and the continue
statement is used to skip the rest of the current iteration and move on to the next one.