0

I'm new to Java (and to programming in general). I have a program that is supposed to run a method on two variable strings, but only if the strings are the same length and are not identical.

I've tried using

while(i < n){
    if (string1.length() == string2.length() && string1 != string2){
        compare(string1, string2);
        i++
    }
}

but it still runs the compare method even if the strings are identical.

I've also tried using

while(i < n){
    if (string1.length() == string2.length(){
        if (string1 == string2){
            continue;
        }
        compare(string1, string2);
    }
    i++
}

but this also still runs the compare method regardless of whether or not the strings are identical.

Is there an issue with my formatting, or perhaps misused keywords? Thanks!

3 Answers3

1

This string1 != string2 does not test String value equality, only reference equality. You need !string1.equals(string2). Or your while would need to be something like,

if (string1.equals(string2)) {
  // ... they're equal.
}

It is also worth noting that the two String(s) must have the same length() or equals() would return false.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

Using equals() method instead of ==. Double equal sign can't use in object compare.

0

Change

if (string1.length() == string2.length() && string1 != string2)

With

if (string1.length() == string2.length() && !string1.equals(string2))

== check the reference equality. when you come in to String variables they have two different reference in the heap while having same value. To check the equality of values you should use equals()

Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115