开发者

str1 != "NO" returns true while str1 is "NO"

I have this code:

url = new URL("http://anurl");
urlConn = url.o开发者_开发百科penConnection();
dis = new DataInputStream(urlConn.getInputStream()); 
num = dis.readLine();
System.out.println(num); //prints "NO"
if(num != "NO") {
   //this code is executed
}

I'm doing something wrong?


You shouldn't use != or == when comparing strings. It will do a comparison of the object reference (you can think of it as the pointer to the object) and return true/false depending on if it is the exact same instance of the string or not. Use String.equals() to do it right.


!= compares references, not objects. You need to use if (!num.equals("NO")).


== tests whether values refer to the same object. Use "NO".equals(num).


When you want to compare String then use equals

if(!"NO".equals(num)) {
   //this code is executed
}


try it with:

if(num.equals"NO") {
   //this code is executed
}

Please read this for more info.


== and != will do an exact bit wise comparison of the reference variables. In other words they will do a comparison of the addresses referred by the references and not the values. Since they are pointing to different objects so different addresses [which are stored in the references] are compared. That is why you have that behavior.


String comparison in Java requries equals:

if (!num.equals("NO")) {
  ...
}

Your code might work in C# or in some other programming language, but not in Java.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