File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Error in == checking Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Error in == checking" Watch "Error in == checking" New topic

Error in == checking

Shiva Mohan
Ranch Hand

Joined: Jan 05, 2006
Posts: 481

Line 1 and 2 showing incompatible type found int required java.lang.Integer.
why?can anyone please explain this for me.
Scott Selikoff
Saloon Keeper

Joined: Oct 23, 2005
Posts: 3753

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 ]

[OCA 8 Book] [Blog]
Shiva Mohan
Ranch Hand

Joined: Jan 05, 2006
Posts: 481
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

marc weber

Joined: Aug 31, 2004
Posts: 11343

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 ]

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
I agree. Here's the link:
subject: Error in == checking
It's not a secret anymore!