Equivalent of goto of c++ in Java in a specific scenario - java

I am replacing a old C++ code with Java:I know there is no equivalent of goto in java as it causes many surprising errors and unintended loop terminations.
C++ code: //I have skipped the actual code
for(//some condition){
if (excl(grds[i],0))
{
//do something
goto breakout;
}
//some more code
breakout:
//rest of the code
}//end of for loop
Java representation:
for(//some condition){
if (excl(grds[i],0))
{
//do something
}
else
{
//some more code
}
//rest of the code
}//end of for loop
I have kept the "some more code" part in the else section so I guess it will function same as the breakout. When the if condition is true it wont go to the else part and rest of the code will be executed as usual. I guess break or continue wont serve the purpose as we need to any way run the rest of the code section for all iterations.
Is this the correct way of representing this C++ code in Java?

Yes, that would be the better way — in Java, and in C++.

This is probably the easiest way:
for(//some condition){
if(!excl(grds[i],0))
{
//some more code
}
//rest of the code
}//end of for loop
You really shouldn't be using goto in C++. As a side note, in Java you can have named blocks that can be used to simulate a goto:
namedBlock:
{
// some code
if(condition)
break namedBlock;
// some more code
}
// rest of the code
But this is awful practice. Don't do it. Forget I even mentioned it ;)

for(//some condition){
if (!(excl(grds[i],0)))
{
//some more code
}
//rest of the code
}//end of for loop
Edit: after your clarification, the way you did it is fine.
Why can't you have it like this?
In your C++ code, //some more code is only executed when the condition is false and the //rest is always executed. So put that in the if.

Yes.
To be more precise, that's the correct best way of representing that code in C++ as well. Why use goto instead of a simple if?

This is a hack
for(//some condition){
do { // note this *do*
if (excl(grds[i],0))
{
break; // out of do/while
}
//some more code
}
while(false); // do only once
//rest of the code
}//end of for loop

I'm sure people will hate me for this, but you can get closer to the goto statement in Java than the if/else example. For instance, you can do:
for(/*some condition*/){
breakout: {
if (excl(grds[i],0)) {
break breakout; //this will jump to the end of the "breakout" block
}
//some more code
}
//rest of the code
}
Of course, this is not an example of good Java coding style, and just because this can be done doesn't mean it should be done. Really you should stick with the if/else.

There are occasions, very rare occasions, when using goto is exactly the right choice in C++. The example shown is not one of them. This is a goto that should never have been used, period. A goto has zero reason for existence if you can eliminate the goto with no additional variables, no increase in the complexity.
Some valid uses of goto in C++ can be easily eliminated in Java.
C and C++ do not have a way to break or continue out of a nested loop. Java does. When the target of a goto is immediately before some close brace, change the goto label with continue label. When the target of a goto is immediately after some close brace, change the goto label with break label. (The label statement may need to be moved around.)
Some C++ code uses goto in lieu of throw for local error handling / local error recovery. C++ exceptions have a pretty stiff performance penalty. If the code is being converting to Java it's kinda obvious that performance is not an issue. Use Java exceptions for this kind of goto.

Related

Is there a Java built-in construct like vb.net's Do Until Loop?

I am trying to make my code more readable and so it would be useful to use the following (or equivalent)
do
{
...
}
until(Display.isCloseRequested())
rather than
do
{
...
}
while(!Display.isCloseRequested())
but I can't seem to find something like this.
Yes, I don't like the 'java convention' of having the opening brace on the same line as the statement and the final statement on the same line as the closing brace. I prefer that code style.
No, Java doesn't have a do-until loop construct or similar. Just do-while with the opposite test as you indicated in the question, for, and while. All use "positive" tests (loop continues while test is true).
More in the JLS:
Control flow statements
for
while and do-while
If you really want the until syntax, you can cheat a little and create an until() method that negates a boolean expression.
For example...
do {
// something
} while (
until(Display.isCloseRequested())
);
...
public static boolean until(boolean condition) {
return !condition;
}
You can statically import the until method whenever you want to use it.
Although this introduces some issues:
It doesn't look very pretty.
It is unconventional and can cause confusion.

Is there a way to ignore the 'Unreachable statement' error?

