![]() |
| ||
| Logical operations and data-checks So I've run into this situation a million times in my "learning career" and I've always found a long way around the issue so as not to risk throwing unnecessary exceptions.. Let's look at a simple example... So, I've learned to check if an object is null before checking with its methods. Today I saw something like the following snippet on the Internet: Switching the order of the check to MyPanel.isEnabled() && MyPanel != null results in the exception. I guess what I'm trying to confirm is, has the JVM always given precedence to the first argument in a logical operation, and will it always ignore successive arguments given the first is reason enough to "call it quits"? I try my best to keep things organized, and often I'd like to combine object checks into a single line at the beginning of a method call, just to be tidy. I think I've answered my own question by running the test above, but, should I feel safe in the future to combine null- and data-checks into a single logical statement without watching for exceptions? ;) |
| ||
| Re: Logical operations and data-checks Correct, this sort of thing is known as short circuit evaluation. it also happens under logical OR evaluation when the left-hand-side of the expression yields 'true', ie As you see in the example you've found, this is sometimes used in subtle ways to perform checks before executing a statement - Which is not always a good idea IMHO, because it runs the chance of being accidentally changed to introduce weird bugs! For example |
| ||
| Re: Logical operations and data-checks && and || use the short-circuit evaluation. To force the compiler to check both conditions, use & or |. |
| ||
| Re: Logical operations and data-checks In fact & and | aren't strictly logical comparison operators at all. They're logical mathematical operators. So instead of performing a comparison you're performing a mathematical operation if you use them, and evaluating the result of that operation. |
| All times are GMT -4. The time now is 4:13 am. |
Forum system based on vBulletin Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
©2003 - 2008 DaniWeb® LLC