Java newbie here, I'm experimenting with some simple code using NetBeans. The program simply takes in a few strings into an Array of a predetermined length, while not allowing the previously used ones to be added.
String[] AnArray = new String[3];
for (int i=0; i<AnArray.length; i++) {
System.out.println("Insert a string:");
Scanner s = new Scanner(System.in);
String astring = s.next();
for (String AnArray1 : AnArray) {
if (astring.equals(AnArray1)) { /* THIS IS WHERE I CHANGE astring.equals(AnArray1) TO astring == AnArray1 */
System.out.println ("String already used");
break;
}
else
AnArray[i] = astring;
}
}
for (String AnArray1 : AnArray) {
System.out.println(AnArray1);
}
If the string was already used, it should print out a message "String already used" and not add it, leaving the field empty (null).
If I use .equals, it works correctly (well, as I expect it to). However, if I use '==' it prints out the message, but still adds the (already used) string to the Array.
Note: All advice is appreciated, but I'd be most grateful for an explanation as to HOW/WHY this IS happening (as opposed to what I should do to improve my code).
EDIT: I don't see how this is a duplicate. If someone can paste the relevant part of the answer to my question, I would be grateful. My question is: since the condition is True in BOTH cases (using == or .equals) why does the .equals() follow the break command while == triggers else AS IF it's ALSO false?