Reputation: 6521
Is it safe to write something like this in java?
if(var==2){
return true;
}
return false;
Somehow, while debugging, the compiler executes the first return, and goes to the second. Shouldnt the method be terminated after the first return?
Upvotes: 0
Views: 104
Reputation: 18492
Yes it's perfectly fine to do that, even though you can write it shorter than that. Perhaps it just looks like it's getting to your second return while you're visually stepping through your code, when var == 2
, but it's stepping to the end of the function. You should be able to check the return value of the function after it's finished executing.
If you really wanted to be sure, you could use assert
statements or even a print statement with the return value.
Upvotes: 1
Reputation: 16
Yes it is safe! You can have as many returns as you want - the method will be terminated after the first one
Upvotes: 1
Reputation: 77995
It's perfectly safe and valid Java code. And it's not possible for the return to not actually return.
If you believe it is, I suggest you do a clean and then recompile, it's possible there is a mismatch between the compiled class and your source code.
Upvotes: 1
Reputation: 234795
That's perfectly safe. Alternatives are return var == 2;
or return var == 2 ? true : false;
Upvotes: 1
Reputation: 272467
Yes, it's safe.
But consider writing this instead:
return (var==2);
Upvotes: 3