java - Comparing the value of readline() to a string -


this question has answer here:

i reading inputstream using readline() method , trying compare it.

the code follows:

//socket defined before inputstream = socket.getinputstream();  br = new bufferedreader(new inputstreamreader(is));  line = br.readline();      if (line  == "hey") {         log.d("watsapp client tag", "message pushed !!");         log.d("watsapp client tag", "" + line);       }    else {          log.d("watsapp client tag", "message not pushed");         log.d("watsapp client tag", "" + line);      } 

the above code executes else part. although first value of input stream "hey" , second not. expecting in logcat "message pushed !!" , "message not pushed" instead both "message not pushed"

05-31 14:46:14.309    6138-6151/? d/watsapp client tag﹕ message not pushed 05-31 14:46:14.309    6138-6151/? d/watsapp client tag﹕ hey 05-31 14:46:14.339    6138-6151/? d/watsapp client tag﹕ message not pushed 05-31 14:46:14.339    6138-6151/? d/watsapp client tag﹕ <messageadded:1112/> 

please can tell going wrong @ line if (line == "hey"). thanks!

you have compare string using equals() method. == operator here check references. compare string (and other reference type variables) -

string firststring = "somevalue"; string secondstring = "somevalue";  if(firststring.equals(secondstring)){    system.out.println("both string equals");  }else{    system.out.println("not equals");  }   

update: compare variable of type string string literal or constant. it's better perform check -

string str1 = "astring"; string str2 = null; system.out.println( "astring".equals(str1) ); //true; system.out.println( "astring".equals(str2) ); //false;   

the advantage of comparing never nullpointerexception in second case.


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -