-4

I hope somebody could give me an explaination why the below code wont work:

            //Why doesnt this work
            String l = myString.substring(cut,  lengthLastBtn-1);
            String c = myString.substring(cut,  lengthLastBtn-1);

            if(l==c){
                Log.i(TAG, "Correct");
            }
            //End

            //This work!
            String l = "hi";
            String c = "hi";

            if(l==c){
                Log.i(TAG, "Correct");
            }
            // End

            // Or if i want the Vars as in the first code i have to use the if statement like this
            if(l.contains(c)){
                Log.i(TAG, "Correct");
            }
            //End

So, why cant a compare a string when i have used the substring method on it. I even see in the log for the strings that they are the same, or have the same text at least.

user3711421
  • 1,658
  • 3
  • 20
  • 37

1 Answers1

1

When you use the “==“ operator with String`s, it means a comparison between objects, not the value that objects hold.

In order to compare Strings values , you should use the built-in method equals. The result is true if the String object represents the same sequence of characters.

if(string1.equals(string2)) {
     //Match 
} 
Víctor Albertos
  • 8,093
  • 5
  • 43
  • 71