Is it possible to somehow ignore this error? I find it much easier to just put return in front of the code I don't want to run than to comment it (when the comments overlap and behave badly)...
No. It's a compile time error. So you must get rid of it before running your class.
What I usually do is put a fake if statement in front of it. Something like:
if(true)
return;
// unwanted code follows. no errors.
i++;
j++;
With this code, you will not get a Unreachable statement error. And you will get what you want.
33. if (1==1) return;
34. System.out.println("Hello world!");
It works in other languages too. But ByteCode without row 34.
It isn't possible to ignore this error since it is an error according to the Java Language Specification.
You might also want to look at this post: Unreachable code error vs. dead code warning in Java under Eclipse?
If you want disable/enable certain piece of code many times trick from old C may help you:
some_code();
more_code();
// */
/*
some_code();
more_code();
// */
Now you need only to write /* at the beginning
you have to fix that unreachable code.
public void display(){
return; //move the return statement to appropriate place
int i;
}
compiler will not compile your source code.
you have to take care of your source code that every line is reachable to compiler.

Skipping to the beginning of a for loop in a Scala program

In a for loop in my Scala code, i want to skip to the beginning of the loop and not execute following statements if a particular condition is true. In Java i can use 'continue' for doing this. But 'continue' does not seem to work in Scala.
So how can i skip to the beginning of my loop in a Scala program ?
Please Help
Thank You.
First, your best option is usually to avoid that sort of construct anyway, and try to use higher-level methods instead (e.g. you can often do xs.map(doSomeStuff).filter(condition).foreach(doConditionalStuff)). This isn't always practical, but it is far more often than you might initially suspect. Still, the issue remains for those cases where continue is useful: a very long series of guards within a long code block that cannot be logically broken into pieces.
continue is a difficult language construct for a language with anonymous functions. One reason is practical: the anonymous function is a function, and you can't easily go back to some loop that's calling it just by executing a jump. Another reason is conceptual: if you're in a map method, which itself is a kind of loop, where exactly should the continue take you back to the beginning of?
Rather than dealing with these awkward cases, Scala provides (as a library function, based upon exceptions) a breakable construct that explicitly specifies where you want to break to:
import scala.util.control.Breaks._
breakable {
for (i <- 1 to 10) {
if (i>3) break
println(i)
}
}
But because this is a generic construct, you can use it inside the for loop also:
import scala.util.control.Breaks._
for (i <- 1 to 10) {
breakable {
if ((i%2)==0) break
println(i)
}
}
You can even break to multiple levels if you create your own break classes. Here's an example of simulating a for loop with both break and continue:
val outer,inner = new scala.util.control.Breaks
outer.breakable {
for (i <- 1 to 10) {
inner.breakable {
if ((i%2)==0) inner.break
if (i>3) outer.break
println(i)
}
}
}
And if you use this pattern a lot, you can change your imports to make it nicer:
// Do this once at the top of the file
import scala.util.control.Breaks._
object Continued extends scala.util.control.Breaks {}
import Continued.{break=>continue, breakable=>continuing}
// Now every time you need it:
breakable{ for (i <- 1 to 10) continuing {
if ((i%2)==0) continue
if (i>3) break
println(i)
}}
It is a bit more work to type if you really need that functionality, but given how nonsensical breaks and continues are in the context of the other very useful functionality that Scala has, it's not a bad compromise.
If you're using Scala 2.7, from http://www.scala-lang.org/node/257
These keywords are not included in Scala 2.7, and must be implemented in a different way. For break, the simplest thing to do is to divide your code into smaller methods and use the return to exit early. For continue, a simple approach is to place the skipped-over parts of a loop into an if.
Scala 2.8 will include break, but not continue.
If you're using Scala 2.8
import util.control.Breaks._
// for continue, write this somewhere in your program
val continue = new Breaks
/* use like */
Breaks.breakable {
for (i <- 1 to 10)
continue.breakable { if (i % 2 == 0) continue.break; println(i); if (i == 7) Breaks.break }
}
//source http://daily-scala.blogspot.com/2010/04/breaks.html
Note that normally needing break and continue means that you aren't being as functional as Scala would like you to be.

Why does Java allow for labeled breaks on arbitrary statements?

