-4

I have following code:

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        CharSequence cs = "5.00";
        double danswer = 5.0000;
        DecimalFormat df = new DecimalFormat("#.00");

        if(cs.toString() == String.valueOf(df.format(danswer)))
        {
            System.out.println("person");   
        }
        else
        {
            System.out.println("False");    
        }
    }
}

Why am i not able to compare in this case? As both are string values? How can i compare the values in this case?

NoviceMe
  • 3,126
  • 11
  • 57
  • 117

3 Answers3

1

I would only take a small search to find the answer for this, as it has already been given hundreds of times. But for those die hards who can't use a search function:

You can't use the "==" to compare Strings, NEVER. Instead, you should compare them by using ".equals()"

in your example:if(cs.toString().equals(String.valueOf(df.format(danswer))))

dashhund
  • 322
  • 3
  • 17
  • 1
    maybe not never. for intern()ed constants (either with intern() of with your own pool), you can safely use ==, but that's a very specific case. – Teovald Feb 04 '15 at 18:23
0

use equal method. String a="abc"; if(a.equal("abc"))

use that in your code

nik
  • 210
  • 3
  • 13
0

In this case you want to compare 2 strings but operator "==" is operator that compare boolean and numeric type. When you want to compare strings always use .equals() method because strings need to compare char by char and .equals() do that for you. Every string has .equals() function

class Ideone
        {
public static void main (String[] args) throws java.lang.Exception
{

    CharSequence cs = "5.00";
    double danswer = 5.0000;
    DecimalFormat df = new DecimalFormat("#.00");

    if(cs.toString().equals(String.valueOf(df.format(danswer))))
    {
        System.out.println("person");   
    }
    else
    {
        System.out.println("False");    
    }
}

} This can work fine!

Medin
  • 412
  • 4
  • 17