Translate goto statements to if, switch, while, break, etc - java

Is there a way to mechanically translate goto statements to if, switch, while, break, and continue statements, etc, or with function calls, objects, anything?

While it is not a good idea, it is possible using loops and swith-case. In the following example the goto variable decides what label (0, 1, 2 or default) to goto when you get to a continue.
int goTo=0;
while(true){
switch(goTo){
case 0:
doSomething();
goTo = 1;
continue;
case 1:
doSomethingElse();
goTo = 2;
continue;
case 2:
doSOmethingDifferent();
goTo = 0;
continue;
default:
return;
}
}

I thought this would be worth sharing here. I saw this on Reddit one day, it's an implementation of goto to an arbitrary line number (in the same .java file) via a custom class loader. It's a fun piece of code. http://steike.com/tmp/goto.zip . I take no credit for it.
Edit:
For those who are curious but don't want to download the zip and run it, for the following file:
public class GotoDemo {
public static void main(String[] args) {
int i = 5;
System.out.println(i);
i = i - 1;
if (i >= 0) {
GotoFactory.getSharedInstance().getGoto().go(4);
}
try {
System.out.print("Hell");
if (Math.random() < 2) throw new Exception();
System.out.println("World!");
} catch (Exception e) {
System.out.print("o ");
GotoFactory.getSharedInstance().getGoto().go(13);
}
}
}
It will print:
3
2
1
0
Hello World!

Considering the complexity that goto's can create based on where its jumping between, it's very doubtful.

The Java language doesn't support the features necessary to simulate gotos to arbitrary position (not even within the same method). You can implement a few simple uses of goto using the constructs you mentioned, but can't implement all possible goto uses this way. (*)
On the byte code level you could probably implement goto (at least within a method), but that byte code could not be mapped back to valid Java code in this case.
As for gotos that cross method or object boundaries: That's definitely a big no-no on the JVM level. The entire Java security model depends on the fact that code is verifyable and thus has only defined entry points (also known as "methods").
(*) Disclaimer: this assumes that you don't want to completely restructure the method to implement the effect of goto, which could also invoke code duplication and obfuscating the "normal" flow of the method. Since you can implement a turing machine in a Java method you can definitely implement "goto" in a Java method ;-)

Sure: (abbreviating slightly for clarity)
int goTo = 0; boolean done = false;
while (!done) {
switch (goTo) {
default:
case 1: System.out.println("We're at line 1!"); goTo = 2; break;
case 2: System.out.println("We're going to line 4!"); goTo = 4; break;
case 3: System.out.println("We're at line 3 and we're done!"); done = true; break;
case 4: System.out.println("We're at 4, going to 2! Screw you, line 3!"); goTo = 2; break;
}
}
Why you would want to do such a thing is beyond me, but hey, you can...

Yes, using a combination of the methods you mentioned...it is possible (anything is possible really, just figuring out how to do it properly is a pain in the ass).
Keep in mind that goto's can result in extremely complex execution paths...and therefore may result in unsightly large amounts of duplicate code in whatever is generated.

In practice, I imagine any given example goto can be translated to something else, particularly if method extraction is an allowed transformation. Is this an abstract question or do you actually have so many goto's that you really need an actual tool? Perhaps the java code itself was machine-translated from something?
I used to put one actual goto into every program I wrote just to annoy the purists.

Related

What's the point of using labeled statements in Java? [duplicate]

