Home » Android » java – Why is my String to String comparison failing?

java – Why is my String to String comparison failing?

Posted by: admin May 14, 2020 Leave a comment


I have an Android app where I want to check to see if an app name that is installed matches a string passed to the function containing this code. The code and example is below:

private Boolean checkInstalledApp(String appName){
    PackageManager pm = this.getPackageManager(); 
    Intent mainIntent = new Intent(Intent.ACTION_MAIN, null); 
    List<ResolveInfo> list = pm.queryIntentActivities(mainIntent, 0);
    Boolean isInstalled = false;
    for(ResolveInfo info: list) {
      if (info.activityInfo.applicationInfo.loadLabel( pm ).toString()==appName){
          isInstalled = true;

    return isInstalled;

Assuming you called checkInstalledApp("SetCPU"); and the app name on the phone is called the same thing it should return true. However, it never does. I logged the results and it should match up but it does not. Can anyone please enlighten me as to why this doesn’t work?

How to&Answers:

Use the String’s equals() method instead of the == operator for comparing strings:

info.activityInfo.applicationInfo.loadLabel( pm ).toString().equals(appName)

In Java, one of the most common mistakes newcomers meet is using == to compare Strings. You have to remember, == compares the object references, not the content.


Check out number 7: Top 10 – New Java Developer Errors


public static boolean compaireString (String string, String string2) 
    // string == null && String2 == null or they reference the same object
    if (string == string2) return true;
    //we have to be sure that string is not null before calling a methode on it
    if (string != null && string.equals(string2)) return true;

   return false;