0

I've tested this on several different methods. The string I compare s to is exactly the same as the one that shows up in the log file. The apostrophes are to make sure there's no spaces. Anyone know what's going on?

import java.lang.reflect.Method;
import android.util.Log;

public class Button {
    public Button () {
        for(Method m1:MyOtherClass.class.getMethods()) {
        String s = m1.getName();
            if(s == "Update") {
                Log.i("result","true");
            }
            Log.i("test", "'" + s + "'");
        }
    }
}
Dennis Meng
  • 5,109
  • 14
  • 33
  • 36

4 Answers4

5

Your problem is in:

if(s == "Update")

Replace it with

if (s.equals("Update"))

== compares references when dealing with Objects (like String), not content/value.

Dennis Meng
  • 5,109
  • 14
  • 33
  • 36
1

Don't compare Strings (or any Objects) by ==. Use s.equals("Update")

== is used to check if references contains same Objects, not if Objects contains same values,

for example

Integer i1=new Integer(1);
Integer i2=new Integer(1);
Integer i3=i1;
//checking references
System.out.println(i1==i2);//false
System.out.println(i1==i3);//true

//checking values
System.out.println(i1.equals(i2));//true
System.out.println(i1.equals(i3));//true
Pshemo
  • 122,468
  • 25
  • 185
  • 269
1

Use equals() method from String class.

TeaCupApp
  • 11,316
  • 18
  • 70
  • 150
0

Use "Update".equals(s) This does proper value comparison.

devang
  • 5,376
  • 7
  • 34
  • 49