This question already has answers here:
Please explain the usage of Labeled Statements
(3 answers)
Closed 7 years ago.
I'm busy studying for my certification and I stumbled upon a concept I've never even heard before - "Labeled Statements". e.g:
'label' : 'statement'
L1: while(i < 0){
L2: System.out.println(i);
}
So my question is.. why? How is this useful and when would one want to use something like this?
The only use that I'm aware of is that you can use labels in break or continue statements. So if you have nested loops, it's a way to break out of more than one level at a time:
OUTER: for (x : xList) {
for (y : yList) {
// Do something, then:
if (x > y) {
// This goes to the next iteration of x, whereas a standard
// "continue" would go to the next iteration of y
continue OUTER;
}
}
}
As the example implies, it's occasionally useful if you're iterating over two things at once in a nested fashion (e.g. searching for matches) and want to continue - or if you're doing normal iteration, but for some reason want to put a break/continue in a nested for loop.
I tend to only use them once every few years, though. There's a chicken-and-egg in that they can be hard to understand because they're a rarely-used construct, so I'll avoid using labels if the code can be clearly written in another way.
It can be used to avoid the need for a "not found" flag.
FOUND: {
for(Type t: list)
if (t.isTrue())
break FOUND;
// handle not found.
}
This is perhaps a misuse of labels, but you can use them to break without a loop.
LABEL: {
if(condition)
break LABEL;
// do something
}
It can also be used to confuse people, which is a good reason to avoid it. ;)
http://www.google.com
while(true) break http;
I used to use those as comment statements :) Jokes aside, it is like the Go to statements in basic, which allows you to jump to a line of code, ie during a deep looping structure...
Usage:
scan: {
int c;
for (firstUpper = 0 ;
firstUpper < count ;
firstUpper += Character.charCount(c)) {
c = codePointAt(firstUpper);
if (c != Character.toLowerCase(c)) {
break scan;
}
}
return this;
}
Here is an example of inordinate break that is likely to be missed out by the rest of the replies. It allows to break a loop within switch{} statement:
loop: for(;;){
int c=in.read();
switch(c){
case -1:
case '\n':
break loop;
case 'a':
processACommand();
break;
case ...
default:
break;
}
}
I think that they are required so that you can write Fortran while pretending to write Java. Without them, the aphorism Real programmers write in Fortran whatever language they are using might be invalidated.
As other answers have stated, labels are a seldom used part of the Java language.
But in your case some other things should be considered:
The labels are quite "generic" and are in fact line numbers: L1, L2, ...
The labels are not used in the code.
You are studying material for a certification.
This means, that the L1, L2 labels are simply line numbers. I assume, that the text explaining the code refers to that line numbers. In the same way some books and papers enumerate all mathematical terms just for referencing them in the text or to make citations easier.

Is there something like goto in Java? [duplicate]

