+ 1
Getting same result for both == and equals();
please tell me why I'm getting "true" for both of these situations public class App { public static void main(String[] args) { String a1 = "jina"; String a2 = "jina"; System.out.println(a1==a2); System.out.println(a1.equals(a2)); } }
3 odpowiedzi
+ 23
Strings in java are objects, so when comparing with ==, you are comparing references, rather than values. The correct way is to use equals().
Using == is true. Because the JVM has a table of String constants. So whenever you use string literals (quotes "), the virtual machine returns the same objects
@Stack overflow
+ 15
some interesting explanation in the following page:
focus on the answer which starts with:
"Difference between == and equals confused me for sometime until I decided to have a closer look at it. ....."
https://stackoverflow.com/questions/7520432/what-is-the-difference-between-vs-equals-in-java