Type casting in Java
casting, compiler-errors, java, type-conversion
Solution
The compiler thinks that, in the expression `(Integer)-x`, you are trying to subtract `x` from a variable called `Integer`, hence the error since no such variable is defined. `(int)-x` works because `int` is a reserved keyword for a primitive type and cannot be used as a variable name, so the compiler can deduce that you are trying to cast, not subtract.
Problem
Possible Duplicate: Any idea why I need to cast an integer literal to (int) here? ``` package typecastingpkg; public class Main { public static void main(String[] args) { byte a=10; Integer b=(int)-a; System.out.println(b); int x=25; Integer c=(Integer)(-x); // If the pair of brackets around -x are dropped, a compile-time error is issued - illegal start of type. System.out.println(c); Integer d=(int)-a; //Compiles fine. Why does this not require a pair of braces around -a? System.out.println(d); } } ``` In this code, while casting of `-x` of primitive type `int` to a wrapper type `Integer`, a compile-time error is produced: `illegal start of type`. ``` Integer c=(Integer)-x; ``` It requires a pair of braces around `-x` like `Integer c=(Integer)(-x);` The following expression however compiles fine. ``` Integer d=(int)-a; ``` Why does this one not require a pair of braces around `-a` as in the preceding expression?