I'm confused about this. Most of us have been told that there isn't any goto statement in Java.
But I found that it is one of the keywords in Java. Where can it be used? If it can not be used, then why was it included in Java as a keyword?
James Gosling created the original JVM with support of goto statements, but then he removed this feature as needless. The main reason goto is unnecessary is that usually it can be replaced with more readable statements (like break/continue) or by extracting a piece of code into a method.
Source: James Gosling, Q&A session
The Java keyword list specifies the goto keyword, but it is marked as "not used".
It was in the original JVM (see answer by #VitaliiFedorenko), but then removed. It was probably kept as a reserved keyword in case it were to be added to a later version of Java.
If goto was not on the list, and it gets added to the language later on, existing code that used the word goto as an identifier (variable name, method name, etc...) 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.
The keyword exists, but it is not implemented.
The only good reason to use goto that I can think of is this:
for (int i = 0; i < MAX_I; i++) {
for (int j = 0; j < MAX_J; j++) {
// do stuff
goto outsideloops; // to break out of both loops
}
}
outsideloops:
In Java you can do this like this:
loops:
for (int i = 0; i < MAX_I; i++) {
for (int j = 0; j < MAX_J; j++) {
// do stuff
break loops;
}
}
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/_keywords.html
"The keywords const and goto are
reserved, even though they are not
currently used. "
So they could be used one day if the language designers felt the need.
Also, if programmers from languages that do have these keywords (eg. C, C++) use them by mistake, then the Java compiler can give a useful error message.
Or maybe it was just to stop programmers using goto :)
They are reserved for future use (see: Java Language Keywords)
The keywords const and goto are reserved, even though they are not currently used.
The reason why there is no goto statement in Java can be found in "The Java Language Environment":
Java has no goto statement. Studies illustrated that goto is (mis)used more often than not simply "because it's there". Eliminating goto led to a simplification of the language--there are no rules about the effects of a goto into the middle of a for statement, for example. Studies on approximately 100,000 lines of C code determined that roughly 90 percent of the goto statements were used purely to obtain the effect of breaking out of nested loops. As mentioned above, multi-level break and continue remove most of the need for goto statements.
An example of how to use "continue" labels in Java is:
public class Label {
public static void main(String[] args) {
int temp = 0;
out: // label
for (int i = 0; i < 3; ++i) {
System.out.println("I am here");
for (int j = 0; j < 20; ++j) {
if(temp==0) {
System.out.println("j: " + j);
if (j == 1) {
temp = j;
continue out; // goto label "out"
}
}
}
}
System.out.println("temp = " + temp);
}
}
Results:
I am here // i=0
j: 0
j: 1
I am here // i=1
I am here // i=2
temp = 1
It is important to understand that the goto construct is remnant from the days that programmers programmed in machine code and assembly language. Because those languages are so basic (as in, each instruction does only one thing), program control flow is done completely with goto statements (but in assembly language, these are referred to as jump or branch instructions).
Now, although the C language is fairly low-level, it can be thought of as very high-level assembly language - each statement and function in C can easily be broken down into assembly language instructions. Although C is not the prime language to program computers with nowadays, it is still heavily used in low level applications, such as embedded systems. Because C's function so closely mirrors assembly language's function, it only makes sense that goto is included in C.
It is clear that Java is an evolution of C/C++. Java shares a lot of features from C, but abstracts a lot more of the details, and therefore is simply written differently. Java is a very high-level language, so it simply is not necessary to have low-level features like goto when more high-level constructs like functions, for, for each, and while loops do the program control flow. Imagine if you were in one function and did a goto to a label into another function. What would happen when the other function returned? This idea is absurd.
This does not necessarily answer why Java includes the goto statement yet won't let it compile, but it is important to know why goto was ever used in the first place, in lower-level applications, and why it just doesn't make sense to be used in Java.
Because it's not supported and why would you want a goto keyword that did nothing or a variable named goto?
Although you can use break label; and continue label; statements to effectively do what goto does. But I wouldn't recommend it.
public static void main(String [] args) {
boolean t = true;
first: {
second: {
third: {
System.out.println("Before the break");
if (t) {
break second;
}
System.out.println("Not executed");
}
System.out.println("Not executed - end of second block");
}
System.out.println("End of third block");
}
}
No, goto is not used, but you can define labels and leave a loop up to the label. You can use break or continue followed by the label. So you can jump out more than one loop level. Have a look at the tutorial.
No, thankfully, there isn't goto in Java.
The goto keyword is only reserved, but not used (the same goes for const).
No, goto is not used in Java, despite being a reserved word. The same is true for const. Both of these are used in C++, which is probably the reason why they're reserved; the intention was probably to avoid confusing C++ programmers migrating to Java, and perhaps also to keep the option of using them in later revisions of Java.
Yes is it possible, but not as nice as in c# (in my opinion c# is BETTER!). Opinions that goto always obscures software are dull and silly! It's sad java don't have at least goto case xxx.
Jump to forward:
public static void main(String [] args) {
myblock: {
System.out.println("Hello");
if (some_condition)
break myblock;
System.out.println("Nice day");
}
// here code continue after performing break myblock
System.out.println("And work");
}
Jump to backward:
public static void main(String [] args) {
mystart: //here code continue after performing continue mystart
do {
System.out.println("Hello");
if (some_condition)
continue mystart;
System.out.println("Nice day");
} while (false);
System.out.println("And work");
}
Note that you can replace most of the benign uses of goto by
return
break
break label
throw inside try-catch-finally
As was pointed out, there is no goto in Java, but the keyword was reserved in case Sun felt like adding goto to Java one day. They wanted to be able to add it without breaking too much code, so they reserved the keyword. Note that with Java 5 they added the enum keyword and it did not break that much code either.
Although Java has no goto, it has some constructs which correspond to some usages of goto, namely being able to break and continue with named loops. Also, finally can be thought of as a kind of twisted goto.
To prohibit declarations of variables with the same name.
e.g.
int i = 0, goto;
It's very much considered one of those things you Do Not Do, but was probably listed as a reserved word to avoid confusion for developers.
http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-6.html#jvms-6.5.goto
If you have been told that there is no goto statement in Java you have been fooled. Indeed, Java consists two layers of 'source' code.
See the following link is shows all java reserved words and tells you what versions they where added.
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/_keywords.html
goto is reserved, even though it is not currently used, never say never however :)
I'm not a fan of goto either, as it usually makes code less readable. However I do believe that there are exceptions to that rule (especially when it comes to lexers and parsers!)
Of Course you can always bring your program into Kleene Normalform by translating it to something assembler-like and then write something like
int line = 1;
boolean running = true;
while(running)
{
switch(line++)
{
case 1: /* line 1 */
break;
case 2: /* line 2 */
break;
...
case 42: line = 1337; // goto 1337
break;
...
default: running = false;
break;
}
}
(So you basically write a VM that executes your binary code... where line corresponds to the instruction pointer)
That is so much more readable than code that uses goto, isn't it?
Of course it is keyword, but it is not used on level of source code.
But if you use jasmin or other lower level language, which is transformed to bytecode, then "goto" is there
Because although the Java language doesn't use it, JVM bytecode does.
goto is not in Java
you have to use GOTO
But it don't work correctly.in key java word it is not used.
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html
public static void main(String[] args) {
GOTO me;
//code;
me:
//code;
}
}

Is there a programming language with better approach for switch's break statements?

