Java boolean method: unreachable statement - java

I want to check if there are no elements in an array.
private Player[] players = new Player[maxPlayers];
public boolean activePlayer(){
for(int i = 0; i < players.length; i++){
if(players[i] != null) {
return true;
break;
}
}
return false;
}
ItelliJ marks break; red with the message unreachable statement. What does this mean and how can I fix this?

The return statement right before the break will immediately end the method, so the break will never be reached.

in simple terms, the if the first if condition is true then it will only goto "return true;" and exit... if it does not go into the If block then it will continue to loop through and end at "return false;" So yes intelliJ is right. it should never come to the "break;"
the return true; will actually do the break for you and you don't need to do it explicitly and it will return to where ever you are calling the function "activePlayers()"
If you explain why you are adding a break, we may be able to help you further

Think through the serial behavior of the program, one line at a time. If it makes it past the conditional statements, it will hit the return statement. In Java, return terminates a function, returning control to the calling function and potentially returning a value as well. The break line will never be touched!
This might help you understand the flow of control in a Java program: http://www.dickbaldwin.com/java/Java026.htm
If you add more information about what you would like the program to do/ what you expect from the break statement, we'd be happy to help!

We use return to return a value back to the calling method, so therefore once control goes inside the if block the value true is returned to the calling method hence the break will never be reached.
To put it simply, return ends the execution of the current method and returns a value back to the caller.

Well, in Java, returning a value in a function will, in order,:
1. stop executing the code inside of the function
2. return the value in the function
ItelliJ is a very snappy and "intelligent" code checker that tells you when something is wrong or buggy.
It is giving you the error, "unreachable statement" because the "break" statement never gets executed because when you return "true"... (look back at the first part of the answer)... the break statement never gets executed.
So it is therefore an "unreachable" statement that will never be executed in any case whatsoever.

Related

how to stop or terminate while loop in java whenever we want

I am getting Unreachable code compilation error when I am using true in while loop
my code:
LoginService();
while(true)
{
//some stuff
}
LogoutService(); //getting compilation error Unreachable code
How to handle the situation ?
Your getting that error because you have an infinite loop due to your true condition in the while loop. You should reevaluate the reason for your while loop and provide an appropriate exit out of it.
You are seeing this error because the compiler has detected an infinite loop. To fix this, try this version, which uses a boolean variable to control loop execution:
LoginService();
boolean flag = true;
while (flag) {
//some stuff
if (condition) {
flag = false;
}
}
LogoutService();
This fixes your compiler error and also makes your logic explicit for when the loop should continue executing.
As much as possible (I would suggest never) use a while(true) !
Just put an exit condition in your while :
boolean exitLoop = false;
while(!exitLoop){ /*do stuff*/}
Your while(true) never ends and so LogoutService() will never be called! Have some logic that breaks the loop.
while(true){...} without any break inside means that the code after the while statement could never been reached. It is a compilation error.
14.21. Unreachable Statements
It is a compile-time error if a statement cannot be executed because
it is unreachable.
This section is devoted to a precise explanation of the word
"reachable." The idea is that there must be some possible execution
path from the beginning of the constructor, method, instance
initializer, or static initializer that contains the statement to the
statement itself. The analysis takes into account the structure of
statements. Except for the special treatment of while, do, and for
statements whose condition expression has the constant value true, the
values of expressions are not taken into account in the flow analysis.
So to solve your issue, make the last statement reachable.
For example :
LoginService();
while(true)
{
// ...
if (someCondition){
break;
}
}
LogoutService();

Missing return statement error in Java if-then tree

