views:

381

answers:

4

I have an object variable Object test = Spinner.getSelectedItem(); -It gets the selected item from the Spinner (called spinner) and names the item 'test'

I want to do an if statement related to that object e.g:

'if (test = "hello") {
//do something
}'

But it appears not to work....

Can someone give me some help? -Do I have to use a different if? or convert the object to string etc.?

Thanks alot...

James

+3  A: 

The statement:

test = "hello"

is an assignment of the string "hello" to the variable test - it doesn't do a comparison.

test == "hello"

is a comparison but still might not work because it compares references. Two different string instances that happen to be both "hello" may not be the same references and therefore the statement may be false.

Try:

"hello".equals( test )
staticman
Ok thanks... *trying it now...*
James Rattray
Thats exactly what I needed, thanks :)
James Rattray
+2  A: 

If you want to compare strings, use equals():

if ("hello".equals(test))...
Eyal Schneider
.equals compares objects, not strings. from the java documentation for Object boolean equals(Object obj) Indicates whether some other object is "equal to" this one.Which is inherited by the String class.
Tom Dignan
Thats exactly what I needed thanks :)
James Rattray
@Tom: of course. I just wanted James to make sure that he is comparing a string with a string (It depends on the type of the items in his Spinner). Otherwise, he will probably receive only false values.
Eyal Schneider
A: 

Make test a string and cast the results of getSelectedItem() to a string

string test = (string)Spinner.getSelectedItem();
if (test == "hello") 
{
    //Do something
}
used2could
I tried that, for some reason, didnt work =/
James Rattray
A: 

It is also valid in saying test.equals("hello") i don't like the other way it doesn't look right in my coding style.

Dean
You'd have to add an extra null check that way, however. AdapterView#getSelectedItem returns null when nothing is selected.
Lance Nanek
I always hated that reasoning. I prefer to always handle the null case explicitly so that it is clear that I expect null or I don't expect null instead of running the risk of accidentally missing nulls that should not logically happen.
TofuBeer