Program considers two equal doubles to be different [duplicate] - java

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.

Related

Comparing Integer and int with == [duplicate]

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!

mysql varchar does not compute with java string [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
my case:
I try to get a value from my MySQL database. This data is defined as a VARCHAR.
This is done in java with a prepared statement and resultset.
String add1 =rs.getString("include");
according to this website table 5.1 states "Can always be converted to these Java types".
therefore a VARCHAR should be able to be converted in a java.lang.string.
When i check the data type in java it indeed gives java.lang.string. So for so good.
My issue is when i try to compare this obtained "String" value to a in java defined String value they don't seem to be equal.
Let's give a simple example.
I get the (VARCHAR) value "1" from the database and store in in String add1
I want to check if this value is indeed "1" and therefore I use the following statement
if(add1=="1")
{
/* do something */
}
Only the values are , according to java, not the same. So I was curious about why this is.
I started searching why those two "Strings" are not equal.
First of I checked the length of both strings. Both came out to be 1 in length as expected.
Afterwards I checked the value of both. To see if both values where indeed the same i wanted to check their hexadecimal representance.
Both came out with the value 0x31. Still as expected.
But then why isn't my if statement accepted by java if both seem to represent the same string-hex-bin-you name it value.
In short: Why is my VARCHAR "String" obtained from a MySQL databse in java not the same as a String defined in java.
Compare values, not memory references:
if(add1.equals("1"))
{
/* do something */
}
Please see this post best answer.
You must always compare strings with the .equals method in your case it will be
add1.equals("1")
"==" or equality operator in Java is a binary operator It is good for compairing primitives like boolean, int, float "==" works fine but when it comes to compare objects it creates confusion with equals method in Java. "==" compare two objects based on memory reference. so "==" operator will return true only if two object reference it is comparing represent exactly same object otherwise "==" will return false.
String comparison is a common scenario of using both == and equals method. Since java.lang.String class override equals method, It return true if two String object contains same content but == will only return true if two references are pointing to same object.
Read more: http://javarevisited.blogspot.com/2012/12/difference-between-equals-method-and-equality-operator-java.html#ixzz3PdLbOre0
You need to compare the Strings with .equals() method. because == checks for object reference.
What is the difference between == vs equals() in Java?

Why does this md5 not match [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
i recently started to do some encryption with Apache DigestUtils. I simply want to use md5 hashes for authorization, but i'm an absolute beginner in this topic and in general not really experienced in Java. The API of this library provided me the methods md5, md5hex.
If i'm not mistaken the result of these just differs in the output as a hexString (i'm not even sure whats this means) and regular bytes.
String b1 = DigestUtils.md5hex("Some String");
String b2 = DigestUtils.md5hex("Some String");
The result is 83beb8c4fa4596c8f7b565d390f494e2 & 83beb8c4fa4596c8f7b565d390f494e2
But a comparison with == results in false
if (b1 == b2){
System.out.println("Matching")
}
I'm pretty confused and i can't find a source for an introduction around this topic(for java!)
Because == is not how Strings are compared in Java, use .equals
For example...
if (b1.equals(b2)) {...
"==" means to compare with the values.
If you compare two object-type objects(such as String, Date), the compared value is their unique reference address in the jvm. That means you want to know if they are the same object
If you compare two primitive types(such as int, float, double...), the compared value is their real values.
So if we want to compare two objects, we usually use equals() function instead of "==", because we just want to know if they they have the same attribute values.
Further more, If you define you own class, you should override the equals() function to compare objects of the class.

Can any one explain the asserTrue why it is failed? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I compare strings in Java?
Java String.equals versus ==
I am new to Selenium and Java.
I have tried the below to compare the field value of last name to the one which i supplied.
String lastname=selenium.getValue("//*[#id='lastName']");
System.out.println(lastname);
assertTrue (lastname == "xxx");
It is keep on failing.
Just literally tried to change the last line with help of Eclipse (just trial and error)
assertTrue("lastname.equals("xxx"));
It is working fine... Why it is failed in first case? == is not allowed to compare strings?
Short answer: == checks for same object .equals checks for the same value.
More info in How do I compare strings in Java?
equals function checks the actual contents of the lastname. == operator checks whether the references to the objects are equal.
You must use equals() to compare strings with Java, as you guessed.
You're actually comparing pointers (or really reference equality) when you use == with strings. In other words you're testing if two objects are the same, rather than the content of the objects.
For comparing equality of string ,We Use equals() Method. There are two ways of comparison in java. One is "==" operator and another "equals()" method . "==" compares the reference value of string object whereas equals() method is present in the java.lang.Object class. This method compares content of the string object.

Comparing two strings in Java [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java String.equals versus ==
I know it' a dumb question but why this code doesn't work.
boolean correct = "SampleText" == ((EditText)findViewById(R.id.editText1)).getText().toString();
if(correct) ((TextView)findViewById(R.id.textView1)).setText("correct!");
else ((TextView)findViewById(R.id.textView1)).setText("uncorrect!");
The point is to check if content of "editText1" is equal to "Sample Text"
In Java, two strings (and in general, two objects) must be compared using equals(), not ==. The == operator tests for identity (meaning: testing if two objects are exactly the same in memory), whereas the method equals() tests two objects for equality (meaning: testing if two objects have the same value), no matter if they're two different objects. Almost always you're interested in equality, not in identity.
To fix your code, do this:
String str = ((EditText)findViewById(R.id.editText1)).getText().toString();
boolean correct = "SampleText".equals(str);
Also notice that it's a good practice to put the string literal first in the call to equals(), in this way you're safe in case the second string is null, avoiding a possible NullPointerException.
In Java Strings have to be compared with their equals() method:
String foo = "foo";
String bar = "bar";
if (foo.equals(bar)) System.out.println("correct");
else System.out.println("incorrect");
to compare the values for two strings (for equality), you need to use equals, not == (or use equalsIgnoreCase if you do not care about case sensitivity).
Using equals will check the contents/values of the strings (as opposed to "==" which will only check if the two variables point to the same object - not the same value).
The correct way to compare 2 objects in java is using equals() method of Object class
And as String is an object in java, it should be compared in same way.
The correct way to compare a String is with,
s1.equals(s2)
So you can use this,
boolean correct = "SampleText".equals(((EditText)findViewById(R.id.editText1)).getText().toString());
((TextView)findViewById(R.id.textView1)).setText("SampleTest".equals(((EditText)findViewById(R.id.editText1)).getText().toString()) ? "correct!" : "incorrect!");
It's a bit long and theres probably a better way you could do this. The .toString() feels weird!

Categories