1

I have a problem with comparing strings: I get the string value of "activation" in string.xml. When I compare it with a string value that has the same value, the result is always false (in string.xml activation = test)

<?xml version="1.0" encoding="utf-8"?>
<resources> 
    <string name="app_name">MyNameApp</string>
    <string name="activation">test</string>
</resources>

public class CheckGenuine {     
    public static String cod;
    public static String app;

    public static Boolean chk(Context ctx) {    
        Boolean ret;
        cod = ctx.getString(R.string.activation);
        app = ctx.getString(R.string.app_name);

        if (cod == "test") {
            Toast.makeText(ctx, "True cod = " + cod, Toast.LENGTH_LONG).show();     
            ret = true;} 
        else {
            Toast.makeText(ctx, "False cod = " + cod, Toast.LENGTH_LONG).show();  
            ret = false;}

  // *** why ret is always false and Toast shows "False cod = test"   ????????????????  

        return ret;     
    }   

}
Samet ÖZTOPRAK
  • 3,112
  • 3
  • 32
  • 33

3 Answers3

4

You should be using .equals() to compare String values, not the == operator. This article does a good job of explaining the difference.

wsanville
  • 37,158
  • 8
  • 76
  • 101
1

Use if (cod.equals("test")) {

== ->> compares string refrences(Memory location)

.equals() compares string value.

Samir Mangroliya
  • 39,918
  • 16
  • 117
  • 134
0

String comparison is carried out by equals() function in Java, if you use '== operation', it means to compare by 2 objects itself, not by values.

String value = "myString"
if (value.equals("myString")) {
}
Samet ÖZTOPRAK
  • 3,112
  • 3
  • 32
  • 33