How to use goto statement correctly

how to use label in java
alternative for goto statement in java
goto statement in java example
goto statement in c++
label statement in java
java goto line
goto statement in switch case in java
goto statement in python

I am taking my high school AP Computer Science class.

I decided to throw a goto statement into a one of our labs just to play around, but I got this error.

Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
    Syntax error on token "goto", assert expected
    restart cannot be resolved to a variable
at Chapter_3.Lab03_Chapter3.Factorial.main(

I went to a goto question on Stackoverflow to find out how to do it properly, and I did exactly as was demonstrated in one of the answers. I really don't understand why the compiler wants an assert statement (at least that's what I assume it wants), nor do I have any idea how to use assert. It seems to want the restart part of goto restart; to be a variable, but restart is just a label that pulls the program back up to line 10 so that the user can enter a valid int. If it wants restart to be a variable, how do I do that?

import java.util.*;

public class Factorial 
    public static void main(String[] args) 
        int x = 1;
        int factValue = 1;
        Scanner userInput = new Scanner(;
        System.out.println("Please enter a nonzero, nonnegative value to be factorialized.");
        int factInput = userInput.nextInt();

            System.out.println("Enter a nonzero, nonnegative value to be factorialized.");
            factInput = userInput.nextInt();

        if(x<1)//This is another way of doing what the above while loop does, I just wanted to have some fun.
            System.out.println("The number you entered is not valid. Please try again.");
            goto restart;
        System.out.println(factInput+"! = "+factValue);

As already pointed out by all the answers goto - a reserved word in Java and is not used in the language.

restart: is called an identifier followed by a colon.

Here are a few things you need to take care of if you wish to achieve similar behavior -

outer:                  // Should be placed exactly before the loop
loopingConstructOne  {  // We can have statements before the outer but not inbetween the label and the loop          
    loopingConstructTwo {
        continue;       // This goes to the top of loopingConstructTwo and continue.
        break;          // This breaks out of loopingConstructTwo.
        continue outer; // This goes to the outer label and reenters loopingConstructOne.
        break outer;    // This breaks out of the loopingConstructOne.
        continue inner; // This will behave similar to continue.
        break inner;    // This will behave similar to break.

I'm not sure of whether should I say similar as I already have.

How to use goto statement correctly, As already pointed out by all the answers goto - a reserved word in Java and is not used in the language. restart: is called an identifier followed by a colon. A goto statement in C programming provides an unconditional jump from the 'goto' to a labeled statement in the same function. NOTE − Use of goto statement is highly discouraged in any programming language because it makes difficult to trace the control flow of a program, making the program hard to understand and hard to modify.

The Java keyword list specifies the goto keyword, but it is marked as "not used".

This was probably done in case it were to be added to a later version of Java.

If goto weren't on the list, and it were added to the language later on, existing code that used the word goto as an identifier (variable name, method name, etcetera) would break. But because goto is a keyword, such code will not even compile in the present, and it remains possible to make it actually do something later on, without breaking existing code.

C goto Statement, For example: to break from nested loops. Should you use goto? If you think the use of goto statement simplifies  Finally construction, the following rules apply to branching with the GoTo statement. Table 1. Block or region. Branching in from outside. Branching out from inside. Try block. Only from a Catch block of the same construction 1. Only to outside the whole construction. Catch block.

If you look up continue and break they accept a "Label". Experiment with that. Goto itself won't work.

public class BreakContinueWithLabel {

    public static void main(String args[]) {

        int[] numbers= new int[]{100,18,21,30};

        //Outer loop checks if number is multiple of 2
        OUTER:  //outer label
        for(int i = 0; i<numbers.length; i++){
            if(i % 2 == 0){
                System.out.println("Odd number: " + i +
                                   ", continue from OUTER label");
                continue OUTER;

            for(int j = 0; j<numbers.length; j++){
                System.out.println("Even number: " + i +
                                   ", break  from INNER label");
                break INNER;

Read more

C++ goto statement, A goto statement provides an unconditional jump from the goto to a labeled statement in the same function. NOTE − Use of goto statement is highly discouraged  Let's look at how to use the GOTO statement in SQL Server (Transact-SQL). For example: DECLARE @site_value INT; SET @site_value = 0; WHILE @site_value <= 10 BEGIN IF @site_value = 2 GOTO TechOnTheNet; SET @site_value = @site_value + 1; END; TechOnTheNet: PRINT ''; GO.

Java does not support goto, it is reserved as a keyword in case they wanted to add it to a later version

How to use 'goto' statement? - MATLAB Answers, Correctly, Walter. I've been confused by the "return" statements in the original code, which cannot be reached. Therefore I assumed, that this is a demo code only  Excel VBA GoTo Statement. VBA Goto Statement is used for overcoming the predicted errors while we add and create a huge code of lines in VBA. This function in VBA allows us to go with the complete code as per our prediction or assumptions. With the help Goto we can go to any specified code of line or location in VBA.

goto doesn't do anything in Java.

Is using goto ever worthwhile?, This is only valid in perf-critical code, but goto statements execute very you goto out of a block the stack is unwinded properly and all proper destructors called). The goto statement transfers the program control directly to a labeled statement. A common use of goto is to transfer control to a specific switch-case label or the default label in a switch statement. The goto statement is also useful to get out of deeply nested loops.

FrontPage 2003 All-in-One Desk Reference For Dummies, John Paul Mueller. Using the GoTo statement correctly The GoTo statement does provide an essential service: It helps you redirect program flow. Before you use  Hi, Can anyone please help me out with the below query: I want to use a goto statement inside if-else statement.How should i do that? I came across in mathworks that there is no goto in matlab.Only Continue and break is available for For loop and while loop alone.

VBA For Dummies, Using GoTo 130 Using the GoTo statement correctly 130 Chapter 6: Trapping Errors and Squashing  In this tutorial, you will learn to create the goto statement in C programming. Also, you will learn when to use a goto statement and when not to use it. The goto statement allows us to transfer control of the program to the specified label.

Chapter 11 THE GOTO STATEMENT 1. Goals The GOTO statement , Use of the GOTO statement is de-emphasized allowed to use the GOTO statement is one of the most operate properly. inside procedure P. Had this not. The real power of GOTO comes when we’re able to let the G-Code make decisions about when to use the GOTO. For that, we use the “IF” statement. IF: Conditional Branching. While GOTO represents an “unconditional branch” in G-Code execution, IF allows for “conditional branching”.

  • Be careful:
  • Even if you find the perfect use case and it totally makes sense, find another way to do it. At best most of the people you work with will think less of you. It's not actually that bad, but you'll never get past the stigma.
  • As for what you are trying to do with the label, by the way, break and continue can specify a label (much as you'd expect goto to)
  • @JohnnyCoder The stigma goes back to the way programmers used to use goto's. In other words, not just to break out of a loop--but any place they felt like it, all over the place. Ever heard the term "spaghetti code"? If you drew lines showing where the goto's started and ended, it would look like a plate of spaghetti. (P.S. I have been programming long enough to remember when spaghetti code was how I and everyone around me wrote programs. We didn't know any better, yet.)
  • @JohnnyCoder A lot of beginning programmers don't understand that the goal of code in most situations is NOT to make the computer do something, it's to make it easy for the next guy to understand, repair, and maintain it as easily as possible. After a decade or two of programming--Being bitten by crappy code that is very difficult to understand and maintain--most programmers understand the importance of maintainability and soon forget that there is any other way to think. Jumping across vast areas of code makes maintenance very challenging. Break and continue can't just jump anywhere like goto
  • This was extremely helpful. I'm going to have to print out this answer and put it in my binder to study and use. +1. You deserve +100, but I cant do that. :)
  • It's a great answer, +1, but if you ever have the desire to do this you are doing it wrong, period--refactor instead, break out a few other well-named methods instead. If you use this construct then at best you avoid a needed refactor, leaving your code messy AND you obfuscate it with a structure that few programmers understand. More likely you will be thought of as a poor programmer by the rest of the team for being unable to make clearer code. The desire to do this should be considered a very bad code smell.
  • @BillK Well, I would argue that with basic commenting you can do this clearly. As long as those on the team can comprehend this, it seems fine to me. That said, I am somewhat inexperienced with teams and probably have no idea what I am talking about.
  • all right. thank you. I hope they add goto it is so convenient.
  • I hope they will never use it. After using the Java language (and earlier C/C++) for more than 10 years, I always found better way to design function/methods not to use that "bug creator" way. Just have a look to the apple ssl implementation security breach. Ok, they also forgot another best practice: always use curly braces even it make the code more verbose...
  • Been programming 30+ years. Started with C. goto was available to me from the start and has been avoided completely the entire time. Initially, other programmers shamed me away from using it. In time, I saw enough usages of goto to give me my own convictions and sense of aversion to it. But, I have seen a few (very few) uses (by other programmers, poor souls) where it was cleaner to use goto than to write the equivalent without it. Those uses probably got de-factored later on.