An interesting fact about java branches

in java •  4 years ago 

If you don't have an else in your branching statement, you may face an error. The reason is, the program might or might not execute the statement inside second if. Here is the example from the textbook:

ifElse.png

The right and left parts seem to be similar, however, they are not. The right (not left) code may raise an error.

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  

You've got a free upvote from witness fuli.
Peace & Love!

Well, there is a reason behind it. Although we humans can be sure that the right and left codes are equivalent, the compiler scans the branching first and can't make sure that one of the statements will be executed. It does not know inside statements at this stage; so it will assume that "maybe", none of the statements will be executed. So it will raise an error.