0

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?

ii_578
  • 11
  • 1
  • 1
    Already answered here: [ difference between == and equals() in Java](https://stackoverflow.com/questions/7520432/what-is-the-difference-between-and-equals-in-java) – nobi malik May 19 '19 at 08:04
  • Have a look at this article: https://gist.github.com/Yengas/9040261 – sekky May 19 '19 at 08:06
  • Thanks for answering nobi malik, but I've read it and still don't understand why == triggers both if and else, while .equals doesn't. I think I understand the difference between the two, but now how it applies to my situation. – ii_578 May 19 '19 at 08:06
  • 1
    @ii_578 Using `equals()` vs `==` is the main problem, but the other problem is that you are looking for the first case where the given string is not equal to the already saved array elements, not for all the strings in the array. You need to rewrite it in a way that you check **all** the entries and decide **after** that if you want to add the new string to your array or not. You need to define some `hasFound` boolean variable which you check after the `for` loop to add the new string to the array (or not). – Progman May 19 '19 at 08:54
  • @Progman thanks, I've become aware of this too. But what puzzles me most is how my condition can be both True and False (why is the Else executed after the if when using == and the Break is ignored). I'm yet to find an answer. – ii_578 May 19 '19 at 09:04
  • 1
    @ii_578 It doesn't execute the `if` and `else` part at the same time, that's not how `if()` is working. But keep in mind that you are in some loops, so you might enter this code again in the next iteration. And in the next iteration you will get into the other branch. Use a debugger and use single steps to see which `for` loop iteration you are in and where there thread is going. – Progman May 19 '19 at 09:08

2 Answers2

0

In Java, == compares the object's references, not the object's contents. That is, with == you check whether the two references point to the same object in memory (which implies that they also have the same contents). With .equals(), however, you check whether the contents of the objects, i.e. the string characters, are the same. Also see e.g. What is the difference between == and equals() in Java?.

Edit: Here's a working example that tries to stick as close to your original code as possible:

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();

    boolean alreadyContains = false;

    for (int k=0; k<i; k++) {
        AnArray1 = AnArray[k];
        if (astring.equals(AnArray1)) {
            alreadyContains = true;
            break;
        }
    }

    if (alreadyContains) {
        System.out.println ("String already used");
    } else {
        AnArray[i] = astring;   
    }
}    

for (String AnArray1 : AnArray) {
    System.out.println(AnArray1);
}
sschuberth
  • 28,386
  • 6
  • 101
  • 146
  • But aren't they the same in my example if I use either .equals() or ==? In both cases the if condition is met since it's True. Then it should break. Why does it continue with the else after the if condition was met? – ii_578 May 19 '19 at 08:13
  • Another problem is that in the inner `for`-loop you iterate over the whole `AnArray` although not all strings in there have been initialized yet, i.e. they default to `null` (and it is `null` == `null`). You can fix that by replacing `for (String AnArray1 : AnArray) {` with `for (int k=0; k – sschuberth May 20 '19 at 07:01
0

I hope the below summary helps you in your case:

  1. use == to compare primitive e.g. boolean, int, char etc, while use equals() to compare objects in Java.

  2. == return true if two reference are of same object. Result of equals() method depends on overridden implementation.

  3. For comparing String use equals() instead of == equality operator.

nobi malik
  • 57
  • 8
  • I understand this. The essence of my question is: why does == trigger BOTH if and else. Else triggers if the condition is False, while if if it's True. How is it both True and False? – ii_578 May 19 '19 at 08:18