So i've been learning java for a few months and i quickly found out when you try to compare Strings with == it doesn't work, and that to compare objects you have to use the .equals() method.
However I have just started learning about GUIs and actionListeners and i wrote a program and accidentally tried to compare two strings with == but for some reason the program worked. Below i've wrote a simplified example out which demonstrates this.
So the getActionCommand() method returns a String. And when used on a button it returns a String of what is written on the button. Which on my program is "I am a button wahoo". The first if statement compares the String returned by getActionCommand() with "I am a button wahoo", and changes the text on the button.
And the text on the button does changed when i run the program. Can anyone tell me why in this case comparing the strings using == is working? Thanks in advance for any help.
The reason is to save memory String objects are stored in a pool like structure. In some cases, if the content is same, they might refer to the same object. In such cases, '==' operator would work. But, this can't be relied upon.
Because you have written "I am a new button" in each of those places, the compiler can recognise those as identical Strings. The same String object is used for all; comparison with the == operator will return true. If, however, the compiler cannot recognise those Strings as identical, different String objects will be used an the == operator will return false.