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...

boolean IsEnabled (JPanel MyPanel) {
	return MyPanel.isEnabled();
}

Throws java.lang.NullPointerException if null is passed to the method.

So, I've learned to check if an object is null before checking with its methods.

boolean IsEnabled (JPanel MyPanel) {
	if (MyPanel == null) return false;
	else return MyPanel.isEnabled();
}

// OR

boolean IsEnabled (JPanel MyPanel) {
	return (MyPanel == null) ? false : MyPanel.isEnabled();
}

Both work just fine, because MyPanel.isEnabled() is only called if MyPanel is not null. It's a more efficient alternative to wrapping MyPanel.isEnabled() in a try-catch statement. No exception should ever be thrown in the above case. The second method is simple, as all is contained in a single line, but is there anything simpler?

Today I saw something like the following snippet on the Internet:

boolean IsEnabled (JPanel MyPanel) {
	return MyPanel != null && MyPanel.isEnabled();
}

It combines the null-check and the data-check on the same line, separated by a logical operator. In this example, the logic is AND. If MyPanel is null, the first part of the check returns false, and MyPanel.isEnabled() is not called and no exception is thrown, even though a NullPointerException should be thrown. I suppose the false before the && is reason enough for the processor not to bother checking with whatever is after the &&, am I right?

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? ;)

Dani AI

Generated

Good catch, — your one-line guard using && is a perfectly valid, language-guaranteed pattern in Java: && and || evaluate left-to-right and short‑circuit, so a false left operand prevents evaluation of the right operand. That behavior is part of the language semantics, not an accidental JVM optimization, so you can rely on it for simple null-guards when the intent is only to read data and not to rely on side effects.

That said, ’s warning is important: using short‑circuiting to hide side effects or to perform non-obvious guards can be fragile. If someone later edits the expression (or swaps the operands), you can suddenly introduce an NPE or other runtime error (division by zero, etc.). Use single-line guards for simple, obvious checks; prefer an explicit null check or a short guard clause when clarity matters.

To clarify ’s point: & and | are different. For integer types they are bitwise; for boolean operands they are non‑short‑circuit logical operators — both sides are always evaluated. That makes & useful only when you explicitly want both operands evaluated (for example to force side effects), otherwise prefer &&/||.

A modern, readable alternative (Java 8+) that avoids explicit nulls is Optional:

boolean enabled = Optional.ofNullable(panel)
                          .map(javax.swing.JComponent::isEnabled)
                          .orElse(false);

Best practices: prefer clear guard clauses for complex logic, avoid relying on short‑circuit for side effects, use Optional or Objects.requireNonNull when appropriate, and keep boolean expressions simple so their evaluation order is obvious to future maintainers.

Recommended Answers

All 3 Replies

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

if ( true || false )

The program knows that there is no need to evaluate the right-hand-side, since the result of the boolean expression is already known for certain.

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

int n=0;
if ( n!=0 && 10/n == 2 )

if this check was improperly altered in this block of code, the program could crash

int n=0;
if ( 10/n == 2 && n!=0 )
    //Bad: Looming catastrophe!
Member Avatar for Member #119018

&& and || use the short-circuit evaluation. To force the compiler to check both conditions, use & or |.

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.