Line 1 and 2 showing incompatible type found int required java.lang.Integer.
why?can anyone please explain this for me.
Also, you should use equals() on an Integer instead == since equals() compares Integer values whereas == just tells you if it is the same object (ergo you could have many objects all with the same value but == would fail).
Site note - There are many reasons for the wrapper classes but in particular I find them useful because you can set a reference to them to null implying the object was never set. Ints don't really have that feature other than to always set it to a specific invalid number that you pick like -1.
[ March 29, 2006: Message edited by: Scott Selikoff ]
Integer i3 = 10;
Integer i4 = 10;
if(i3 == i4) System.out.println("same object");
if(i3.equals(i4)) System.out.println("meaningfully equal");
This example produces the output:
However, the boxing will result in both comparisons returning true because the value is within the byte range. If it were outside the range of a byte, then there is no guarantee regarding the == comparison.
From the Java Language Specification section 5.1.7...
If the value p being boxed is ... an int or short number between -128 and 127, then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2...
Ideally, boxing a given primitive value p, would always yield an identical reference. In practice, this may not be feasible using existing implementation techniques. The rules above are a pragmatic compromise.
[ March 29, 2006: Message edited by: marc weber ]