Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Compare a long value is equal to Long value

Tags:

java

long a = 1111;
Long b = 1113;
    
if (a == b) {
    System.out.println("Equals");
} else {
    System.out.println("not equals");
}

The above code prints "equals", which is wrong.

How do I check whether a long value equals a Long value?

like image 526
Chitresh Avatar asked Dec 19 '10 15:12

Chitresh


People also ask

Can we compare two long values in Java?

The java. lang. Long. compareTo() method compares two Long objects numerically.

Can you compare long int?

The int data type is a 32-bit signed two's complement integer. The long data type is a 64-bit signed two's complement integer. The long is a larger data type than int. The difference between int and long is that int is 32 bits in width while long is 64 bits in width.

What is equal method in Java?

Java String equals() Method The equals() method compares two strings, and returns true if the strings are equal, and false if not. Tip: Use the compareTo() method to compare two strings lexicographically.


2 Answers

First your code is not compiled. Line Long b = 1113;

is wrong. You have to say

Long b = 1113L;

Second when I fixed this compilation problem the code printed "not equals".

like image 59
AlexR Avatar answered Sep 28 '22 08:09

AlexR


It works as expected:

public static void main(String[] args) {
    long a = 1111;
    Long b = 1113l;

    if (a == b) {
        System.out.println("Equals");
    } else {
        System.out.println("not equals");
    }
}

prints not equals.

Use compareTo() to compare Long, == wil not work in all case as far as the value is cached.

like image 44
jmj Avatar answered Sep 28 '22 07:09

jmj