Does Java Support Goto?


Java is known for its consistency and versatility. Java offers several control stream chief methodologies. Java's etymological construction lacks control stream elucidation, as shown by the "goto" statement. In this part, we'll look at why Java doesn't have a goto function, some of its options, and how to use them to achieve similar goals.

Syntax

First, let's examine Java's language structure. The goto explanation enables you freely swap code parts based on a name. Goto generates complex control streams in C and C++, but the code is frequently unreadable and worthless.

label: {
   // Code section 1
   if (condition) {
      // Code section 2
      if (anotherCondition) {
         // Code section 3
         break label;
      } else {
         // Code section 4
         if (yetAnotherCondition) {
            // Code section 5
            if (finalCondition) {
               // Code section 6
            }
         }
      }
   }
   // Code section 7
}

Explanation of Syntax

Java's authors omitted goto articulation because it would confuse code and make it hard to understand. They favored structured control streams for clearer code and fewer errors.

Algorithm

step-by-step algorithm used in Java to manage control flow −

  • Entry Point − The execution of the program will begin at the entry point that has been chosen, which could be the main method or another entry point.

  • Execution in Sequence − The code is run in a way that is consecutive, line by line, except if control stream explanations are experienced, in which case execution leaps to the following assertion in the program.

  • Statements That Create Loops Looping statements, which include the for, while, and do-while statements, allow a block of code to be repeated until a certain condition is satisfied.

Approaches

Even since Java doesn't have goto, developers have found ways to structure similar functionality.

Approach 1: Labeling and Conditional Statements

Explanation

Labels can mark code sections, and conditional expressions can control execution based on conditions. Goto lacks control and readability.

Example

public class GotoExample {
   public static void main(String[] args) {
      GotoExample program = new GotoExample();
      program.execute();
   }

   private void execute() {
      label: {
         System.out.println("Executing Code Section 1");
         // Code section 1
         if (condition) {
            System.out.println("Executing Code Section 2");
            // Code section 2
            if (anotherCondition) {
               System.out.println("Executing Code Section 3");
               // Code section 3
                  break label;
            } else {
               System.out.println("Executing Code Section 4");
               // Code section 4
               if (yetAnotherCondition) {
                  System.out.println("Executing Code Section 5");
                  // Code section 5
                  if (finalCondition) {
                     System.out.println("Executing Code Section 6");
                     // Code section 6
                  }
               }
            }
         }
         System.out.println("Executing Code Section 7");
         // Code section 7
      }
   }

   private boolean condition = true;
   private boolean anotherCondition = true;
   private boolean yetAnotherCondition = true;
   private boolean finalCondition = true;
}

Output

Executing Code Section 1
Executing Code Section 2
Executing Code Section 3

Explanation

To demonstrate execution, we inserted System.out.println() statements to each code section. This lets you track execution and see what's running dependent on circumstances.The control center displays code execution messages.

Approach 2 Encapsulating with Methods

Structure Java control flow by encapsulating code in methods. By breaking the software into manageable pieces, method invocations let us browse it.

Example

public class GotoExample {
   public static void main(String[] args) {
      GotoExample program = new GotoExample();
      program.execute();
   }

   private void execute() {
      section1();
      if (condition()) {
         section2();
         if (anotherCondition()) {
            section3();
            return;
         } else {
            section4();
            if (yetAnotherCondition()) {
               section5();
               if (finalCondition()) {
                  section6();
               }
            }
         }
      }
      section7();
   }

   private void section1() {
      System.out.println("Executing Code Section 1");
      // Code section 1
   }

   private void section2() {
      System.out.println("Executing Code Section 2");
      // Code section 2
   }

   private void section3() {
      System.out.println("Executing Code Section 3");
      // Code section 3
   }

   private void section4() {
      System.out.println("Executing Code Section 4");
      // Code section 4
   }

   private void section5() {
      System.out.println("Executing Code Section 5");
      // Code section 5
   }

   private void section6() {
      System.out.println("Executing Code Section 6");
      // Code section 6
   }

   private void section7() {
      System.out.println("Executing Code Section 7");
      // Code section 7
   }

   private boolean condition() {
      // Define the condition logic
      return true;
   }