It's the same syntax in a way too many languages:
switch (someValue) {
case OPTION_ONE:
case OPTION_LIKE_ONE:
case OPTION_ONE_SIMILAR:
doSomeStuff1();
break; // EXIT the switch
case OPTION_TWO_WITH_PRE_ACTION:
doPreActionStuff2();
// the default is to CONTINUE to next case
case OPTION_TWO:
doSomeStuff2();
break; // EXIT the switch
case OPTION_THREE:
doSomeStuff3();
break; // EXIT the switch
}
Now, all you know that break statements are required, because the switch will continue to the next case when break statement is missing. We have an example of that with OPTION_LIKE_ONE, OPTION_ONE_SIMILAR and OPTION_TWO_WITH_PRE_ACTION. The problem is that we only need this "skip to next case" very very very rarely. And very often we put break at the end of case.
It's very easy for a beginner to forget about it. And one of my C teachers even explained it to us as if it was a bug in C language (don't want to talk about it :)
I would like to ask if there are any other languages that I don't know of (or forgot about) that handle switch/case like this:
switch (someValue) {
case OPTION_ONE: continue; // CONTINUE to next case
case OPTION_LIKE_ONE: continue; // CONTINUE to next case
case OPTION_ONE_SIMILAR:
doSomeStuff1();
// the default is to EXIT the switch
case OPTION_TWO_WITH_PRE_ACTION:
doPreActionStuff2();
continue; // CONTINUE to next case
case OPTION_TWO:
doSomeStuff2();
// the default is to EXIT the switch
case OPTION_THREE:
doSomeStuff3();
// the default is to EXIT the switch
}
The second question: is there any historical meaning to why we have the current break approach in C? Maybe continue to next case was used far more often than we use it these days ?
From this article, I can enumerate some languages that don't require a break-like statement:
Ada (no fallthrough)
Eiffel (no fallthrough)
Pascal (no fallthrough)
Go - fallthrough
Perl - continue
Ruby (no fallthrough)
VB, VBA, VBS, VB.NET (no fallthrough)
To be continued by someone else...
Your second question is pretty interesting. Assuming only C, I believe this decision keeps the language cohesive. Since break is a jump, it must be explicitly written.
Scala pattern matching I think is a huge improvement in these cases. :)
object MatchTest2 extends Application {
def matchTest(x: Any): Any = x match {
case 1 => "one"
case "two" => 2
case y: Int => "scala.Int"
}
println(matchTest("two"))
}
Sample from scala-lang.org
And VB .NET handles it a little more like how you expect it should work.
Select Case i
Case 1 to 3
DoStuff(i)
Case 4,5,6
DoStuffDifferently(i)
Case Is >= 7
DoStuffDifferentlyRedux(i)
Case Else
DoStuffNegativeNumberOrZero(i)
End Select
There is no fall through at all, without possibly using a Goto
Here is the answer:
http://en.wikipedia.org/wiki/Switch_statement
It's called fall-through statement (continue in the example) and it exists in the following languages:
Go, Perl, C#
In C# it won't compile without break or goto case statement (except when there's no pre-action).
PASCAL doesn't have fall-through
I think the answer to your question of why it is this way centers around two behaviors, both having to do with the generated assembly code from the C source.
The first is that in assembly, the current instruction is executed, and unless there is a jump or some other flow control instruction, the instruction at the next address will be executed. Performing a naive compile of the switch statement to assembly would generate code that would just start executing the first instruction, which would be to see if there was a matching condition...
The second related reason is the notion of a branch table or jump list. Basically the compiler can take what it knows about your value, and create some extremely efficient machine code for the same thing. Take for example a simple function like atoi that converts a string representation of a number and returns it in integer form. Simplifying things way down to support just a single digit, you could write some code similar to this:
int atoi(char c) {
switch (c) {
case '0': return 0;
case '1': return 1;
// ....
}
}
The naive compiler would perhaps just convert that to a series of if/then blocks, meaning a substantial amount of CPU cycles would be taken for the number 9, while 0 returns almost immediately. Using a branch table the compiler could emit some [psuedo] assembly that would immediately "jump" to the correct return clause:
0x1000 # stick value of c in a register
0x1004 # jump to address c + calculated offset
# example '0' would be 0x30, the offset in for this sample
# would always be 0x0FD8... thus 0x30 + 0x0FD8 = 0x1008
0x1008 # return 0
Apology: my assembly and C skills are quite rusty. I hope this helps clarify things.
0x
Hey, don't forget COBOL's EVALUATE:
EVALUATE MENU-INPUT
WHEN "0" PERFORM INIT-PROC
WHEN "1" THRU "9" PERFORM PROCESS-PROC
WHEN "R" PERFORM READ-PARMS
WHEN "X" PERFORM CLEANUP-PROC
WHEN OTHER PERFORM ERROR-PROC
END-EVALUATE.
Ada doesn't have fallthrough, and requires that all values are explicitly handled, or a "others" clause added to handle the rest.
SQL CASE statement also does not fallthrough.
XSLT has which does not fallthrough.
It seems to be C and derived languages that have the fallthrough. It's quite insidious, and the only real use I've seen is implementing duff's device.
http://www.adaic.org/whyada/intro4.html
Python doesn't have one at all.
Took some getting used to but I have some horrendous memories hunting through massive switch blocks back in my C# days. I'm much happier without it.
Although not exactly what you asked for, Groovy has a very powerful switch statement
The OP talks about "fall through", but very seldom have I ever been bit by that.
Many many times, however I have been bit by designs that are non-extensible. To wit, "switch (kbHit)" statements, with a few hundred keys in there, that are a maintenance nightmare, and a frequent location for "god methods", and giant piles of spaghetti-code.
Using switch is often a sign of poor object oriented programming. As another person answered, "2 uses of Switch in 48 source files", in one of his application, shows a programmer who does not rely heavily on this construct. From his metric, I surmise that he is probably at least a good structured programmer, and probably understands OOP/OOD as well.
OOP (not necessarily only C++) programmers, and even pure C users who do not have an object description technique forced upon them, could implement an "inversion of control" container that publishes a "key was hit" and allows subscribers to plug in their handlers for "on keyboard code x". This can make reading your code much easier.
Pure speculation, but:
I occasionally write C or Java in which I say something like:
switch (tranCode)
{
case 'A':
case 'D':
case 'R':
processCredit();
break;
case 'B':
case 'G':
processDebit();
break;
default:
processSpecial();
}
That is, I deliberately use fall-thru to let several values fire the same operation.
I wonder if this is what the inventors of C were thinking of when they created the SWITCH statement, that this would be the normal usage.
Tcl doesn't automatically fall through.
In object oriented languages you use the Chain of Responsibility pattern. How that is implemented can vary. What you are describing in your example, is mixing a state machine with behavior by abusing a switch statement. For your particular example a Chain of Responsibility pattern with the parameter that the chain evaluates being a State pattern, that mutates as it goes down the chain, would be the appropriate implementation.
languages are too much and I can't answer for sure that there's not such a language, provided it is a "derivative" of C in syntax, because other languages using different syntax and where the case does not "continue" naturally exist, e.g. Fortran. I don't know languages that uses an explicit "continue" to continue to the following case.
I believe it is historical reason due to the way such a case could be programmed at a "low level". Moreover the syntactical aspect of the case is that of a label, and break works like in loops, so you can imagine an equivalent like this:
if ( case == 1 ) goto lab1;
if ( case == 2 ) goto lab2;
if ( case == 3 ) goto lab3;
//...
default:
// default
goto switch_end;
lab1:
// do things
goto switch_end; // if break is present
lab2:
// do things, and follow to lab3
lab3:
// lab3 stuffs
goto switch_end;
//
...
switch_end: // past all labS.
More languages without a fallthough:
XSLT
JSTL
Algol
PL/1
Lima does it like this:
if someValue == ?1 ::
OPTION_ONE: fall
OPTION_LIKE_ONE: fall
OPTION_ONE_SIMILAR:
doSomeStuff1[]
;; the default is to EXIT the switch
OPTION_TWO_WITH_PRE_ACTION:
doPreActionStuff2[]
fall ;; fall through to the next case
OPTION_TWO:
doSomeStuff2[]
OPTION_THREE:
doSomeStuff3[]

