Java Puzzlers

Well, Joshua Bloch wrote Java Puzzlers: Traps, Pitfalls, and Corner Cases, I started reading this book…I love him!

#### Puzzle 1: Oddity

If you write this method for checking odd, it's wrong.

```public static boolean isOdd(int i) {
return i % 2 == 1;
}
```

Because, when i is a negative odd number, i % 2 is equal to -1 rather than 1, so the
isOdd method incorrectly returns false. Test code:

```public class Main1 {

public static void main (String args[]) {

System.out.println(" isOdd(5)  > " + isOdd(5));
System.out.println(" isOdd(-5) > " + isOdd(-5));
System.out.println(" isOdd(2)  > " + isOdd(2));
System.out.println(" isOdd(-2) > " + isOdd(-2));

}

public static boolean isOdd(int i) {
System.out.println(i + "%2=" + i%2);
return i % 2 == 1;
}

}
```

Output:

``````5%2=1
isOdd(5)  > true
-5%2=-1
isOdd(-5) > false
2%2=0
isOdd(2)  > false
-2%2=0
isOdd(-2) > false```
```

Solution: So, just check i % 2 != 0 or use (i & 1) != 0, because bitwise operation is faster then arithmetic and logical operations.
See JLS: http://docs.oracle.com/javase/specs/jls/se5.0/html/expressions.html#15.17.3

#### Puzzle 2: Time for a Change

This problem is pretty simple. We all know it! avoid float and double where exact answers are required; for monetary calculations, use int, long, or BigDecimal

#### Puzzle 3: Long Division

This puzzle is little tricky. Widening primitive conversion [JLS 5.1.2] applicable. See: http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html .

```public class LongDivision {
public static void main(String[] args) {
final long MICROS_PER_DAY = 24 * 60 * 60 * 1000 * 1000;
final long MILLIS_PER_DAY = 24 * 60 * 60 * 1000;
System.out.println(MICROS_PER_DAY / MILLIS_PER_DAY);
}Puzzle 4: It’s Elementary

}
```

Solution: When working with large numbers, watch out for overflow—it’s a silent killer. Just because a variable is large enough to hold a result doesn’t mean that the computation leading to the result is of the correct type. When in doubt, perform the entire computation using long arithmetic.

```public class LongDivision {
public static void main(String[] args) {
final long MICROS_PER_DAY = 24L * 60 * 60 * 1000 * 1000;
final long MILLIS_PER_DAY = 24L * 60 * 60 * 1000;
System.out.println(MICROS_PER_DAY / MILLIS_PER_DAY);
}
}
```

#### Puzzle 4: It’s Elementary

```public class Elementary {
public static void main(String[] args) {
System.out.println(12345 + 5432l);
}
}
```

This program must surely print 66666. There is only one problem with this analysis: When you run the program, it prints 17777.

Solution: Always use a capital el (L) in long literals, never a lowercase el (l). This completely eliminates the source of confusion on which the puzzle relies:

```System.out.println(12345 + 5432L);
```

#### Puzzle 5: The Joy of Hex

Need to understand later! :-(