Java – compiled in CMD but error in NetBeans
I have a small java file given below
class abc{ public static void main(String args[]){ Object a= 9; int b= (int)a; System.out.print(b); } }
It has errors when compiling in CMD, but it is incorrect in NetBeans In addition, when I replace '(int) "with' (integer)", it will compile and run normally on CMD and NetBeans
class abc{ public static void main(String args[]){ Object a= 9; int b= (Integer)a; System.out.print(b); } }
What is the reason and how can I solve this problem?
Edit: the error in compiling the first code is:
C:\Users\ANKIT.ANKITSHUBHAM-PC>javac abc.java abc.java:4: inconvertible types found : java.lang.Object required: int int b= (int)a; ^ 1 error
Editor: the problem is not casting This is about why when I use '(int)' to convert an object to int, CMD and NetBeans behave differently, but use the same way when using '(integer)'
Solution
What happened here?
Object a= 9;
Yes:
>Int with a value of 9 > it is automatically wrapped in an integer > it is stored in a variable of type object
Now, on the next line, object cannot be converted to int in Java 6 because it is actually an integer, not a primitive type However, it can be converted to integer and then auto- un@R_102_2419 @Ing is responsible for extracting an int
Now to "why work in NetBeans?"
NetBeans uses a different compiler (see here) than command line javac It may behave differently from javac and be more tolerant - perhaps it will automatically unpack integers when it encounters an attempt to convert it to int
In another answer, Java 7 supports automatic unpacking in this case, so the possible reason is that your command line javac is from Java 6 and NetBeans uses the Java 7 compiler (or later)