Java int and integer compare

Comparing Integer objects [duplicate]

For reference types, == checks whether the references are equal, i.e. whether they point to the same object.

For primitive types, == checks whether the values are equal.

java.lang.Integer is a reference type. int is a primitive type.

Edit: If one operand is of primitive type, and the other of a reference type that unboxes to a suitable primitive type, == will compare values, not references.

+1 for question and answer. Just to make sure: in situation (Integer == int) or (int == Integer) it will always be unboxed to (int == int) not autoboxed to (Integer == Integer) ?

Integer objects are objects. This sounds logical, but is the answer to the question. Objects are made in Java using the new keyword, and then stored in the memory. When comparing, you compare the memory locations of the objects, not the value/properties of the objects.

Using the .equals() method, you actually compare the values/properties of objects, not their location in memory:

new Integer(1) == new Integer(1) returns false , while new Integer(1).equals(new Integer(1)) returns true .

int s are a primitive type of java. When you create an int, all that is referenced is the value. When you compare any primitive type in Java, all that is compared is the value, not the memory location. That is why 5 == 5 always returns true.

When you compare an Integer object to a primitive type, the object is cast to the primitive type, if possible. With an Integer and an int this is possible, so they are compared. That is why Integer(1).equals(1) returns true.

Источник

Integer == int allowed in java

I was wondering if java automatically turns a Integer into an int when comparing to an int? Or will the == try and compare references on primitives? Is this always true or do I need to do i.intValue()==2 ?

Integer i = Integer.valueOf(2); if (i==2) < //always? >

Yeah running works, but you can compare two equal strings with == and sometimes get true or fals depending on how the strings were pooled.

This is a feature called [autoboxing][1] and has been introduced in Java 1.5. [1]: stackoverflow.com/questions/166340/…

6 Answers 6

Yes, when comparing int using == arguments will be unboxed if necessary.

15.21.1 Numerical Equality Operators == and !=

If the operands of an equality operator are both of numeric type, or one is of numeric type and the other is convertible (§5.1.8) to numeric type, binary numeric promotion is performed on the operands (§5.6.2). If the promoted type of the operands is int or long, then an integer equality test is performed; if the promoted type is float or double, then a floating-point equality test is performed.

Note that binary numeric promotion performs value set conversion (§5.1.13) and unboxing conversion (§5.1.8). Comparison is carried out accurately on floating-point values, no matter what value sets their representing values were drawn from.

Same applies for < , , >= etc, as well as + , — , * and so on.

System.out.println(Integer.valueOf(17) == 17); 

but you can compare two equal strings with == and sometimes get true or fals depending on how the strings were pooled.

Right, and there is actually a similar situation for Integers as well.

When boxing (transforming int to Integer ) the compiler uses a cache for small values (-128 — 127) and reuses the same objects for the same values, so perhaps a bit surprising, we have the following:

System.out.println(Integer.valueOf(100) == Integer.valueOf(100)); // prints true System.out.println(Integer.valueOf(200) == Integer.valueOf(200)); // prints false 

Источник

Best way to compare an int to a Number

I have a method with a Number parameter and have to determine if it is smaller than an int . What I came up with is this :

Integer.valueOf(myInt) > (Integer) myNumber Which looks rather clumsy for such a simple task. Moreover, I am not sure if it would play nicely with BigDecimal et.al., and what cases would I have to test?
How could it be improved? Thank you

Are you sure that the passed Number will always be an Integer ? There may be a cast exception in the example.

4 Answers 4

Your code will result in a ClassCastException if the myNumber is anything but an Integer .

I’d say this has the best chance of dealing correctly with all Number types:

myInt > myNumber.doubleValue() 

because double has the widest range of all the types you can convert a Number to, and it will not truncate fractions.

btw. Why use doubleValue() for comparing to an int? wouldnt intValue() make more sense? Or are there some quirks?

@kostja: The Number may have a fractional part, which intValue() would truncate, leading to wrong results for the comparison (perhaps not in your case but definitely for others)

You might have a problem here if myNumber is an instance of Long . You might end up having overflow issues (what if your Number is actually greater than Integer.MAX_VALUE ?).

Also, your Number could be a double , and a conversion to int would cause a loss of precision, as your number would be truncated.

Converting your number to double could be a reasonable solution:

myInt > myNumber.doubleValue(); 

But that would drop information.

(double)myInt > myNumber.doubleValue() 

The comparison gets a little tricky because BigDecimal and BigInteger also extend Number. These classes can hold integer values of unlimited size (well, limited by the memory on your computer).

Thus, if you ask for for the double value or long value of these you may risk erroneous comparisons since BigDecimal or BigInteger will be forced to truncate their value.

The safest thing to do would be to convert the Number to a String and then give this String to the BigDecimal class to parse.

Number n = . ; int i = . ; BigDecimal m = new BigDecimal(n.toString()); BigDecimal j = new BigDecimal(i); boolean result = j.compareTo(m) < 0; // equivalent to i < n 

If you're sure you will never get an instance of BigInteger or BigDecimal whose value exceeds the maximum positive or maximum negative value of a double then it should be safe to use Number.doubleValue to get a number to compare to.

There are additional problems that you may face with the possibility of having to compare BigDecimals. This is because BigDecimals represent their values in base 10, whereas other Number subclasses use base 2.

As such new BigDecimal("0.1") is not equal to 0.1d or 0.1f . This is because floats and doubles cannot represent many base 10 fractions accurately (whereas BigDecimal can). So getting a double value from a BigDecimal may end up giving you erroneous comparisons. But since you are comparing to ints this in a problem that you do not need to face.

Источник

Java: Integer equals vs. ==

As of Java 1.5, you can pretty much interchange Integer with int in many situations. However, I found a potential defect in my code that surprised me a bit. The following code:

Integer cdiCt = . ; Integer cdsCt = . ; . if (cdiCt != null && cdsCt != null && cdiCt != cdsCt) mismatch = true; 

appeared to be incorrectly setting mismatch when the values were equal, although I can't determine under what circumstances. I set a breakpoint in Eclipse and saw that the Integer values were both 137, and I inspected the boolean expression and it said it was false, but when I stepped over it, it was setting mismatch to true. Changing the conditional to:

if (cdiCt != null && cdsCt != null && !cdiCt.equals(cdsCt)) 

fixed the problem. Can anyone shed some light on why this happened? So far, I have only seen the behavior on my localhost on my own PC. In this particular case, the code successfully made it past about 20 comparisons, but failed on 2. The problem was consistently reproducible. If it is a prevalent problem, it should be causing errors on our other environments (dev and test), but so far, no one has reported the problem after hundreds of tests executing this code snippet. Is it still not legitimate to use == to compare two Integer values? In addition to all the fine answers below, the following stackoverflow link has quite a bit of additional information. It actually would have answered my original question, but because I didn't mention autoboxing in my question, it didn't show up in the selected suggestions: Why can't the compiler/JVM just make autoboxing “just work”?

Источник

Читайте также:  Use audio in java
Оцените статью