I just learned today that the following Java code is perfectly legal:
myBlock: {
/* ... code ... */
if (doneExecutingThisBlock())
break myBlock;
/* ... more code ... */
}
Note that myBlock isn't a loop - it's just a block of code I've delimited with curly braces.
This seems like a rather strange feature to have. It means that you can use a named break to break out of an if statement or anonymous block, though you can't normally use a break statement in these contexts.
My question is this: is there a good reason for this design decision? That is, why make it so that you can only break out of certain enclosing statements using labeled breaks but not regular breaks? And why allow for this behavior at all? Given how (comparatively) well-designed Java is as a language I would assume there's a reason for this, but I honestly can't think of one.
It is plausible that this was done for simplicity. If originally the labeled break can only break loop statements, then it should be immediately clear to language designer that the restriction isn't necessary, the semantics work the same for all statements. For the economics of the language spec, and simpler implementation of compilers, or just out of the habit towards generality, labeled break is defined for any statement, not just loop statements.
Now we can look back and judge this choice. Does it benefit programmers, by giving them extra expression power? Seems very little, the feature is rarely used. Does it cost programmers in learning and understanding? Seems so, as evidenced by this discussion.
If you could go back time and change it, would you? I can't say I would. We have a fetish for generality.
If in a parallel universe it was limited to loop statements only, there is still a chance, probably much smaller, that someone posts the question on stackoverflow: why couldn't it work on arbitrary statements?
Think of it as a return statement that returns from the block instead of from the entire function. The same reasoning you apply to object to break being scattered anywhere can also be applied to return being allowed anywhere except at the end of a function.
The issue with goto is that it can jump forward, past code. A labeled break cannot do that (it can only go backwards). IIRC C++ has to deal with goto jumping past code (it is been over 17 years since I cared about that though so I am not sure I am remembering that right).
Java was designed to be used by C/C++ programmers, so many things were done to make it familiar to those developers. It is possible to do a reasonable translation from C/C++ to Java (though some things are not trivial).
It is reasonable to think that they put that into the language to give C/C++ developers a safe goto (where you can only go backwards in the code) to make it more comfortable to some programmers converting over.
I have never seen that in use, and I have rarely seen a labeled break at all in 16+ years of Java programming.
You cannot break forward:
public class Test
{
public static void main(final String[] argv)
{
int val = 1;
X:
{
if(argv.length == 0)
{
break X;
}
if(argv.length == 1)
{
break Y; <--- forward break will not compile
}
}
val = 0;
Y:
{
Sysytem.out.println(val); <-- if forward breaks were allowed this would
print out 1 not 0.
}
}
}
Why make it so that you can only break out of certain enclosing statements using labeled breaks but not regular breaks
Consider:
while (true) {
if (condition) {
break;
}
}
If the break did as you suggest, this code would perform unexpectedly. Breaks would become a lot more difficult to use.
And why allow for this behavior at all?
I don't use it, but it is a feature and allows for certain unique control-flow constructs. I'd ask you, why not allow it?
is there a good reason for this design decision?
Yes. Because it works.
In the labelled break case, the fact that you don't need to be inside a loop or switch lets you to express things that are harder to express in other ways. (Admittedly, people rarely do use labelled break this way ... but that's not a fault of the language design.)
In the unlabelled break case, the behavior is to break out of the innermost enclosing loop or switch. If it was to break out of the innermost enclosing statement, then a lot of things would be much harder to express, and many would probably require a labelled block. For example:
while (...) {
/* ... */
if (something) break;
/* ... */
}
If break broke out of the innermost enclosing statement, then it wouldn't break out of the loop.
There is another possible reason / rationale. Remember that Java was a brand new language and a relatively early adopter of exceptions and exception handling.
Consider this:
try {
/* ... code ... */
if (doneExecutingThisBlock())
throw new OuttaHere();
/* ... more code ... */
} catch (OuttaHere e) {
/* do nothing */
}
According to the dogma, that is bad code. You shouldn't use exceptions for "normal" flow control.
(Pragmatically, that it also very inefficient due to the overheads of exception creation and handling. Exceptions performance was improved significantly in Java 8, I think, but that was ~20 years later.)
Now imagine that you are a language designer, and you feel that you have to provide an alternative to the "exceptions as flow control" anti-pattern. The "break to label" construct does exactly that. Compare the above with the example in the question.
In hindsight, this is unnecessary. The above can be done in other ways; i.e. without labelled break. In practice this construct is used so rarely that many (maybe most) programmers don't even know it exists in Java.
The ability to leave a sequence of statements has been implemented in several programming languages before Java. Two examples:
Algol-68 had exit to terminate the execution of the smallest closed-clause (very loosely speaking, a begin ... end sequence).
BLISS had labelled BEGIN … END blocks, with a LEAVE statement to terminate execution.
Implementations with labels (as in Java) are more flexible in that they can exit nested blocks (or compound statements, or whatever you call them in your language of choice); without the label, you're limited to exiting a single "level" only.
Answering the direct question, "why" -- because it's been found to be a useful construct in other, prior, languages.
Adding to Stephen C's answer, if (something) you cannot break out of a nested loop. These situations do happen in numerical algorithms. One simple example here - you cannot break out of the i-loop without the named for. Hope this helps.
public class JBreak {
private int brj;
public JBreak (String arg) {
brj = Integer.parseInt (arg);
}
public void print () {
jbreak:
for (int i = 1 ; i < 3 ; i++) {
for (int j = 0 ; j < 5 ; j++) {
if ((i*j) == brj)
break jbreak;
System.out.println ("i,j: " + i + "," + j);
}}}
public static void main (String[] args) {
new JBreak(args[0]).print();
}}
It's the "structured" equivalent to a goto, useful in certain circumstances.
I quite often use such a label create named sub-blocks in a method to tightly limit scope of variables or to simply label a block of code which is not appropriate to break out into a separate function. That is, I use it to label a block so that the code structure around braces is preserved. Here's an example in C for a JNI call, and I do the same in Java:
JNIEXPORT void JNICALL Java_xxx_SystemCall_jniChangePassword(JNIEnv *jep, jobject thsObj,
jlong handle, jbyteArray rndkey, jbyteArray usrprf, jbyteArray curpwd, jbyteArray newpwd, jint pwdccs, jint tmosec) {
Message rqs,rpy;
thsObj=thsObj;
SetupRequest: {
memset(&rqs,0,sizeof(rqs));
setOpcode(&rqs,"CHGPWD");
if(!setField(mFldAndLen(rqs.rnd ),null ,jep,rndkey,"Random Key")) {
return;
}
if(!setField(mFldAndLen(rqs.dta.chgpwd.user ),&rqs.dta.chgpwd.userLen ,jep,usrprf,"User Profile")) {
return;
}
if(!setField(mFldAndLen(rqs.dta.chgpwd.curPass),&rqs.dta.chgpwd.curPassLen,jep,curpwd,"Cur Password")) {
return;
}
if(!setField(mFldAndLen(rqs.dta.chgpwd.newPass),&rqs.dta.chgpwd.newPassLen,jep,newpwd,"New Password")) {
return;
}
rqs.dta.chgpwd.ccsid=pwdccs;
}
...
The break statement terminates the labeled statement; it does not transfer the flow of control to the label. Control flow is transferred to the statement immediately following the labeled (terminated) statement.
It seems to be useful to exit nested loops. See http://download.oracle.com/javase/tutorial/java/nutsandbolts/branch.html
It's semantically the same as is there a equivalent of Java's labelled break in C# or a workaround

Java for-loop, do i need continue statement here?

Consider this code:
if (int a == 0) {
System.out.println("hello");
continue;
}
This if is part of a for loop in java. What is the significane of continue statement here? I know continue is the opposite of break so that it wont break out of the loop rather just skip that iteration for anything below it. But in case it is inside an if statement, do I really need it like this?
No, you don't need to use continue there, you can use an else block instead:
if (a == 0) {
System.out.println("hello");
} else {
// The rest of the loop body goes here.
}
Which is better is a style issue. Sometimes one is better, sometimes the other - it depends on what the typical flow should be and which flow you want to emphasize in the code.
If this is the last statement of the for loop - no, you don't need it. Otherwise you need it to skip everything below the if-clause. If you don't want to skip it, then don't use continue.
Here is an explanation with examples of what continue is doing.
continue means that the statements below the if block won't work. If this is the behavior you need, you should continue. Otherwise it is not needed.

Categories

Resources