This question already has answers here:
How can I properly compare two Integers in Java?
(10 answers)
Is it safe to compare two `Integer` values with `==` in Java? [duplicate]
(2 answers)
How do I compare two Integers? [duplicate]
(9 answers)
Comparing Integer objects [duplicate]
(5 answers)
Closed 1 year ago.
List<Integer> test = List.of(955, 955);
if (test.get(1) == test.get(0))
...
Above condition results in false
List<Integer> test = List.of(955, 955);
int a = test.get(1);
int b = test.get(0);
if (a == b)
...
The above condition returns true.
Why is that the case? What is the difference between the snippets?
In one case, you're comparing two Integer object references. In the other case, you're comparing two ints. When using the == operator to compare object references, it will return False if they are not the same object, even if they do wrap the same value.
In the first example, you are comparing references. In your example, you have two different objects with different references and the same values.
In the second example, you are using automatic unboxing which creates new integers in stack memory, and integer comparison which works what you expect. Automatic unboxing can produce NullPointerException in case of null.
First Code Snippet:
You are comparing the object reference, meaning the specific object reference that the object is pointing too. In this case you are comparing an Integer which is a wrapper class for int.
Second Code Snippet:
You are comparing the an 'int' to another 'int'.
Example:
Think about it this way: if two people had the name John, in the first scenario we are comparing the people named John, whereas in the second scenario we are comparing the name John only. I hope that helped!
Related
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
String str1 = "abc:5";
String str2 = "abc:" + str1.length();
String str3 = "abc:" + 5;
System.out.println(str1==str2);
System.out.println(str1==str3);
Output of the program is :
false
true
But I don't understand why?
== operator will compare reference only
.equals() will compare the values.
in your case
str1==str2 // compares the two references, which are different.
had it been, str1.equals(str2), it would have compared the values, which will return true
The “==” operator
In Java, when the “==” operator is used to compare 2 objects, it checks to see if the objects refer to the same place in memory. In other words, it checks to see if the 2 object names are basically references to the same memory location.The “==” operator compares the objects’ location(s) in memory
The “equals” method
The Java String class actually overrides the default equals() implementation in the Object class – and it overrides the method so that it checks only the values of the strings, not their locations in memory.
Here str1 = "abc:5"; is located in constant pool of string and str2 is concatenated with 2 different object with new operator. So both str1 and str2 are referring to different object. That's the reason it is showing false.
The == operator is used for only reference variables in java. For example if you are comparing characters a1 and a2 you can use the == operator because the char type is highlighted in most IDEs in Java. To check if two Strings are equal to each other you can use .equals()or .equalsIgnoreCase() to compare the Strings. This is because Strings are objects, not primitives, and require their own method in the class to test if Strings are the same.
For the first System.out.println(); statement, you would use System.out.println(str1.equals(str2)); or System.out.println(str1.equalsIgnoreCase(str2));.
For the second System.out.println(); statement, you would use System.out.println(str1.equals(str3)); or System.out.println(str1.equalsIgnoreCase(str3));.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
What is "==" in Java ? Why can i only compare numerical data type with it and characters can be compared. But not the string data types. What does it provide when i compare two strings?
== compares reference equality: it returns true if its operands have the same value on the stack. (that is, they are either the same numerical quantity or they point to the same object)
Strings are objects, so here we're asking whether they point to the same object on the stack. This will be true if we're talking about String literals defined in code:
If we have
String s1 = "Hello";
String s2 = "Hello";
then s1 == s2 => true
However, if one of the Strings is obtained by some run-time process, for example user input, then it will not be reference-identical, even if the contents of the two Strings are the same.
In Java == compare reference two reference value. If left side reference equals to right side reference will return true else false.
When you come to compare String(objects) you should use equals()
Why?
String a= new String("a");
String b= new String("a");
Here a and b are same by value but they have two different reference.
If you compare to objects (strings are objects) you will compare the reference of both objects.
The '==' operator in Java is used to compare similar variables (like an integer and another integer). For an over-complicated reason, Strings are considered 'Object' type variables. To compare strings use the operator variableString.equals(otherString);
This question already has answers here:
Difference between double and Double in comparison
(5 answers)
Closed 8 years ago.
I am comparing two Doubles:
37.4238777160645
and
37.4238777160645
But Java does not consider them to be equal. I am comparing them in the following manner
if(object1.getLatitude()!=object2.getLatitude()){
fail("objects are not equal "+object1.getLatitude()+":"+object2.getLatitude());
}
resulting in the following fail:
junit.framework.AssertionFailedError: objects are not equal 37.4238777160645:37.4238777160645
I don't understand why - Please advise.
The issue has already been pointed out. But if you are using junit, it would be simpler to use the appropriate method:
assertEquals(object1.getLatitude(), object2.getLatitude());
or
assertEquals(object1.getLatitude(), object2.getLatitude(), 0.001d);
instead of using fail. That would also solve your issue.
Objects should be compared with .equals and not ==. By == you're comparing the references, which are not the same since you return a different object each time.
Use Double#equals to compare the values.
You should use java.lang.Double.compare() :
Double.compare(object1.getLatitude(), object2.getLatitude())
so you wil have :
if(Double.compare(object1.getLatitude(), object2.getLatitude()) != 0){
fail("objects are not equal "+object1.getLatitude()+":"+object2.getLatitude());
}
When applied to objects, the == operator returns true only when both operands are the same object.
Your method returns Double objects, so each call will produce a new object, and comparing them using == will always be false.
Use .equals(), which compares values of the Doubles:
if (!object1.getLatitude().equals(object2.getLatitude()))
Alternatively, change you methods to return double instead of Double, and your current code will work.
Floating point comparison in may programming languages should always take the form of
if(a-b op c)
where a and b are the numbers being compared and c being the threshold and op is either > or
<
.
This is because floating point representation in binary to not map directly to what is printed.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
1) if I set
int[] set1 = new int[]{1, 2};
int[] set2 = new int[]{1, 2};
how come when I pass them as strings using
System.out.println(Arrays.toString(set1) == Arrays.toString(set2));
it returns false?
2) Is there any way to compare equality of entire arrays without looping through each index of the array?
Strings are Objects, so they should be compared using equals:
System.out.println(Arrays.toString(set1).equals(Arrays.toString(set2))); //prints true
Use Arrays#equals to compare arrays, note that the arrays must have the same length and the items must be equals: == for primitives (int, long ...) and equals for Object references).
== compares string references, not values. Use str1.equals(str2). (more information on this here; it basically compare whether the actual objects are the same, not the string content)
No, naturally if you want to know if each element is the same you'll have to loop through all of them. Arrays#toString does this behind the scenes also (how else would it get a string representation?).
Sidenote: converting an array to a string introduces a lot of unnecessary overhead (string manipulation, etc.). You should probably just loop through and compare elements, or create a helper method (or use a built-in one like Arrays#equals).
Use Arrays.equals to compare arrays and see this for Strings comparisons.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
Can you explain me why do I have "false" output? If I understand correctly, references point to the same object!
public class mainC {
String str1,str2;
public static void main(String [] args){
mainC m=new mainC();
m.str1="a";
m.str2="b";
System.out.print("m.str1 == m.str2: "+m.str1 == m.str2);
}
}
Thank you.
m.str1 and m.str2 point to different String objects, which is why you get false. The == compares str1 and str2, not m.
Side note: Now, if you had:
m.str1="a";
m.str2="a"; // Same series of characters, e.g., "a"
...you'd be getting true, but it would be misleading. == compares object references. So you can have two different String objects that have the same characters in them, but they would not be == to each other (in fact, that's quite common). To compare strings, you use equals. The reason my example above returns true is that both strings are initialized pointing to literals, and String literals in Java are intern'd by default, so that literals with the same characters are mapped to the same object.
A string in Java is implemented as a reference type and not a value type. Since this is the case, their pointers in memory aren't equal. To get around this, you can use their equals function to compare them.