-1

I think Method A will displays "Ok", but in fact it displays "Fails". The Method B can get the correct result "OK".

I'm sure that the function fi.iki.elonen.NanoHTTPD.getMimeTypeForFile("my.css") will return the result "text/css".

I don't understand why the Method A can't get correct result. Is there some bugs with the function fi.iki.elonen.NanoHTTPD.getMimeTypeForFile ?

BTW, Method C can get the correct result "OK".

Method A

String a="text/css";
String b= fi.iki.elonen.NanoHTTPD.getMimeTypeForFile("my.css");

Utility.LogError("B: "+b);

if (a==b){
    Utility.LogError("Ok");
}else{
    Utility.LogError("Fails");
}

Method B

   String a="text/css";
    String b= fi.iki.elonen.NanoHTTPD.getMimeTypeForFile("my.css");

    Utility.LogError("B: "+b);

    if (a.compareTo(b)==0){
        Utility.LogError("Ok");
    }else{
        Utility.LogError("Fails");
    }

Method C

   String a="text/css";
   String b= "text/css";

    Utility.LogError("B: "+b);

    if (a==b){
        Utility.LogError("Ok");
    }else{
        Utility.LogError("Fails");
    }
HelloCW
  • 843
  • 22
  • 125
  • 310

4 Answers4

2

Method 1

It results to "Fails" It because the actual objects on heap are getting compared when you use == reference : Detailed explanation

Method 2

It results in Ok as a and b contain same text(mime type) in them (using compare to)

Method 3

It results in Ok, as expected.

Community
  • 1
  • 1
cafebabe1991
  • 4,928
  • 2
  • 34
  • 42
1

In method A , you judge "a==b" which means a have the same reference as b.Obviously their reference is different.

1

Beacause , In the case A, "if(a == b)",a is a memory address ,as the same, b is a memory address ,ofcourse they are not the same ! and In the case B,you compare to a & b 's value! so they are the same .

0

To compare strings in Java you must use equals().

String a = "abc";
String b = "abc";

if(a.equals(b)) {
// true!
}

When you use ==, java is comparing objects references, not its value.

Tiago Luz
  • 129
  • 6