Tutorial :Why is the Android emulator skipping my return statement?


I'm getting unexpected behavior in my Android 1.5 application under the Windows emulator and debugging with Eclipse. Here's a generalization of what the code is doing:

if (someCondition) {      System.out.println("got here");      return "a";  }    if (someOtherCondition)      return "b"    return "c";  

If I step through this code with the debugger, if someCondition is true it outputs "got here" but then jumps to the final return statement as if it's going to execute that line. From what I can tell, it is returning "a" but it's confusing because it seems like it is going to return "c."

If someCondition is false, and someOtherCondition is true, the debugger steps to the return "b" line - it doesn't jump to the final return statement and then leaves the method as expected.

As I mentioned, it seems like it is always returning the expected behavior but the fact that the debugger jumps to the wrong line had me chasing phantom bugs. A full rebuild, restarting Eclipse and restarting Windows each didn't address the problem - it's fully re-createable.

Any ideas?


Remember that your program that you execute and debug isn't written Java code - it's bytecode that was compiled from the Java code.

If you step through optimized C++ code, you can expect the cursor to jump around all across your code like stupid, depending on how much the scheduler was able to rearrange stuff.

Java is a lot more straightforward, but I would imagine that return instructions still get optimized out a bit, i.e. the clean-up part of the function is shared, so the return always gets you there.

Don't rely too much on the precise position of the cursor - instead, use debug output (which is also faster in practice).


just making sure: the actual code as a semicolon after return "b" -right? Missing semicolons always cause strangeness.


I think you are encountering one of optimizations that dx tool does to class files. In short in some circumstances returns gets combined. You can see more info on this http://www.netmite.com/android/mydroid/2.0/dalvik/docs/debugger.html under Known Issues and Limitations But unfortunately from there it is not clear in what exact cases that optimization will take effect and it is still not clear why one return gets combined but the other doesn't like in your example...

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »