Branching Without an if, A Java Puzzle

August 6, 2016 | 2 min Read

I returned home late the other night, and saw this tweet in my timeline:

https://twitter.com/marckhouzam/status/761389998788714496

He added a clarifying note that said the ‘?’ was also broken.

For those of you who don’t know Marc, he is the co-lead of the Eclipse C/C++ Development Tools and all round good guy. I was pretty sure his keyboard wasn’t actually broken and he was basically asking: How can you write a branch statement in Java without an if.

My first thought was to use another branching construct, and the while loop was the first one to pop into my head:

int bar(Object o) {
  while(o == null) {
    return 0;
  }
  return 1;
}

However, since I couldn’t sleep I started thinking of other ways to solve this. Since it could be solved with a while, what about a do while.

int bar(Object o) {
  int counter = 2;
  do {
    counter--;
  } while(o == null && counter > 0);
  return counter;
}

You could likely solve it with a for loop too, but that would require an f.

A case statement is the next obvious branching construct. However, you cannot switch on a condition such as does n == null. But you can switch on integers, and the identityHashCode is good choice because the identityHashCode for null is 0:

int bar(Object o) {
  int hash = System.identityHashCode(o);
  switch(hash) {
    case 0: return 0;
  }
  return 1;
}

Another conditional construct is the catch block, since it only enters into the catch block if an exception is thrown. It’s pretty easy to raise an exception with a null reference:

int bar(Object o) {
  try {
    o.equals(o);
    return 1;
  } catch(NullPointerException e) {
    return 0;
  }
}

Finally, I took the original question literally and wrote the if statement without an f. This can be done by replacing the character with its unicode equivalent. I think this was a little cheeky and not really in the spirit of the question though:

int bar(Object o) {
  i\u0066(o == null ) 
    return 0;
  else 
    return 1;
  }
}

Does anyone else have other suggestions for how to solve this? Or maybe Marc should just take Jesper’s advice:

https://twitter.com/JesperEs/status/761457229035888640

Ian Bull

Ian Bull

Ian is an Eclipse committer and EclipseSource Distinguished Engineer with a passion for developer productivity.

He leads the J2V8 project and has served on several …