Reflexive Assignment in Java

October 11, 2010 at 06:54 (code golf, java)

Background: Code golf is a game in which the goal is to solve programming problems using as few keystrokes as possible. It has its roots in Perl golf, and anyone with golfing experience knows that Perl is particularly well suited to such challenges. J and K, as well as the more esoteric GolfScript, are also known for combining terse syntax with powerful features. Obfuscation is a related topic.

In this post, I will discuss a snippet of Java code one might not normally think to write. I understand that “Java code golf” is practically an oxymoron, since it seems the goal of Java is to write code using as many keystrokes as possible, but let us overlook this point for now.

Suppose we want to increment a variable by an integer from standard input, but only if that integer is positive. We could use this code fragment:

Scanner r = new Scanner(;
int x, s = 0;
// do stuff with s
x = r.nextInt();
s += x > 0 ? x : 0;

But we could accomplish the same thing without introducing the variable x, as follows:

Scanner r = new Scanner(;
int s = 0;
// do stuff with s
s += (s = r.nextInt()) > 0 ? s : 0;

If you don’t see how it works, take a closer look. The variable s doubles as its own temporary variable! I admit it’s not as cool as the XOR swap algorithm, but I still got a kick out of discovering it while playing around.

Of course, I always try my best to contribute to the production of completely unreadable code.


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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: