-3

i have the following piece of code but i could not detect why there is no output when i debug it , the control flow is never goes inside for loop but i cannot figure out why

could anyone please help me ? here is my code

public class DealWithStrings {
    ArrayList<String> container = new ArrayList<>();

    public void printDuplicate() {
        String string = "aaabed";
        String[] res = string.split("");

        for (int i = 1; i < string.length(); i++) {
            if (res[i] == res[i - 1]) {
                container.add(res[i]);
            }
        }

        for (String s : container) {
            System.out.println(s);
        }
    }

    public static void main(String[] args) {
        DealWithStrings d = new DealWithStrings();
        d.printDuplicate();
    }
}
Adrien Brunelat
  • 4,492
  • 4
  • 29
  • 42
Abed
  • 7
  • 2

2 Answers2

3

Compare String using .equals, not ==

Instead of

if(res[i]==res[i-1])

Use

if(res[i].equals(res[i-1]))

== will evaluate to true if the objects are the same, and in this case they never are. .equals will check if the contents of the Strings (the actual text) are the same.

Henrik Aasted Sørensen
  • 6,966
  • 11
  • 51
  • 60
Stefan
  • 2,395
  • 4
  • 15
  • 32
1

Replace your code '==' operator with '.equals()' method, because , '==' equal operator compares the reference of the two characters in memory, whereas you need to check 'contents' at that reference.

And .equals method is overridden to check the content for Strings.

for (int i = 1; i < string.length(); i++) {
        if (res[i].equals(res[i - 1])) {
            container.add(res[i]);
        }
    }
Jabongg
  • 2,099
  • 2
  • 15
  • 32