Is there a goto statement in Java?

I'm confused about this. Most of us have been told that there isn't any goto statement in Java.
But I found that it is one of the keywords in Java. Where can it be used? If it can not be used, then why was it included in Java as a keyword?
James Gosling created the original JVM with support of goto statements, but then he removed this feature as needless. The main reason goto is unnecessary is that usually it can be replaced with more readable statements (like break/continue) or by extracting a piece of code into a method.
Source: James Gosling, Q&A session
The Java keyword list specifies the goto keyword, but it is marked as "not used".
It was in the original JVM (see answer by #VitaliiFedorenko), but then removed. It was probably kept as a reserved keyword in case it were to be added to a later version of Java.
If goto was not on the list, and it gets added to the language later on, existing code that used the word goto as an identifier (variable name, method name, etc...) 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.
The keyword exists, but it is not implemented.
The only good reason to use goto that I can think of is this:
for (int i = 0; i < MAX_I; i++) {
for (int j = 0; j < MAX_J; j++) {
// do stuff
goto outsideloops; // to break out of both loops
}
}
outsideloops:
In Java you can do this like this:
loops:
for (int i = 0; i < MAX_I; i++) {
for (int j = 0; j < MAX_J; j++) {
// do stuff
break loops;
}
}
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/_keywords.html
"The keywords const and goto are
reserved, even though they are not
currently used. "
So they could be used one day if the language designers felt the need.
Also, if programmers from languages that do have these keywords (eg. C, C++) use them by mistake, then the Java compiler can give a useful error message.
Or maybe it was just to stop programmers using goto :)
They are reserved for future use (see: Java Language Keywords)
The keywords const and goto are reserved, even though they are not currently used.
The reason why there is no goto statement in Java can be found in "The Java Language Environment":
Java has no goto statement. Studies illustrated that goto is (mis)used more often than not simply "because it's there". Eliminating goto led to a simplification of the language--there are no rules about the effects of a goto into the middle of a for statement, for example. Studies on approximately 100,000 lines of C code determined that roughly 90 percent of the goto statements were used purely to obtain the effect of breaking out of nested loops. As mentioned above, multi-level break and continue remove most of the need for goto statements.
An example of how to use "continue" labels in Java is:
public class Label {
public static void main(String[] args) {
int temp = 0;
out: // label
for (int i = 0; i < 3; ++i) {
System.out.println("I am here");
for (int j = 0; j < 20; ++j) {
if(temp==0) {
System.out.println("j: " + j);
if (j == 1) {
temp = j;
continue out; // goto label "out"
}
}
}
}
System.out.println("temp = " + temp);
}
}
Results:
I am here // i=0
j: 0
j: 1
I am here // i=1
I am here // i=2
temp = 1
It is important to understand that the goto construct is remnant from the days that programmers programmed in machine code and assembly language. Because those languages are so basic (as in, each instruction does only one thing), program control flow is done completely with goto statements (but in assembly language, these are referred to as jump or branch instructions).
Now, although the C language is fairly low-level, it can be thought of as very high-level assembly language - each statement and function in C can easily be broken down into assembly language instructions. Although C is not the prime language to program computers with nowadays, it is still heavily used in low level applications, such as embedded systems. Because C's function so closely mirrors assembly language's function, it only makes sense that goto is included in C.
It is clear that Java is an evolution of C/C++. Java shares a lot of features from C, but abstracts a lot more of the details, and therefore is simply written differently. Java is a very high-level language, so it simply is not necessary to have low-level features like goto when more high-level constructs like functions, for, for each, and while loops do the program control flow. Imagine if you were in one function and did a goto to a label into another function. What would happen when the other function returned? This idea is absurd.
This does not necessarily answer why Java includes the goto statement yet won't let it compile, but it is important to know why goto was ever used in the first place, in lower-level applications, and why it just doesn't make sense to be used in Java.
Because it's not supported and why would you want a goto keyword that did nothing or a variable named goto?
Although you can use break label; and continue label; statements to effectively do what goto does. But I wouldn't recommend it.
public static void main(String [] args) {
boolean t = true;
first: {
second: {
third: {
System.out.println("Before the break");
if (t) {
break second;
}
System.out.println("Not executed");
}
System.out.println("Not executed - end of second block");
}
System.out.println("End of third block");
}
}
No, goto is not used, but you can define labels and leave a loop up to the label. You can use break or continue followed by the label. So you can jump out more than one loop level. Have a look at the tutorial.
No, thankfully, there isn't goto in Java.
The goto keyword is only reserved, but not used (the same goes for const).
No, goto is not used in Java, despite being a reserved word. The same is true for const. Both of these are used in C++, which is probably the reason why they're reserved; the intention was probably to avoid confusing C++ programmers migrating to Java, and perhaps also to keep the option of using them in later revisions of Java.
Yes is it possible, but not as nice as in c# (in my opinion c# is BETTER!). Opinions that goto always obscures software are dull and silly! It's sad java don't have at least goto case xxx.
Jump to forward:
public static void main(String [] args) {
myblock: {
System.out.println("Hello");
if (some_condition)
break myblock;
System.out.println("Nice day");
}
// here code continue after performing break myblock
System.out.println("And work");
}
Jump to backward:
public static void main(String [] args) {
mystart: //here code continue after performing continue mystart
do {
System.out.println("Hello");
if (some_condition)
continue mystart;
System.out.println("Nice day");
} while (false);
System.out.println("And work");
}
Note that you can replace most of the benign uses of goto by
return
break
break label
throw inside try-catch-finally
As was pointed out, there is no goto in Java, but the keyword was reserved in case Sun felt like adding goto to Java one day. They wanted to be able to add it without breaking too much code, so they reserved the keyword. Note that with Java 5 they added the enum keyword and it did not break that much code either.
Although Java has no goto, it has some constructs which correspond to some usages of goto, namely being able to break and continue with named loops. Also, finally can be thought of as a kind of twisted goto.
To prohibit declarations of variables with the same name.
e.g.
int i = 0, goto;
It's very much considered one of those things you Do Not Do, but was probably listed as a reserved word to avoid confusion for developers.
http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-6.html#jvms-6.5.goto
If you have been told that there is no goto statement in Java you have been fooled. Indeed, Java consists two layers of 'source' code.
See the following link is shows all java reserved words and tells you what versions they where added.
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/_keywords.html
goto is reserved, even though it is not currently used, never say never however :)
I'm not a fan of goto either, as it usually makes code less readable. However I do believe that there are exceptions to that rule (especially when it comes to lexers and parsers!)
Of Course you can always bring your program into Kleene Normalform by translating it to something assembler-like and then write something like
int line = 1;
boolean running = true;
while(running)
{
switch(line++)
{
case 1: /* line 1 */
break;
case 2: /* line 2 */
break;
...
case 42: line = 1337; // goto 1337
break;
...
default: running = false;
break;
}
}
(So you basically write a VM that executes your binary code... where line corresponds to the instruction pointer)
That is so much more readable than code that uses goto, isn't it?
Of course it is keyword, but it is not used on level of source code.
But if you use jasmin or other lower level language, which is transformed to bytecode, then "goto" is there
Because although the Java language doesn't use it, JVM bytecode does.
goto is not in Java
you have to use GOTO
But it don't work correctly.in key java word it is not used.
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html
public static void main(String[] args) {
GOTO me;
//code;
me:
//code;
}
}

