0

How to compare two long value at runtime. When I got the value of both of long type variable at runtime which same so it should be print else part but the both value is different from each other so it should be print if part.

Long dbData = 54188439.... // Got the value at run time
Long spreadSheet = 54188439.....//Got the value at run time

if(dbData != spreadSheet)
{
Log.i("","Please update your contact");
}
else
{
Log.i("","Not required");
}  

Here I always got if part whatever be the condition. Please help me out.

abc
  • 67
  • 3
  • 11

7 Answers7

1

Make use of equals operator

changed the statement from

if(dbData != spreadSheet)

to

  if(!dbData.equals(spreadSheet))

When Same

public static void main(String[] args) {
        Long dbData = new Long(54188439);
        Long spreadSheet = new Long(54188439);

        if (!dbData.equals(spreadSheet)) {
            System.out.println("Please update your contact");
        } else {
            System.out.println("Not required");
        }
    }

Output

Not required

When Different

public static void main(String[] args) {
     Long dbData = new Long(54188439);
    Long spreadSheet = new Long(541878439);

        if (!dbData.equals(spreadSheet)) {
            System.out.println("Please update your contact");
        } else {
            System.out.println("Not required");
        }
    }

output

Please update your contact

Ankur Singhal
  • 26,012
  • 16
  • 82
  • 116
1

The reason it won't work is because you are comparing the objects, not the values. See also https://stackoverflow.com/a/8968390/4890300 for a great answer.

Community
  • 1
  • 1
0
if(dbData.longValue() != spreadSheet.longValue())

Edit your condition as above. It will compare 2 long values. Your exiting condition compare 2 object references.

Thanks

isurujay
  • 1,386
  • 10
  • 15
0

You should compare two instances of Long-class only with it's equals method, because == operators check the addresses, not the values.

if(!dbData.equals(spreadSheet)) 
{
  Log.i("","Please update your contact");
}
else
{
  Log.i("","Not required");
}  
Stanislav
  • 27,441
  • 9
  • 87
  • 82
0

Use Long.compare(long x, long y)

if (Long.compare(val1, val2) == 0) {
   // values are equal
} else {
   // values are not equal
}
Raman Shrivastava
  • 2,923
  • 15
  • 26
0

Your dbData and spreadSheet are instances of the Long class, not long primitives. You have to compare theme either using the equals() method, or compare their longValue()s. I.e.

if (!dbData.equals(spreadSheet)) { 
  // ...
} else {
  // ...
}

or

if (dbData.longValue() != spreadSheet.longValue()) { 
  // ...
} else {
  // ...
}
Jozef Chocholacek
  • 2,874
  • 2
  • 20
  • 25
0

You can use below code.

    Long dbData = 54188439L;// Got the value at run time
    Long spreadSheet = 54188439L;//Got the value at run time

    if (!dbData.equals(spreadSheet)) {


    } 
Rafiq
  • 740
  • 1
  • 5
  • 17