"unreachable statement" when trying to compile a "while" statement - java

I'm new to Java and working through some coursework. However, on the following piece of code I'm getting the error "Unreachable statement" when trying to compile. Any pointers as to what I'm doing wrong?
public String getDeliveredList() {
int count = 0;
while (count < deliveredList.size()){
return ("Order # " + count + deliveredList.get(count).getAsString());
count++;
}
}

Once you've returned from the function, logically it can no longer execute anything after that point -- the count++ statement will never be reached.
while (count < deliveredList.size()){
// function always ends and returns value here
return ("Order # " + count + deliveredList.get(count).getAsString());
// this will never get run
count++;
}

If you have returned from a function then any statement after the point from where the function returned are basically unreachable statements and the compiler will issue an error on such statements.
However the following code will not issue an error inspite of statements written after return
void max(int a,int b)
{
if(a>b)
{
System.out.println(a+" is greater");
return;
}
System.out.println(b+" is greater");
return;
}
This is because the first return statement is written within a nested scope and not immediately visible in the function scope. The program execution will only pass through first return statement when a>b. If it is not so then that block of codes is never executed. So in spite of having statements after return, the code is compile-able;

Related

Compilation error in BlueJ- if else with return statement

I am using BlueJ IDE to write java programs.
I have a method with String return type. I have put the return statements within if-else, such that if the boolean variable "flag" has true value, then one value is returned, while if the value is false, another value is returned.
Now, the problem is that BlueJ asks for another return statement even after this, as shown below.
If I give another return after if-else, it works.
Why is this happening? I had learnt that there can be no statements after the return statement. So, why is the compiler asking for another return statement?
If someone wants the code for cut-paste purposes, here it is. This code is meant to convert binary numbers to their decimal equivalents, including fractions, but no negative numbers.
public class Conversions{
protected String Binary_Decimal(String str){
int a = str.indexOf('.');
boolean flag = false;
if (a == -1){
str += ".0";
a = str.indexOf('.');
flag = true;
}
String bd = str.substring(0, a);
String ad = str.substring(a + 1);
a = 0;
double num = 0;
for (int i = bd.length() - 1; i >= 0; i--){
num += Math.pow(2, a) * Integer.parseInt(Character.toString(str.charAt(i)));
a++;
}
if (flag == true){
return Integer.toString((int) num);
}
else if (flag == true) {
a = -1;
for (int i = 0; i < ad.length(); i++){
num += Math.pow(2, a) * Integer.parseInt(Character.toString(str.charAt(i)));
a--;
}
return String.valueOf(num);
}
return String.valueOf(num); //<-- WHY DOESN'T IT RUN WITHOUT THIS EXTRA return?
}
}
Here, str is the string that is input by the user using a different method Input().
The issue is that you wrote an if - else as an if - else if. The compiler does not understand or care that the two conditions you have are mutually exclusive and therefore cover all cases. Given how you wrote the branches, you need an explicit else or a catchall return for the compiler to be assured that the function always returns a String.
This is one example of why it is a bad idea to explicitly spell out the else when you have a set of conditions. The more important reason being that your if will often contain something much more complex and you might not negate it properly.
Delete the second ELSE IF clause and put the block directly after the first return statement, and consider that flag is a boolean. As follows:
if (flag) return Integer.toString((int) num);
a=-1;
for(....){
....
}
return String.valueOf(num);
In this way, the compiler should not notify you that error.
So, why is the compiler asking for another return statement?
Because you are missing a default return statement.
What if none of the conditions you have satisfied ? There must be something return default right ? That is what the issue is. That is why it is getting compiled when you uncomment that line.
Or even , you have an else statement, your program will have at least one satisfied return and it gets compiled too. Try it.
I had learnt that there can be no statements after the return statement.
This statement comes with some conditions. You have the return statement inside the if condition. So if your expression is not true, there is no way that the return gets execute.

Compiler can't find variable in method with for,if/else return statement

