sivanesan1
sivanesan1

Reputation: 839

integer value comparison not working properly

I've a string value String str="Success"

How to check the "str" value is not equal to "Success". If I try if(str!="Success"). It is not working properly.

I've a integer value int a=250 If I use If(a!=250) this is also not working properly.

How to code for these conditional statements ? I'm using Android and Eclipse version 2.1.

Any help would be appreciable.

Upvotes: 1

Views: 5703

Answers (6)

Ram kiran Pachigolla
Ram kiran Pachigolla

Reputation: 21191

As every one said, String values should compare with .equals method.

like

if(str.equals("Success"))
{
    System.out.println("My String is Success");
}

Next coming to integer comparison.

As you have said, you have the integer value

int a=250

if(a!=250)
{
   // Some code
}

Here already your a value is 250. then you are executing some lines of code if a value is not equal to 250. Then how the condition will execute. if you want to test then

change the a value and then check again as

int a=50

if(a!=250)
{
   // Some code===============> Now this code will execute
}

Upvotes: 0

Payal
Payal

Reputation: 913

In Java you cannot use == to compare Strings, you must use:

if(string.equals("example"))

So let's use equals() in your conditional and optimize it: if(!str.equals("Success")) this will work

Upvotes: 0

r0-
r0-

Reputation: 2498

You should not compare strings with != or =. That won't work in most cases.

new String("test").equals("test") 

Should be used for comparison.

!= compares the value and is true if they are NOT equal.

you could also use something like if(a == 250){...}

Upvotes: 0

Nikhil Dhawan
Nikhil Dhawan

Reputation: 11

a!=250 should work. For string try str.equals("Success")

Upvotes: 1

slhddn
slhddn

Reputation: 1997

You should try to study Java first ;) This is not the way to do a String comparison. For String comparison, you must use .equals(String) method.

String str1 = "str1";
String str2 = "str2";

if(str1.equals(str2)) {
    //do something
}

Upvotes: 0

Rahul
Rahul

Reputation: 45060

For string comparison, use the standard String.equals() method.

str.equals("Success"); - For Equals

if(!str.equals("Success")) - For Not Equals(your case)

And for int, what is being used, is proper. a!=250 will return false in your case. Hence, it'll not enter the if block.

Upvotes: 0

Related Questions