[Logo]
Forums Register Login
Error in == checking


Line 1 and 2 showing incompatible type found int required java.lang.Integer.
why?can anyone please explain this for me.
Integers are objects, ints are primitives. You have to instantiate Integers using class methods like "new Integer(10)" instead of just '10'. Alternatively you could use ints like "int i3 = 10" instead.

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 ]
Thanks for the reply.but ,i have read the following code

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:
same object
meaningfully equal

How?
The shortcut syntax "Integer i3 = 10;" will work with Java 5.0's boxing feature. In prior versions of Java, this results in the error you describe.

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 ]
Wink, wink, nudge, nudge, say no more ... https://richsoil.com/cards



All times above are in ranch (not your local) time.
The current ranch time is
Oct 23, 2017 07:59:55.