Tag Archives: java

Java Quiz of the Day

Java quiz of the day (easy): what gives

Object[] a = new Integer[]{};
List<Object> b = new ArrayList<Integer>();

Response: we get an exception on the second line:

Type mismatch: cannot convert from ArrayList<Integer> to List<Object>

Arrays and Generics are not consistent. While for arrays, an array of some type is also an array of one of its parent types, the same is not true for Generics. If it was, we could construct weird things where we would get at most a runtime exception when trying to access items of a collection. See the following example:

class A{
	void foo(List<Integer> list) {
		List<Object> otherList = list; // (A)
		otherList.add("hi"); // (B)
	}
}

List<Integer> list = new ArrayList<Integer>();
list.add(5);
new A().foo(list);
for (Integer i : list) {
	System.out.println(i.intValue()); // (C)
}

Here line (A) is not a legal assignment. If it was, then we could insert into our originally List a String on line (B). Then back from our method foo, we would get a runtime exception when processing the list on line (C). This problem was fixed for Generics, while similar problems exist for arrays.

Java Quiz of the Day II

What gives:

Integer a = 100, b = 100;
Integer c = 200, d = 200;
System.out.println( (a == b) == (c == d) ); // A

Response: counter intuitively, the program prints ‘false’ out. Integer in Java is a non-native class, where ‘==’ means ‘reference equality’ (two variables are reference equal if they are pointing to the same object). From there we would expect the expression of line (A) to be reduced to ‘false == false’, but it is slightly more complicated: the Integer class has the particularity that all Integer (like Short) in the range [-128, 127] are shared. This means the two variables ‘a’ and ‘b’ are actually pointing to the same shared object. Hence the expression of line (A) is in fact reduced to ‘true == false’.

Java Quiz of the Day

What gives

Double a = null;
Double b = a == null ? a : 1.0;

Response: as strange as it can seem at first look, b is not equal to null after the second statement, but the code produces a NullPointerException.

The reason for that is the type of the second expression (double) inside the ternery operator. The first expression ‘a’ of type Double is unboxed to double (calling doubleValue() on ‘a’ which is null), causing the NPE.

You can find a discussion about that here.