ciaodarwin
ciaodarwin

Reputation: 481

Jumper in Java?

Is there any syntax that allows you to jump from one line to the other?

example:

System.out.println("line");
System.out.println("line2");
System.out.println("line3");
System.out.println("line4");

//goto line2 or something like that??

Upvotes: 0

Views: 2705

Answers (5)

Durandal
Durandal

Reputation: 20059

Java intentionally does not support goto. This is to encourage (force) you to build the control flow using the proper conditional constructs.

In your example, the proper method would be a while-loop:

System.out.println("line");
while (true) {
    System.out.println("line2");
    System.out.println("line3");
    System.out.println("line4");
}

If you think about it, there is no code flow pattern that cannot be expressed without the need for goto (it may require to stray from personal ingrained habits). The only time you may want to use goto is to avoid code duplication. If you encounter such a case, restructuring the code into a separate method that can be called where needed is a much cleaner solution.

Upvotes: 1

Marko Topolnik
Marko Topolnik

Reputation: 200168

You can achieve this in a roundabout way, for example with a switch statement:

switch (lineNum) {
  case 1: System.out.println("line 1");
  case 2: System.out.println("line 2");
  case 3: System.out.println("line 3");
  case 4: System.out.println("line 4");
}

Now you must ensure lineNum has the appropriate value.

For any backward jumps you'll need a do or while loop.

Upvotes: 1

tckmn
tckmn

Reputation: 59283

No, there is no goto statement, but there are several workarounds:

do {
    //do stuff
    if (condition) break; //this will jump--+
    //do stuff                           // |
} while (false);                         // |
// here <-----------------------------------+

and

int id = 0;
while (true) {
    switch (id) {
        case 0:
            //do stuff
            if (condition) {id = 3; break;} //jumps to case 3:
        case 1:
            if (condition) {id = 1; break;} //jumps to case 1:
        // ...
    }
}

Upvotes: 3

fGo
fGo

Reputation: 1146

what exactly do you want to achieve? you could use labels as in http://geekycoder.wordpress.com/2008/06/25/tipjava-using-block-label-as-goto/, anyway using goto like statements could lead to spaghetti code

Upvotes: 0

Bathsheba
Bathsheba

Reputation: 234715

There is no goto in Java although it is a reserved keyword.

A goto is considered a bad programming construct and, as such, was left out of Java.

Upvotes: 0

Related Questions