I'm trying to tell a Critter program to choose an attack type randomly from four options; I thought I had my return statement bases covered, but I'm getting a "missing return statement" error from drjava:
public Attack fight(String opponent) {
int fightChoice = new Random().nextInt(4);
if(fightChoice == 0){
return Attack.ROAR;
} if(fightChoice == 1){
return Attack.POUNCE;
} if(fightChoice == 2){
return Attack.SCRATCH;
} if(fightChoice == 3){
return Attack.FORFEIT;
}
}
any idea why that may be?
Basically, the compiler is not smart enough to figure out that you've covered every possibility with the four if statements (it doesn't really know about the contract on the return value of Random.nextInt()).
You therefore need to add a dummy return after the final if. It doesn't really matter what you return there, since it's effectively dead code. However, it would be good style to return some sort of unused or clearly invalid value.
edit: On second thoughts, rather than return a dummy value, it would be better to unconditionally throw some kind of a "programmer error" exception.
You need a missing statement outside the if statement. For instance, if flightChoice == 4, none of the if conditions will hold, so you should add a return at the end of the method. This return statement has to return something of type Attack like the if branches.
You might think that your if statement's cover all possible cases but compiler just compiles the code, doesn't cover/calculate possibilities. You need to add return statement after the last if-statement.
Just think, what happens when none of your if condition is true? In that case, you would not be returning anything from that method.
You should return from every path your method can follow, else you will get missing return statement error.
You can either make your if's an if-else if block, and then add
an else at the end, and return some value from there.
Or, you can simply add a return statement at the end of your method.
You need a return statement in case no if statement is true.
The above/previous answers explain that you need a return statement at the end, in case no if is true. I would only like to add a suggestion, as a good practice (maybe not best) in this case: just return a result only at the end and assign a value for the returned result in each if (maybe add some elses to make it more efficient in this case).

Why does Eclipse always give me an error after return;

I have some problem with eclipse android.
I have some java files, but if I call a method after return; (see the example) it tells me to remove the method. Why? I'm using Android 1.6.
public void onClick(View paramView)
{
switch (paramView.getId())
{
default:
case 2131296257:
}
while (true)
{
return;
fetchAlarmSettings(); <-- It tells me to remove this.
if (this.strAlarmOnOff.equals("0"))
{
this.butAlarmSet.setText("Turn Alarm Off");
this.db.updateSetting("alarmTime", this.strHour.concat(this.strMinute));
this.db.updateSetting("alarmOnOff", "1");
switch (this.cal.compareTo(Calendar.getInstance()))
{
default:
case -1:
}
while (true)
{
this.setNotifications.setAlarm(this.cal);
break;
this.cal.roll(5, 1);
}
}
this.butAlarmSet.setText("Turn Alarm On");
this.db.updateSetting("alarmOnOff", "0");
this.setNotifications.turnAlarmOff();
}
}
Thanks!
Your method will stop running the moment that the return statement is hit. Basically it should give you an 'Unreachable code!' warning, since any code after the return statement will never be executed. Removing the return keyword should fix the problem.
So basically Eclipse is telling you to remove the next line after the return since it will never be executed. If you remove the method call it will complain over what ever line you throw in next.
Besides that, there are other (according to me) flaws with your code... having a while(true) loop without a break condition in this case seems odd (but then again I might be wrong here). Also, the default block is usually found at the end of a series of case statements. Your second while(true) loop will only iterate once since once the this.setNotifications.setAlarm(this.cal); is executed the loop will stop iterating due to the break statement.
Eclipse will not allow you to write obsolute code, actually the IDE uses java compiler for that.
In this case the code below the return in certain branch (meaning that you can have return in the if and after it code for the else) is not reachable and thus you get compile error.
Simple answer, you can not perform any operation after 'return' statement.

Java methods - what RETURN actually means?