goto keyword in java [duplicate]

I'm confused about this. Most of us have been told that there isn't any goto statement in Java.
But I found that it is one of the keywords in Java. Where can it be used? If it can not be used, then why was it included in Java as a keyword?
James Gosling created the original JVM with support of goto statements, but then he removed this feature as needless. The main reason goto is unnecessary is that usually it can be replaced with more readable statements (like break/continue) or by extracting a piece of code into a method.
Source: James Gosling, Q&A session
The Java keyword list specifies the goto keyword, but it is marked as "not used".
It was in the original JVM (see answer by #VitaliiFedorenko), but then removed. It was probably kept as a reserved keyword in case it were to be added to a later version of Java.
If goto was not on the list, and it gets added to the language later on, existing code that used the word goto as an identifier (variable name, method name, etc...) 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.
The keyword exists, but it is not implemented.
The only good reason to use goto that I can think of is this:
for (int i = 0; i < MAX_I; i++) {
for (int j = 0; j < MAX_J; j++) {
// do stuff
goto outsideloops; // to break out of both loops
}
}
outsideloops:
In Java you can do this like this:
loops:
for (int i = 0; i < MAX_I; i++) {
for (int j = 0; j < MAX_J; j++) {
// do stuff
break loops;
}
}
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/_keywords.html
"The keywords const and goto are
reserved, even though they are not
currently used. "
So they could be used one day if the language designers felt the need.
Also, if programmers from languages that do have these keywords (eg. C, C++) use them by mistake, then the Java compiler can give a useful error message.
Or maybe it was just to stop programmers using goto :)
They are reserved for future use (see: Java Language Keywords)
The keywords const and goto are reserved, even though they are not currently used.
The reason why there is no goto statement in Java can be found in "The Java Language Environment":
Java has no goto statement. Studies illustrated that goto is (mis)used more often than not simply "because it's there". Eliminating goto led to a simplification of the language--there are no rules about the effects of a goto into the middle of a for statement, for example. Studies on approximately 100,000 lines of C code determined that roughly 90 percent of the goto statements were used purely to obtain the effect of breaking out of nested loops. As mentioned above, multi-level break and continue remove most of the need for goto statements.
An example of how to use "continue" labels in Java is:
public class Label {
public static void main(String[] args) {
int temp = 0;
out: // label
for (int i = 0; i < 3; ++i) {
System.out.println("I am here");
for (int j = 0; j < 20; ++j) {
if(temp==0) {
System.out.println("j: " + j);
if (j == 1) {
temp = j;
continue out; // goto label "out"
}
}
}
}
System.out.println("temp = " + temp);
}
}
Results:
I am here // i=0
j: 0
j: 1
I am here // i=1
I am here // i=2
temp = 1
It is important to understand that the goto construct is remnant from the days that programmers programmed in machine code and assembly language. Because those languages are so basic (as in, each instruction does only one thing), program control flow is done completely with goto statements (but in assembly language, these are referred to as jump or branch instructions).
Now, although the C language is fairly low-level, it can be thought of as very high-level assembly language - each statement and function in C can easily be broken down into assembly language instructions. Although C is not the prime language to program computers with nowadays, it is still heavily used in low level applications, such as embedded systems. Because C's function so closely mirrors assembly language's function, it only makes sense that goto is included in C.
It is clear that Java is an evolution of C/C++. Java shares a lot of features from C, but abstracts a lot more of the details, and therefore is simply written differently. Java is a very high-level language, so it simply is not necessary to have low-level features like goto when more high-level constructs like functions, for, for each, and while loops do the program control flow. Imagine if you were in one function and did a goto to a label into another function. What would happen when the other function returned? This idea is absurd.
This does not necessarily answer why Java includes the goto statement yet won't let it compile, but it is important to know why goto was ever used in the first place, in lower-level applications, and why it just doesn't make sense to be used in Java.
Because it's not supported and why would you want a goto keyword that did nothing or a variable named goto?
Although you can use break label; and continue label; statements to effectively do what goto does. But I wouldn't recommend it.
public static void main(String [] args) {
boolean t = true;
first: {
second: {
third: {
System.out.println("Before the break");
if (t) {
break second;
}
System.out.println("Not executed");
}
System.out.println("Not executed - end of second block");
}
System.out.println("End of third block");
}
}
No, goto is not used, but you can define labels and leave a loop up to the label. You can use break or continue followed by the label. So you can jump out more than one loop level. Have a look at the tutorial.
No, thankfully, there isn't goto in Java.
The goto keyword is only reserved, but not used (the same goes for const).
No, goto is not used in Java, despite being a reserved word. The same is true for const. Both of these are used in C++, which is probably the reason why they're reserved; the intention was probably to avoid confusing C++ programmers migrating to Java, and perhaps also to keep the option of using them in later revisions of Java.
Yes is it possible, but not as nice as in c# (in my opinion c# is BETTER!). Opinions that goto always obscures software are dull and silly! It's sad java don't have at least goto case xxx.
Jump to forward:
public static void main(String [] args) {
myblock: {
System.out.println("Hello");
if (some_condition)
break myblock;
System.out.println("Nice day");
}
// here code continue after performing break myblock
System.out.println("And work");
}
Jump to backward:
public static void main(String [] args) {
mystart: //here code continue after performing continue mystart
do {
System.out.println("Hello");
if (some_condition)
continue mystart;
System.out.println("Nice day");
} while (false);
System.out.println("And work");
}
Note that you can replace most of the benign uses of goto by
return
break
break label
throw inside try-catch-finally
As was pointed out, there is no goto in Java, but the keyword was reserved in case Sun felt like adding goto to Java one day. They wanted to be able to add it without breaking too much code, so they reserved the keyword. Note that with Java 5 they added the enum keyword and it did not break that much code either.
Although Java has no goto, it has some constructs which correspond to some usages of goto, namely being able to break and continue with named loops. Also, finally can be thought of as a kind of twisted goto.
To prohibit declarations of variables with the same name.
e.g.
int i = 0, goto;
It's very much considered one of those things you Do Not Do, but was probably listed as a reserved word to avoid confusion for developers.
http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-6.html#jvms-6.5.goto
If you have been told that there is no goto statement in Java you have been fooled. Indeed, Java consists two layers of 'source' code.
See the following link is shows all java reserved words and tells you what versions they where added.
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/_keywords.html
goto is reserved, even though it is not currently used, never say never however :)
I'm not a fan of goto either, as it usually makes code less readable. However I do believe that there are exceptions to that rule (especially when it comes to lexers and parsers!)
Of Course you can always bring your program into Kleene Normalform by translating it to something assembler-like and then write something like
int line = 1;
boolean running = true;
while(running)
{
switch(line++)
{
case 1: /* line 1 */
break;
case 2: /* line 2 */
break;
...
case 42: line = 1337; // goto 1337
break;
...
default: running = false;
break;
}
}
(So you basically write a VM that executes your binary code... where line corresponds to the instruction pointer)
That is so much more readable than code that uses goto, isn't it?
Of course it is keyword, but it is not used on level of source code.
But if you use jasmin or other lower level language, which is transformed to bytecode, then "goto" is there
Because although the Java language doesn't use it, JVM bytecode does.
goto is not in Java
you have to use GOTO
But it don't work correctly.in key java word it is not used.
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html
public static void main(String[] args) {
GOTO me;
//code;
me:
//code;
}
}

Categories