   private boolean anotherCondition() {
      // Define the anotherCondition logic
      return true;
   }

   private boolean yetAnotherCondition() {
      // Define the yetAnotherCondition logic
      return true;
   }

   private boolean finalCondition() {
      // Define the finalCondition logic
      return true;
   }
}

Output

Executing Code Section 1
Executing Code Section 2
Executing Code Section 3

Explanation

I added section3(), section4(), section5(), section6(), and section7() methods. Condition, anotherCondition, yetAnotherCondition, and finalCondition were substituted by their procedures. These methods work for you.

Approach 3 State Machines

State machines manage complex control flow. State machines represent transitions mathematically. State machines organize control flow.

Example

enum State {
   STATE_1, STATE_2, STATE_3, STATE_4, STATE_5, STATE_6, STATE_7
}

public class GotoExample {
   public static void main(String[] args) {
      GotoExample program = new GotoExample();
      program.execute();
   }

   private void execute() {
      State currentState = State.STATE_1;

      while (currentState != State.STATE_7) {
         switch (currentState) {
            case STATE_1:
               section1();
               currentState = State.STATE_2;
               break;
            case STATE_2:
               if (condition()) {
                  section2();
                  currentState = State.STATE_3;
               } else {
                  currentState = State.STATE_4;
               }
               break;
               // Define other states and transitions
         }
      }
   }

   private void section1() {
      System.out.println("Executing Code Section 1");
      // Code section 1
   }

   private void section2() {
      System.out.println("Executing Code Section 2");
      // Code section 2
   }

   // Define other section methods and states

   private boolean condition() {
      // Define the condition logic
      return true;
   }
}

Output

Executing Code Section 1
Executing Code Section 2

Explanation

We added condition reasoning to condition()'s technique specification. If possible, change condition()'s strategy group.

Approach 4 Exception Handling

Exception Handling in Java or Java Exceptions with checked, unchecked and errors with example and usage of try, catch, throw, throws and finally keywords.

Example

public class GotoExample {
   public static void main(String[] args) {
      try {
         section1();
         if (condition()) {
            section2();
            if (anotherCondition()) {
               section3();
               throw new GotoException();
            } else {
               section4();
               if (yetAnotherCondition()) {
                  section5();
                  if (finalCondition()) {
                     section6();
                     throw new GotoException();
                  }
               }
            }
         }
         section7();
      } catch (GotoException e) {
         // Handle the exception to continue execution
         // or perform any necessary operations
      }
   }

   private static void section1() {
      System.out.println("Executing Code Section 1");
      // Code section 1
   }

   private static void section2() {
      System.out.println("Executing Code Section 2");
      // Code section 2
   }

   private static void section3() {
      System.out.println("Executing Code Section 3");
      // Code section 3
   }

   private static void section4() {
      System.out.println("Executing Code Section 4");
      // Code section 4
   }

   private static void section5() {
      System.out.println("Executing Code Section 5");
      // Code section 5
   }

   private static void section6() {
      System.out.println("Executing Code Section 6");
      // Code section 6
   }

   private static void section7() {
      System.out.println("Executing Code Section 7");
      // Code section 7
   }

   private static boolean condition() {
      // Define the condition logic
      return true;
   }

   private static boolean anotherCondition() {
      // Define the anotherCondition logic
      return true;
   }

   private static boolean yetAnotherCondition() {
      // Define the yetAnotherCondition logic
      return true;
   }

   private static boolean finalCondition() {
      // Define the finalCondition logic
      return true;
   }
}

class GotoException extends Exception {
   // Custom exception class to simulate the "goto" behavior
}

Output

Executing Code Section 1
Executing Code Section 2
Executing Code Section 3

Explanation

Approach 4 copies the goto proclamation to handle exceptional cases. To "hop" to code, we issue GotoException. try to control execution using the GotoException.

Conclusion

Java's ordered control stream approaches work even without goto articulation. Markings, limited articulations, state machines, and the ordered programming paradigm help engineers write error-free, efficient code. To create trustworthy, easy-to-understand Java programs, you must be open to these possibilities and follow best practices.

Updated on: 31-Jul-2023

217 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements