Java equality operator [duplicate] - java

This question already has answers here:
Why is == true for some Integer objects? [duplicate]
(4 answers)
Closed 9 years ago.
what is the difference?
public static void main(String[] args){
Integer integer1=1000;
Integer integer2=1000;
System.out.println(integer1==integer2);
}
Result:false
public static void main(String[] args){
Integer integer1=100;
Integer integer2=100;
System.out.println(integer1==integer2);
}
Result:true
We can Try it!

All integers between -128 and 127 are cached, because they are used more often. If you want the first example to work, try:
public static void main(String[] args){
Integer integer1=1000;
Integer integer2=1000;
System.out.println(integer1.equals(integer2));
}
Or, use an int instead of an Integer, as an Integer is an object.

As per JLS 5.1.7:
If the value p being boxed is true, false, a byte, a char in the range \u0000 to \u007f, or 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.
Integer between -128 to 127 are pooled in Java . Look at this source code :

Integer between -128 to 127 are pooled in java.
Below results in autoboxing and 2 different objects are created:
Integer integer1=1000;integer1 and integer2 are referring to 2 different objects
Integer integer2=1000;
Integer integer1=100;both refer to the same because of pooling
Integer integer2=100;

You have Integer as a reference type. == only compares references when used with objects.
Due to immutability, and interning/pooling, small values of an Integer(within the range [-128, 127] at a minimum, though this is implementation specific and should not be relied upon) may be set to reference the same object.
For the first example, the large numbers forgo interning, ergo different references, and it evaluates to false.
In the second, the Integers are the same reference, and the comparison is true.

You can simply use int instead of Integer and it will work. Otherwise refer to any other answer about == vs equals().

Related

return result of Deque pollFirst() in java [duplicate]

This question already has answers here:
How can I properly compare two Integers in Java?
(10 answers)
Closed 3 years ago.
I was coding an algorithm issue, below code can't pass case
public void pop() {
if (s1.pollFirst() == minStack.peekFirst())
minStack.pollFirst();
}
however below can,
public void pop() {
int tmp = s1.pollFirst() ;
if (tmp == minStack.peekFirst())
minStack.pollFirst();
}
the only difference is how I use s1,pollFirst() return result. I can't figure out real difference here.
Thanks
Comparing two Integer Objects with values less than -128 or bigger than 127 using == will always result in false. However, if you compare Integer with primitive int, it will give you true if the actual value is the same.
int n1=128;
Integer n2=127;
Integer n3=127;
Integer n4=128;
Integer n5=128;
System.out.println(n1==n2); //false
System.out.println(n2==n3); //true
System.out.println(n4==n5); //false
System.out.println(n1==n5); //true
In the second example you are assigning the value to the primitive int, therefore it is automatically unboxed.

why i get the next output in my java code? (false true) [duplicate]

This question already has answers here:
Why is 128==128 false but 127==127 is true when comparing Integer wrappers in Java?
(8 answers)
Closed 6 years ago.
I think that the output should be (true true). Sorry for my english
public class A{
public static void main(String[] args) {
Integer i1 = 128;
Integer i2 = 128;
System.out.println(i1 == i2);
Integer i3 = 127;
Integer i4 = 127;
System.out.println(i3 == i4);
}
}
There is a cache of Integer instances for a range of values (at least -128–127), that is used when implicitly converting an int to an Integer.
In this case, 128 is not in the cache, and so each Integer object representing that value is new and distinct.
The value 127, on the other hand, is guaranteed to be in the cache, and so the same instance of Integer is obtained repeatedly.
Integer, as opposed to the primitive int, is an object. Your comparison is comparing two objects of type Integer. I'm kind of surprised you get "false true". If you instead try:
System.out.println(i1.intValue() == i2.intValue());
System.out.println(i3.intValue() == i4.intValue());
you should get the expected result.

Why do == comparisons with Integer.valueOf(String) give different results for 127 and 128?

I have no idea why these lines of code return different values:
System.out.println(Integer.valueOf("127")==Integer.valueOf("127"));
System.out.println(Integer.valueOf("128")==Integer.valueOf("128"));
System.out.println(Integer.parseInt("128")==Integer.valueOf("128"));
The output is:
true
false
true
Why does the first one return true and the second one return false? Is there something different that I don't know between 127 and 128? (Of course I know that 127 < 128.)
Also, why does the third one return true?
I have read the answer of this question, but I still didn't get how it can return true, and why the code in second line returns false.
There's a striking difference here.
valueOf is returning an Integer object, which may have its values cached between -128 and 127. This is why the first value returns true - it's cached - and the second value returns false - 128 isn't a cached value, so you're getting two separate Integer instances.
It is important to note that you are comparing references with Integer#valueOf, and if you are comparing a value that is larger than what the cache supports, it will not evaluate to true, even if the parsed values are equivalent (case in point: Integer.valueOf(128) == Integer.valueOf(128)). You must use equals() instead.
parseInt is returning a primitive int. This is why the third value returns true - 128 == 128 is evaluated, and is of course, true.
Now, a fair bit happens to make that third result true:
An unboxing conversion occurs with respect to the equivalence operator you're using and the datatypes you have - namely, int and Integer. You're getting an Integer from valueOf on the right hand side, of course.
After the conversion, you're comparing two primitive int values. Comparison happens just as you would expect it to with respect to primitives, so you wind up comparing 128 and 128.
The Integer class has a static cache, that stores 256 special Integer objects - one for every value between -128 and 127. With that in mind, consider the difference between these three.
new Integer(123);
This (obviously) makes a brand new Integer object.
Integer.parseInt("123");
This returns an int primitive value after parsing the String.
Integer.valueOf("123");
This is more complex than the others. It starts off by parsing the String. Then, if the value is between -128 and 127, it returns the corresponding object from the static cache. If the value is outside of this range, then it invokes new Integer() and passes in the value, so that you get a new object.
Now, consider the three expressions in the question.
Integer.valueOf("127")==Integer.valueOf("127");
This returns true, because the Integer whose value is 127 is retrieved twice from the static cache, and compared to itself. There's only one Integer object involved, so this returns true.
Integer.valueOf("128")==Integer.valueOf("128");
This returns false, because 128 is not in the static cache. So a new Integer is created for each side of the equality. Since there are two different Integer objects, and == for objects only returns true if both sides are the exact same object, this is going to be false.
Integer.parseInt("128")==Integer.valueOf("128");
This is comparing the primitive int value 128 on the left, with a newly created Integer object on the right. But because it doesn't make sense to compare an int to an Integer, Java will auto-unbox the Integer before doing the comparison; so you end up comparing an int to an int. Since the primitive 128 is equal to itself, this returns true.
Take care of returning values from these methods. The valueOf method returns an Integer instance:
public static Integer valueOf(int i)
The parseInt method returns integer value (primitive type):
public static int parseInt(String s) throws NumberFormatException
Explanation for comparison:
In order to save memory, two instances of the
wrapper objects , will always be == when their
primitive values are the same:
Boolean
Byte
Character from \u0000 to \u007f (7f is 127 in decimal)
Short and Integer from -128 to 127
When == is used to compare a primitive to a wrapper, the wrapper will be
unwrapped and the comparison will be primitive to primitive.
In your situation (according to the above rules):
Integer.valueOf("127")==Integer.valueOf("127")
This expression compares references to the same object because it contains Integer value between -128 and 127 so it returns true.
Integer.valueOf("128")==Integer.valueOf("128")
This expression compares references to different objects because they contain Integer values not in <-128, 127> so it returns false.
Integer.parseInt("128")==Integer.valueOf("128")
This expression compares primitive value (left hand side) and reference to the object (right hand side)
so right hand side will be unwrapped and his primitive type will be compared to the left so it returns true.
Integer objects caches between -128 and 127 of 256 Integer
You should not compare object references with == or !=. You should use .equals(..) instead, or better - use the primitive int rather than Integer.
parseInt: Parses the string argument as a signed decimal integer. The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value. The resulting integer value is returned, exactly as if the argument and the radix 10 were given as arguments to the parseInt(java.lang.String, int) method.
valueOf
Returns an Integer object holding the value extracted from the specified String when parsed with the radix given by the second argument. The first argument is interpreted as representing a signed integer in the radix specified by the second argument, exactly as if the arguments were given to the parseInt(java.lang.String, int) method. The result is an Integer object that represents the integer value specified by the string.
equivalent to
new Integer(Integer.parseInt(s, radix))
radix - the radix to be used in interpreting s
so if you equal Integer.valueOf() for the integer inbetween
-128 to 127 it returns true in your condition
for lesser than -128 and greater than 127 it gives false
To complement the given answers, also take note of the following:
public class Test {
public static void main(String... args) {
Integer a = new Integer(129);
Integer b = new Integer(129);
System.out.println(a == b);
}
}
This code will also print: false
As user Jay has claimed in a comment for the accepted answer, care must be taken when using operator == on objects, here you're checking if both references are the same, which is not, because they are different objets, although they represent the very same value. To compare objects, you should use the equals method instead:
Integer a = new Integer(128);
Integer b = new Integer(128);
System.out.println(a.equals(b));
This will print: true
You may ask, But then why the first line printed true?. Checking the source code for the Integer.valueOf method, you can see the following:
public static Integer valueOf(String s) throws NumberFormatException {
return Integer.valueOf(parseInt(s, 10));
}
public static Integer valueOf(int i) {
assert IntegerCache.high >= 127;
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
If the param is an integer between IntegerCache.low (defaulted to -128) and IntegerCache.high (calculated at runtime with minimum value 127) then a pre-allocated (cached) object is returned. So when you use 127 as parameter, you're getting two references to same cached object and getting true in the comparison of the references.

what should be the primitive type of an integer with size 9bytes or more than 9 bytes?

I am creating a bank account.which has a 'accnum' as variable.which has integer value with size of 12 bytes.
let say the bank account number is 180020131111.How do you initialize to a variable?
public class number{
public static void main(String[] args){
private long x=180020131111; // is not working..
System.out.println(x);
}
}
180020131111 is an integer literal, which cannot fit into an int type. You should append an L at the end to make it long literal.
private long x = 180020131111L;
Well, I would rather store account number as String. I don't think there is really any need for storing it as numeral, as you are just going to display it. I mean it would really look weird if you are going to do some arithmetic operations on account numbers.
By default Integral Literals are treated as 32 bit int and not 64 bit long in java..
Use this
private long x=180020131111L;
The character l ot L at the end makes integral literals long
The largest Java primitive integral type is long which is a 64 bit (8 byte) signed type. If you want to represent numbers larger that 263 - 1 == 9,223,372,036,854,775,807, you need to use BigInteger or BigDecimal.
The problem with this statement ...
private long x=180020131111;
... is that you are using the syntax for an int literal. A long literal requires a l or L suffix. (FWIW - this number does not require 9 bytes to represent ...)

compare Long value in java [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Integer == int allowed in java
What is the difference between the following two statements
Long l1 = 2L;
if(l1 == 2)
System.out.println("EQUAL");
if(l1.longValue() == 2)
System.out.println("EQUAL");
They both are giving same result "EQUAL".But my doubt is Long is object. How is it equal?
As already pointed out in the comments, when doing
if(l1 == 2)
Long l1 gets automatically unboxed to its primitive type, long. So the comparison is between long and int.
In the second case, l1.longValue() will return the long value, as a primitive, of the Long represented by the Long object, so the comparison will be again between long and int. Answering your comment, take a look at What is the main difference between primitive type and wrapper class?
The link given in the comments about autoboxing covers this subject quite well.
This behaviour is explained by widening and boxing.
In the first example,
if(l1 == 2)
what happens is as follows:
1: The compiler notices that you are comparing a wrapper (Long) with a primitive value (int), so it boxes the primitive, resulting in:
if (l1 == new Integer(2))
since 2 is an int (it lacks the 'L' at the end).
2: The compiler now notices that we are comparing a Long with an Integer, so it widens the Integer to a Long, resulting in:
if (l1 == new Long(new Integer(2))
3: Now we are comparing two Longs.
The other case is simpler, here the result is simply:
if (2L == 2)
comparing the primitive values, which is allowed even though they are different types.

Categories