Page 346 - CITS - Computer Software Application -TT
P. 346
COMPUTER SOFTWARE APPLICATION - CITS
Does goto Exist in Java?
No, goto does not exist in Java. Because Java has reserved it for now and may use it in a later version.
In other languages, goto is a control statement used to transfer control to a certain point in the programming. After
goto statement is executed program starts executing the lines where goto has transferred its control and then
other lines are executed. goto statement works with labels that are identifiers, these labels are used to the state
where goto has to transfer the control of execution.
Java does not support goto() method but it supports label. No support for goto method is due to the following
reasons:
1 Goto-ridden code hard to understand and hard to maintain
2 These labels can be used with nested loops. A combination of break, continue and labels can be used to
achieve the functionality of goto() method in Java.
3 Prohibits compiler optimization
Example:
// Java code
public class Main {
public static void main(String[] args) {
boolean t = true;
first:{
second:{
third:{
System.out.println(“Before the break statement”);
if (
t
) break second; // break out of second block
}
System.out.println(“No execution for this statement”);
}
System.out.println(“Part of first block, outside second block.”);
}
}
}
Output:
Before the break statement
Part of first block, outside second block.
In the above code, the outer label is created for the first for loop. When if the condition is true break outer;
statement will go back to first for loop and break the execution. Use this Compiler to compile your Java code.
Conclusion
• exit() method is used to terminate JVM.
• Status code other than 0 in exit() method indicates abnormal termination of code.
• goto does not exist in Java, but it supports labels.
• It is better to use exception handling or plain return statements to exit a program while execution.
• System.exit() method suit better for script-based applications or wherever the status codes are interpreted.
333
CITS : IT&ITES - Computer Software Application - Lesson 85 - 93