March 6, 2009
java  bloch  java7 
Comments (View)
March 5, 2009
java  smartypost 
Comments (View)
March 4, 2009
java  trick 
Comments (View)
java  scjp 
Comments (View)
March 3, 2009

type 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.

java  promotion 
Comments (View)

joshua bloch at  javaone. try to answer his questions.

java  puzzler  bloch 
Comments (View)
March 2, 2009
java  java7 
Comments (View)

generics 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.

java  generics 
Comments (View)