0

Im sure this is really simple but it bugging the hell out of me

I use the following code

    String name = Global.PicName2;
    String tempstr = name.substring(0, 3).trim();
    Toast.makeText(getBaseContext(), tempstr, Toast.LENGTH_LONG).show();


    if (tempstr == "Sou"){Toast.makeText(getBaseContext(), "Yes", Toast.LENGTH_LONG).show();}

Now the first Toast reports that tempstr is "Sou" I have checked the lenght of the string and it is 3 characters long I have trimmed any spaces

Yet it will not go through the if statement and toast yes

If I add the line

    tempstr="Sou";

after the first toast it goes through the if statement so that says its the tempstr that is wrong but I cant work out why

Its driving me nuts any ideas?

Any help appreciated

Mark

Mark Barr
  • 159
  • 2
  • 12

3 Answers3

1

use

 if(tempStr.equals("Sou")){

}
Vilas
  • 1,695
  • 1
  • 13
  • 13
  • DUH!!! God I cant believe im such a Donut thanks to all of you who showed me im an idiot annoying thing is I have been stuck on this for an hour :-( – Mark Barr Jun 28 '15 at 08:58
1

Since you are looking for value equality check. You should use tempstr.equals("Sou").

== operator checks for reference equality while .equals() checks for value equality.

Anupam
  • 869
  • 7
  • 13
0

In Java, when the “==” operator is used to compare 2 objects, it checks to see if the objects refer to the same place in memory. In other words, it checks to see if the 2 object names are basically references to the same memory location. A very simple example will help clarify this:

http://www.programmerinterview.com/index.php/java-questions/java-whats-the-difference-between-equals-and/

// your not checking objects are in same in same or not

if (tempstr == "Sou") // ==” operator is used to compare 2 objects, 
{
   Toast.makeText(getBaseContext(), "Yes", Toast.LENGTH_LONG).show();
}

// Right

if(tempStr.equals("Sou")){

}

or

if(tempStr.equalsIgnoreCase("Sou")){ // you can ignoring case 

}

http://www.tutorialspoint.com/java/java_basic_operators.htm

Anil Meenugu
  • 1,411
  • 1
  • 11
  • 16