Java puzzlers from OCA part 5
In the fifth part of the Java Puzzlers series, we will see something related to X.parseX(String s) methods.
You can see what we expect from X.parseX() methods.
1 2 3 4 5 6 7 8 9 | public class Puzzler { public static void main(String[] args){ int i = Integer.parseInt( "2" ); System.out.println(i); // prints 2 } } |
We give the methods a String that can be converted to the primitive representation and hope for the best. Now lets check another example which will give us a NumberFormatException.
1 2 3 4 5 6 | public class Puzzler { public static void main(String[] args){ int i = Integer.parseInt( "integer" ); // java.lang.NumberFormatException: For input string: "integer" } } |
As the input is a word and not something that can be parsed to an integer, we get NumberFormatException. What happens above is consistent for each number type. So Integer, Byte, Short, Long, Double, Float won’t surprise you when you call their parse methods with some random String. You’ll get a NumberFormatException.
Now lets check what happens with boolean.
1 2 3 4 5 6 7 8 9 | public class Puzzler { public static void main(String[] args){ final boolean b1 = Boolean.parseBoolean( "boolean?" ); System.out.println(b1); } } |
Can you guess what happens? The parse call will probably throw java.lang.BooleanFormatException, right? Not really. If you run that, it’ll print “false” to the screen. The reason is Boolean.parseBoolean() just accepts anything and if it can’t parse it, it just returns “false” value. Now lets see the other example.
1 2 3 4 5 6 7 | public class Puzzler { public static void main(String[] args){ final boolean b2 = Boolean.parseBoolean( "TrUe" ); System.out.println(b2); } } |
You probably expect false again? That’s not the case because parseBoolean is case insensitive and will return “true” in this case.
Published on Java Code Geeks with permission by Sezin Karli, partner at our JCG program. See the original article here: java puzzlers from oca part 5 Opinions expressed by Java Code Geeks contributors are their own. |