Quote:
Originally Posted by jjshabado
Also, Strings are objects in Java so you want to use ‘.equals’ instead of == so that you’re comparing the content of the string and not the object reference.
Yeah this is going to be the issue. Usually you do it like
Quote:
if("Hello".equals(answer)) { ...
that's safer, because if you do if(answer.equals("Hello")) then it will throw a NullPointerException when answer is null (which it won't be here, but it's a good habit).
To expand on equality a bit more, in Java == does value comparison for primitive types. So:
Quote:
int x = 1;
int y = 1;
boolean areEqual = (x == y) //true
But for objects, == is a reference comparison. Object variables are actually pointers to a location in memory. == tests if they point to the same location. So:
Quote:
String x = "hi";
String y = "hi";
boolean areEqual = (x == y); //false
areEqual = (x.equals(y)); //true
y = x;
areEqual = (x == y); //true, because it's not just that they're both "hi", they're both the SAME "hi", at the same place in memory. y = x, for objects, says "point y to the same place in memory as x".
Other similar languages (like C#) make an exception for strings and do a value comparison for ==, but Java doesn't, basically because it's the mission of Java to be as pedantic as possible and make your life difficult.
Also, if you write your code in IntelliJ (which is free, for the basic edition), it will warn you about your dubious use of == and you can set breakpoints and debug to see the execution path your code is taking.