I have a method, which keeps giving me compilation errors. At first I had a return statement for the if and else statements. I couldn't get it to work with 2 return statements, so I changed it into what I have now.
The error message now says that it can't find variable 'x'. I put the return statement inside the previous set of {}, and that still never worked. So I'm not sure if I have to completely redesign my method, or if this is a simple fix.
public static boolean equalN(int [] holdN){
for(int i=0;i<=holdN.length;i++){
int k=1;
boolean x;
if(holdN[i]==holdN[k]){
k++;
x=true;
}
else{
x=false;
}
}
return x;
}
The reason you cannot return x at the end of the method is that it is defined inside the loop, so its scope ends before you want to return it.
The same applies to variable k; good news is that you do not need either one of them.
At first I had a return statement for the if and else statements.
You can make it work with two return statements:
First return statement should be inside the if: once you detect the item that your loop is looking for, return true
Second return statement is at the end of the method, after the end of the loop. The only way to reach that point is for the loop to never return from the middle, which means that no item has been found. Hence, you return false.
Variable scoping is your problem here:
for(int i=0;i<=holdN.length;i++){
...
boolean x;
// x exists and is valid here
...
}
// but x doesn't exist here
return x; // this will fail compilation
}
To solve your compilation problem, you should move the declaration of x above the for loop.
boolean x;
for(int i=0;i<=holdN.length;i++){
...
}
return x;
}
For further explanation, see this SO question about variable scoping.

Eclipse doesnt want to compile code in java

here is part of my code:
My eclipse is saying that i need to put a return statment. Why? I have it already, and this loop will always find at least one thread who is alive and return i, so it should end the function and return integer. Would be grateul for help.
public int SB(int dealer,int PL){ //
boolean NotFound = true;
int i;
if(dealer != PL-1)
i=dealer+1;
else
i=0;
while(NotFound){
if(TH[i].isAlive())
return i;
else{
if(i < PL-1)
i++;
else
i=0;}
}
}
You method is declared to return an int value. This means you are obligated to always return an int value, not just in your
if(TH[i].isAlive())
return i;
statement.
In your case, you return a value if a thread inside the TH array is alive.
What you can do is return an error value at the end of your method that will only happen if no threads inside TH are alive.
For example, you can add this statement at the end of your method:
return -1;
This part of the code will only be reached if your loop runs full iteration. Even if you know there will always be an alive thread and this part of the code will actually never be reached, you need to put it there to humor the compiler.
Also, your loop condition NotFound is never updated inside your loop. This means you have an infinite loop in case no threads inside TH are alive. You don't really need that variable at all. What you can do is change the loop condition to something like:
while(i < TH.length)
Or, as it seems the variable PL is the length of TH, you can put:
while(i < PL)
This would also protect you from an ArrayIndexOutOfBoundsException in case i goes beyond the length of TH
Your return is buried in an if statement. What if the if never becomes true? You must have a default return statement somewhere, perhaps as the bottom of your method or in an else block.

Does "return" stop the execution of a method?