I'm pretty certain I'm missing something really obvious here but this seems quite bizarre.
I'm developing for Android using Eclipse - and I have a method similar to which I'm debugging and it's doing something rather odd...
public boolean test() {
if (variable == value)
return true;
// more code appears here
return false;
}
Stepping through that, on the first line (the if statement) the debugger suggests that variable does indeed equal value (they've both byte variables with a value of 0) - the debugger then moves onto the 2nd line (the return true) but it then moves on to the last line (return false) - skipping everything inbetween!?
The value returned was 'false'
WTF is going on there? I'd assumed that RETURN would exit the method entirely - but the debugger (and the return value being sent back - being false) suggests that it does nothing of the sort!?
What am I missing which is staring me in the face? Are return statements as the last line of methods always executed or something?
p.s. interesting update...
The variables I'm using are assigned in code which I didn't write - I just dug-out the source and re-built/re-ran the debugger with access to that source and I found this line in it
byte variable = (byte)9;
Can you see anything wrong with that and would that perhaps explain the problem do you think!? I've emailed the author but meanwhile - erm....
Update2
OK, I've completely remade the project, cleaned and rebuilt it, uninstalled and reinstalled it into the phone and the debugger now behaves more sensibly...
The problem is clearly the use of '9' (they use 0-9 as possible values in a byte!!) - what's happened now is that although the debugger is suggesting 'variable' is "0" - it's also failing comparison to (byte)0 and thus I get a 'false' return - which is actually correct.
I'm obviously stuck until they change their code to use a short - as for accepting an answer, it's tricky as the 'rebuild everything' answers and the 'compare using (byte) or bytevalue()' answers were sort-of both right!?
If they are Byte objects allocated with new, then == will test if they are the same object in memory and return false. Try to use:
variable.byteValue() == value.byteValue()
instead.
I think your problem is that, when you use the Byte object, doing the == is not comparing the VALUES of the bytes, but is instead comparing the object in memory. This is similar to how String works.
Instead, try:
public boolean test() {
if (variable.equals(value))
return true;
// more code appears here
return false;
}
Update based on Comment
If you are comparing two bytes (particularly a variable and a value), make sure you are casting to a byte on both values (see Binary Numeric Promotion as to why). So, try:
public boolean test() {
if ((byte)variable == (byte)value)
return true;
// more code appears here
return false;
}
I don't think your code buffer in eclipse is matching what is being debugged. The only time you should see code execute past a return statement is of you are using a finally block, in which you will see the code execute in the finally block after the return statement in the debugger.
Are return statements as the last line of methods always executed or
something?
No.
Try surrounding your if block in {} and then see what happens.
Your description of your code does not match the code you pasted. I suspect that this is a symptom of the real problem: you are stepping through source code that is not the same as your compiled code. The line numbers don't match. So it looks like it's doing all kinds of wacky things. Rebuild your compiled code and debug again.
Logically, a return statement does immediately exit a method--
But before it does, other things might happen, like a finally statement after an enclosing try block.
Usually, the debugger will skip to the closing brace of a method after the return statement, rather than to the last return statement.
This makes me think there is something unusual with your method, or that the method you are seeing in the debugger is not identical to the method that is running on the device.
It shouldn't be doing it and what you know about return already is correct.
This could happen when the compiled binary is different than the source code. Try cleaning your project and rebuilding it.
You could try remove "more code appears here" and add this code line-by-line, until you find mistake. Also try restart eclipse, clean up project and redeploy application.
This behavior is normal using the Eclipse debugger. I recommend you to watch the value returned by the method itself and not the code being executed (it will be true, not false).
For example, try the following code. You will see that return true is reached, but later foo, and foo2 are not initialized (although it seems to reach return false).
public boolean test() {
if (variable == value)
return true;
int foo = 5;
int foo2 = 7;
// more code appears here
return false; }
I don't see an open bracket after your "if" statement. It should look like this:
public boolean test() {
if (variable == value) {
return true;
// more code appears here
}
return false;
}
With the additional brackets the "true" will only be associated with the IF conditions, and the false will be only if the IF conditions are not satisfied.

Return statement while using worker thread

Do I always have to return something using Worker Thread in Swing? What if I don't have any return value? I just want to use the worker thread to run an infinite for loop... so what to return? and even if I write a dummy return statement after the infinite for loop, say for e.g return 0; then also it will probably say "code not reachable".
I suspect you haven't tried it. The code you've suggested in the comment should work fine:
public Object construct() {
for (;;) {
Node.execution();
Clock.incrementTimeTick();
System.out.println(Clock.getTimeInTick());
repaint();
}
// End of loop is unreachable, so no need for a return statement.
}
A tight loop like this seems like a bad idea to me, and the repaint() code will need to be made appropriately thread-safe, but it should compile...
Personally I prefer to use while (true) for "forever" loops, but for (;;) should work too.
Implement the worker as SwingWorker<Void, SomeObject> and just return null. Trick the compiler about the infinite loop. Make it depending on some method that in the runtime always return true.
A method like the follow will compile without any compilation errors:
public Object foo() {
for (;;) {
// do something ... or nothing
}
}
The reason is that any statement following the for loop is unreachable, according to the rules set out in the JLS 14.21. Specifically
Any for loop with no condition expression (or a condition expression that is a compile-time constant expression with value true) cannot "complete normally".
Any statement in a block that is preceded by a statement which cannot complete normally is unreachable.

Categories