Home > Java > javaTutorial > Does Java support Goto?

Does Java support Goto?

王林
Release: 2023-09-05 23:33:07
forward
1052 people have browsed it

Does Java support Goto?

Java is known for its consistency and versatility. Java provides several main methods of control flow. Java's etymological constructs lack control flow specifications, as shown by the "goto" statement. In this part, we will learn why Java does not have a goto function, some of its options, and how to use them to achieve similar goals.

grammar

First, let’s take a look at Java’s language structure. The goto interpretation enables you to freely exchange sections of code based on their names. Goto generates complex control flow in C and C, but the code is often 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
}
Copy after login

Glossary explanation

The authors of Java omitted the goto expression because it would make the code cluttered and difficult to understand. They favor structured control flow for cleaner code and fewer bugs.

algorithm

Step-by-step algorithm for managing control flow in Java -

  • Entry Point- The execution of the program will start from the selected entry point, which can be the main method or another entry point.

  • Sequential Execution - The code runs line by line in a continuous manner unless a control flow interpretation is encountered, in which case execution jumps to the following assertion routine.

  • Statements that create loops Loop statements (including for, while, and do-while statements) allow a block of code to be repeated until a specific condition is met.

method

Even though Java didn't have goto, developers found ways to build similar functionality.

Method 1: Labels and conditional statements

illustrate

The

tag can mark code segments, 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;
}
Copy after login

Output

Executing Code Section 1
Executing Code Section 2
Executing Code Section 3
Copy after login
Copy after login
Copy after login

illustrate

To demonstrate execution, we insert System.out.println() statements into each section of code. This allows you to track execution and see what is running depending on the situation. Control Center displays code execution messages.

Method 2 Use method encapsulation

Construct Java control flow by encapsulating code in methods. Method calls allow us to navigate the software by breaking it down into manageable parts.

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;
   }
}
Copy after login

Output

Executing Code Section 1
Executing Code Section 2
Executing Code Section 3
Copy after login
Copy after login
Copy after login

illustrate

I added section3(), section4(), section5(), section6() and section7() methods. Condition, anotherCondition, yetAnotherCondition, and FinalCondition are replaced by their procedures. These methods are suitable for you.

Method 3 State Machine

State machine manages 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;
   }
}
Copy after login

Output

Executing Code Section 1
Executing Code Section 2
Copy after login

illustrate

We added conditional reasoning to the technical specification of condition(). If possible, change the policy group for condition().

Method 4 Exception Handling

Exception handling in Java or Java exceptions with checked, unchecked and errors, and examples 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
}
Copy after login

Output

Executing Code Section 1
Executing Code Section 2
Executing Code Section 3
Copy after login
Copy after login
Copy after login

illustrate

Method 4 Copy the goto statement to handle exceptions. To "jump" to code, we issue a GotoException. Try using GotoException to control execution.

in conclusion

Java's ordered control flow approach works even without goto expressions. Notations, finite joints, state machines, and sequential programming paradigms help engineers write error-free, efficient code. To create trustworthy, easy-to-understand Java programs, you must accept these possibilities and follow best practices.

The above is the detailed content of Does Java support Goto?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template