preparing for scjp exam? follow the link and test yourself! hurt of self-esteem is guaranteed.
3 years agotype promotion exception
the following code causes a compilation error.
int i = 120;
byte b = i;
how would you change the first line to fix the code (without changing the type of i)?
the problem is (as you probably guessed) that we want assign an int expression to a byte variable. the compiler cannot permit this since the range of int is wider than the range of byte.
if you read the specification carefully you’ll come accross this exception of the above rule: an int expression can be assigned to a byte variable given that the expression can be evaluated at compile time. and how can a variable made to a compile time constant? by using the final keyword.
that is, the final keyword should be appended to the begining of the first line:
final int i = 120;
thus the problem is fixed.
3 years agomr. scrappy: what is multyple-exception-handling-catch for? if the code needed for handling two or more exception types is the same it is likely (in my opinion) that the two types have a same parent. why not handle that? or if they don’t share the parent (meaning they are different enough) why should anyone handle them in the same way? why does anyone want to hide the intrinsic differences?
3 years agogenerics and instanceof
what do you think the output of the following code is?
List<Integer> list = new ArrayList<Integer>();
System.out.println(list instanceof List<Integer>);
in short: in the above code we declare list with type List<Integer>. in the next ine we try to check whether list is of type List<Integer>. the answer seems to be obvious: the output is true.
actually, the code will cause a compile-time exception with the following message
illegal generic type for instanceof
to understand this behaviour recall that generics are implemented with type erasure. that is, the resulting bytecode doesn’t contain any information about type parameters. this means that there’s no point in asking if the type of a given object is equivalent to a generic type since in the bytecode there are no generic type parameters.
3 years ago