Java String Conversion Puzzlers

In Java, object coercion from one type to another can led to interesting results, and possible bugs when done implicitly. For example, a common type conversion bug is when you have a method that accepts a primitive boolean but pass it an an object of type Boolean. If the object is null, the conversion from a Boolean object to a boolean primitive will cause a NullPointerException.

But mixing between Strings, characters, and integers can result in an interesting mix of results. For example, I think that any Java developer would have some doubt in describing the output from the following Java code.

System.out.println("Hello, "+(char)('A'+1));
System.out.println("Hello, "+('A'+1));
System.out.println("Hello, "+'A'+1);

The one rule to remember about coercion is that if you are performing a calculation with two different types, the least accurate type will be coerced or converted to the more accurate. In this case, adding a character and an integer will result in converting the character to the corresponding integer value before performing the addition operation. Because the integer equivalent of the char value ‘A’ is 65, then ‘A’+1 = 66. When adding between a string, character, and integer the character and integer are converted to strings because concatenating the values into a new string.

"Hello, "+(char)('A'+1); // Hello, B
"Hello, "+('A'+1); // Hello, 66
"Hello, "+'A'+1; // Hello, A1

Leave a Reply