I have programmed a method in the following way:
if (something) {
return 1;
}
the rest of the code
It seems to me that the method returns 1 and then execute the rest of the code. Can it be the truth? Doesn't return stops the execution of the code. It it is not, how can I force a method to stop?
ADDED
Here is the code (as requested):
for (int i=availableTime; i>0; i=i-1) {
final int sec = i;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
String lbl = "<html>";
lbl += "</html>";
timeLeftLabel.setText(lbl);
}
});
try {Thread.sleep(1000);} catch (InterruptedException e) {}
parameterFromClientsListener = clientsListener.getValue(userName,parameterToGet);
if (!parameterFromClientsListener.equals("null")) {
output = parameterFromClientsListener;
game.log.fine(userName + " set (by button) " + parameterToGet + " to be equal to " + output + " . [IMPORTANT]");
return output;
}
}
game.log.fine("The partner selection phase is expired.");
// This code is executed if the Submit button was not pressed and the time run out.
if (parameterToGet.equals("partner")) {
tellMyChoice(parameterToGet, this.partnerFromForm, "timer of" + field);
output = this.partnerFromForm;
}
game.log.fine(parameterToGet + " was submitted by timer (not by OK button).");
} else {
output = parameterFromClientsListener;
}
game.log.fine(userName + " set (by timer)" + parameterToGet + " to be equal to " + output + " . [IMPORTANT]");
return output;
}
I run this code two times. In every case I generate a log-file. In both log files I see "set (by button)" statement (which is straight before the return). But the problem is that in the second log file I do see "timer of" statement. Which should not be reached if the "set (by button)" is reached. How can it be? I need to mention that "set (by button)" and "timer of" do not occur anywhere else in my code (they occur only once).
ADDED 3
As you can see from the code I do not have the finally statement.
This is not true, the return statement will stop any following code. (With the only exception being that the return statement is in a try{} block that has a finally{} block afterwards.
if(0==0){
return;
}
System.out.println("This will not print.");
return does end the execution of the method. There is one exception: the finally block. In the following case, 2 would be returned
public int foo() {
try {
return 1;
} finally {
return 2;
}
}
Return does indeed end the execution of a method. Check Your other assumptions. Maybe something in other parts of code isn't working as You are assuming.
Does return stops the execution of the code
well, almost.
Once a return is encountered, the method execution is stopped, and the control is passed to the calling method, after executing any finally clauses.
int add(int a, int b)
{
try{
if(a == 0)
{
return b;
}
if(b == 0)
{
return a;
}
return a+b;
}
finally
{
System.out.println("Finally");
}
}
In the above code, is the function is called as add(0, 1), "Finally" will still be printed.
How can I force a method to stop?
OR What are the other ways of exiting from a method?
Exceptions
You write
if (!parameterFromClientsListener.equals("null")) {
output = parameterFromClientsListener;
game.log.fine(userName + " set (by button) " + parameterToGet + " to be equal to " + output + " . [IMPORTANT]");
return output;
}
You are comparing the string (or whatever) with the string "null", and return if they are different. Do you really want to do this, and not parameterFromClientsListener != null?
(Though that should not be a big difference, as long as parameterFromClientsListener is neither null nor "null", and if it is null, your version would give a NullPointerException.)
Do you actually get the entry in your log file? If so, you should also get the return.
I wanted to understand how the observed behavior can be possible. In more details, I saw a "paradoxical" behavior. In my log files I saw output of the line which happens before the return as well as the output produced by the code after the return. So, I assumed that the return does not stop the execution of the program. As it has been correctly mentioned here by other "answerers" this assumption is wrong. The explanation of the behavior is trivial. My program run the shown code several times. The first time it reaches the return statement, the second time it passes it (because the return is in the if statement). So, it is why IO have the both statements in the log file.

Difference between Return and Break statements

How does a return statement differ from break statement?.
If I have to exit an if condition, which one should I prefer, return or break?
break is used to exit (escape) the for-loop, while-loop, switch-statement that you are currently executing.
return will exit the entire method you are currently executing (and possibly return a value to the caller, optional).
So to answer your question (as others have noted in comments and answers) you cannot use either break nor return to escape an if-else-statement per se. They are used to escape other scopes.
Consider the following example. The value of x inside the while-loop will determine if the code below the loop will be executed or not:
void f()
{
int x = -1;
while(true)
{
if(x == 0)
break; // escape while() and jump to execute code after the the loop
else if(x == 1)
return; // will end the function f() immediately,
// no further code inside this method will be executed.
do stuff and eventually set variable x to either 0 or 1
...
}
code that will be executed on break (but not with return).
....
}
break is used when you want to exit from the loop, while return is used to go back to the step where it was called or to stop further execution.
No offence, but none of the other answers (so far) has it quite right.
break is used to immediately terminate a for loop, a while loop or a switch statement. You can not break from an if block.
return is used the terminate a method (and possibly return a value).
A return within any loop or block will of course also immediately terminate that loop/block.
You won't be able to exit only from an if condition using either return or break.
return is used when you need to return from a method after its execution is finished when you don't want to execute the rest of the method code. So if you use return, then you will not only return from your if condition, but also from the whole method.
Consider the following method:
public void myMethod()
{
int i = 10;
if(i==10)
return;
System.out.println("This will never be printed");
}
Here, using return causes to stop the execution of the whole method after line 3 and execution goes back to its caller.
break is used to break out from a loop or a switch statement. Consider this example -
int i;
for(int j=0; j<10; j++)
{
for(i=0; i<10; i++)
{
if(i==0)
break; // This break will cause the loop (innermost) to stop just after one iteration;
}
if(j==0)
break; // and then this break will cause the outermost loop to stop.
}
switch(i)
{
case 0: break; // This break will cause execution to skip executing the second case statement
case 1: System.out.println("This will also never be printed");
}
This type of break statement is known as unlabeled break statement. There is another form of break, which is called labeled break. Consider this example -
int[][] arrayOfInts = { { 32, 87, 3, 589 },
{ 12, 1076, 2000, 8 },
{ 622, 127, 77, 955 }
};
int searchfor = 12;
int i;
int j = 0;
boolean foundIt = false;
search:
for (i = 0; i < arrayOfInts.length; i++)
{
for (j = 0; j < arrayOfInts[i].length; j++)
{
if (arrayOfInts[i][j] == searchfor)
{
foundIt = true;
break search;
}
}
}
This example uses nested for loops to search for a value in a two-dimensional array. When the value is found, a labeled break terminates the outer for loop (labeled "search").
You can learn more abour break and return statements from JavaDoc.
Break statement will break the whole loop and execute the code after loop and Return will not execute the code after that return statement and execute the loop with next increment.
Break
for(int i=0;i<5;i++){
print(i)
if(i==2)
{
break;
}
}
output: 0 1
return
for(int i=0;i<5;i++)
{
print(i)
if(i==2)
{
return;
}
}
output: 0 1 3 4
break:- These transfer statement bypass the correct flow of execution to outside
of the current loop by skipping on the remaining iteration
class test
{
public static void main(String []args)
{
for(int i=0;i<10;i++)
{
if(i==5)
break;
}
System.out.println(i);
}
}
output will be
0
1
2
3
4
Continue :-These transfer Statement will bypass the flow of execution to starting point of the loop inorder to continue with next iteration by skipping all the remaining instructions .
class test
{
public static void main(String []args)
{
for(int i=0;i<10;i++)
{
if(i==5)
continue;
}
System.out.println(i);
}
}
output will be:
0
1
2
3
4
6
7
8
9
return :-
At any time in a method the return statement can be
used to cause execution to branch back to the caller of the method.
Thus, the return statement immediately terminates the method in which
it is executed. The following example illustrates this point. Here,
return causes execution to return to the Java run-time system,
since it is the run-time system that calls main( ).
class test
{
public static void main(String []args)
{
for(int i=0;i<10;i++)
{
if(i==5)
return;
}
System.out.println(i)
}
}
output will be :
0
1
2
3
4
You use break to break out of a loop or a switch statement.
You use return in a function to return a value. Return statement ends the function and returns control to where the function was called.
break breaks the current loop and continues, while return it will break the current method and continues from where you called that method
Break will only stop the loop while return inside a loop will stop the loop and return from the function.
Return will exit from the method, as others have already pointed out. If you need to skip just over some part of the method, you can use break, even without a loop:
label: if (some condition) {
// some stuff...
if (some other condition) break label;
// more stuff...
}
Note, that this is usually not good style, though useful sometimes.
How does a return statement differ from break statement?.
Return statement exits current method execution and returns value to calling method.
Break is used to exit from any loop.
If I have to exit an if condition, which one should I prefer, return or break?
To exit from method execution use return.
to exit from any loop you can use either break or return based on your requirement.
break just breaks the loop & return gets control back to the caller method.
In this code i is iterated till 3 then the loop ends;
int function (void)
{
for (int i=0; i<5; i++)
{
if (i == 3)
{
break;
}
}
}
In this code i is iterated till 3 but with an output;
int function (void)
{
for (int i=0; i<5; i++)
{
if (i == 3)
{
return i;
}
}
}
If you want to exit from a simple if else statement but still stays within a particular context (not by returning to the calling context), you can just set the block condition to false:
if(condition){
//do stuff
if(something happens)
condition = false;
}
This will guarantee that there is no further execution, the way I think you want it..You can only use break in a loop or switch case

Categories

Resources