Auto-unboxing, switch, short circuit logical operators & exception handling are core Java basics that sometimes lead to obscure errors if not understood well & often tested in coding tests.
Q1. What is wrong with this code?
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
public class WhatIsWrong { public static void main(String[] args) { double i = 2; switch (i) { case 1: System.out.println("First class"); break; case 2: System.out.println("Second class"); break; default: break; } } } |
A1. compile-error at switch(i) as switch works only with “int” and “String” (i.e. from Java 7 onwards) data types.
Q2. What is wrong with this code?
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
public class WhatIsWrong { public static void main(String[] args) { Entry entry = null; if (entry != null & entry.value > 0) { System.out.println("A non-zero value"); } } static class Entry { int value; public Entry(int value) { this.value = value; } } } |
A2. “java.lang.NullPointerException” at “entry.value > 0”. Use short circuit “&&” instead to not check “entry.value > 0” when “entry == null”.
Q3. What is wrong with this code?
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import java.util.HashMap; import java.util.Map; public class WhatIsWrong { static Map<Integer,String> map = new HashMap<Integer, String>(); public static void main(String args[]) { byte b = 1; map.put(1, "Hello World"); String s = map.get(b); System.out.println("The result is: " + s); } } |
A3. The output will be
|
1 |
The result is: null |
This is because of the hidden danger of autoboxing.
1) map.put(new Integer(1), “Hello World”); // auto boxed
2) map.get(new Byt(1)); // null
Integer(1) != Byte(1).
Q4. What is wrong with this code?
|
1 2 3 4 5 6 7 8 9 10 11 |
public class WhatIsWrong { public static void main(String args[]) { boolean b = false; Double d1 = 0.5d; Double d2 = null; Double result = b ? d1.doubleValue() : d2; System.out.println(result); } } |
A4. java.lang.NullPointerException due to autounboxing. The two expressions around “:” must return the same type. This means Java tries to convert the expression d2 to primitive “double” value. This means the call “doubleValue()” on d2, which is null will throw a “java.lang.NullPointerException”
Q5. What is wrong with this code?
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
public class WhatIsWrong { public static void main(String args[]) { try{ //....Some file processing logic } catch(Exception ex1){ ex1.printStackTrace(); } catch(IOException ex2){ ex2.printStackTrace(); } } } |
A5. Compile-time error. Exceptions are polymorphic in nature and more specific exceptions need to be caught before the generic exceptions. So, “IOException” must be caught before “Exception”.