short-circuiting can be good. very good.

So I’ve been learning/teaching Java recently. The neophyte in me is asking all sorts of questions the pros take for granted.

My question was, “What is the difference between & and && in Java?”

In an e-search, I found others who had asked the same question. I began learning how the language expresses bitwise operations and discovered that “&” stops short-circuit evaluation. I thought I’d share this clever demonstration passed on by JosAH in 2007 of why doing so could be disastrous.

PowerPlant harrisburg = new PowerPlant();
if (harrisburg.isSafe() && harrisburg.switchOn())
System.out.println("plant is operational");

Change the && to & and we have a problem.


Tags: ,

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: