EGHDK
EGHDK

Reputation: 18130

String CompareTo not working

I have a simple if statement that doesn't seem to work. I'm out of ideas. I don't understand why my logic is wrong.

String a = "bf";

if (a.compareTo("bf"))
{
    // do this
}

I'm getting a redline under the compareTo statement.

Type mismatch: cannot convert from int to boolean

Upvotes: 2

Views: 3597

Answers (7)

Girish
Girish

Reputation: 41

compareto returns an integer. An if statement wants a boolean to check so change you code to:

String a = "bf";

if (a.compareTo("bf")==0)
{
  // do this
}

Upvotes: 1

Kumar Vivek Mitra
Kumar Vivek Mitra

Reputation: 33544

Use equals() method of Object class to compare two String objects here.

String a = "bf";

if (a.equals("bf"))
{
    // do this
}

Moreover compareTo() is the method of java.lang.Comparable Interface.

Upvotes: 1

Ram kiran Pachigolla
Ram kiran Pachigolla

Reputation: 21191

compareTo method returns int value. so do as

if (a.compareTo("bf") == 0)      
{
    //
} 

(or)

use .equals method

if (a.equals("bf"))

{
// do this
}

Upvotes: 2

Chirag
Chirag

Reputation: 56925

When comparing for equality you should use equals(), because it expresses your intent in a clear way.

compareTo() has the additional drawback that it only works on objects that implement the Comparable interface.

This applies in general, not only for strings.

Upvotes: 1

Cirou
Cirou

Reputation: 1430

The compareTo method returns an int value, not a boolean.

You must change it to

if (a.compareTo("bf") == 0)

or use

if (a.equals("bf"))

Upvotes: 1

nano_nano
nano_nano

Reputation: 12523

change it to this

String a = "bf";  
if (a.compareTo("bf") == 0)      
{
 // do this     
} 

Upvotes: 1

nagylzs
nagylzs

Reputation: 4180

compareTo returns an int, not a boolean.

http://developer.android.com/reference/java/lang/Comparable.html

It a negative integer if this instance is less than another; a positive integer if this instance is greater than another; 0 if this instance has the same order as another.

So you should check for == 0

By the way, it works for things that can be ordered only. If you just want to check for equality, use .equals

Upvotes: 1

Related Questions