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

2

3 Answers 3

1

use

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

}
Sign up to request clarification or add additional context in comments.

1 Comment

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 :-(
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.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.