I have two string in Java:
String a = "ab";
String b = "ab";
And I test them with the string.equals()
method because the ==
operator only checks whether the references to the objects are equal.
Why can I use ==
in JavaScript?
I have two string in Java:
String a = "ab";
String b = "ab";
And I test them with the string.equals()
method because the ==
operator only checks whether the references to the objects are equal.
Why can I use ==
in JavaScript?
In Java, you should use String.equals()
== Operator in Java is detecting if they are the same object on both side since String in Java is a Object but not primitive like int, float. == Will check if they have same address
Exmaple:
String a = new String("hello");
String b = "hello";
a.equals(b) // true
a == b // false
a and b are not the same object, But they have same content.
In Java ==
compares whether the variables are pointing to the same object. It does not do a semantic comparison. In Javascript the ==
compares the strings.
String a = "ab";
is assigning the value.
==
in Java checks there reference of the strings to each other. .equals()
checks the values.
You should look at this question for more answers on .equals vs == in java
Also for completeness, I should mention in javascript you can also do ===
so things like null equal to false.
true === 1 //false
true == 1 //true