2

I am reading the inputstream using readline() method and then trying to compare it.

The code is as follows:

//socket is defined before this
InputStream is = 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 always executes the else part. although first value of the input stream is "hey" and second is not. So I am expecting in the logcat "message pushed !!" and "message not pushed" instead I get 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 what is going wrong at line if (Line == "hey"). Thanks!

Razib
  • 10,965
  • 11
  • 53
  • 80
satej k
  • 89
  • 2
  • 13

1 Answers1

3

You have to compare String using equals() method. The == operator here check the references. Compare String (and other reference type variables) like this -

String firstString = "someValue";
String secondString = "someValue";

if(firstString.equals(secondString)){
   System.out.println("both string are equals"); 
}else{
   System.out.println("not equals"); 
}  

Update: Sometimes we compare a variable of type String to a String literal or constant. Then it's better to perform the check like this -

String str1 = "aString";
String str2 = null;
System.out.println( "aString".equals(str1) ); //true;
System.out.println( "aString".equals(str2) ); //false;  

The advantage of comparing like this you never get NullPointerException in the second case.

Razib
  • 10,965
  • 11
  • 53
  • 80