[java] How to Compare a long value is equal to Long value

long a = 1111;
Long b = 1113;

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

the above code prints a "equals" in console, which is wrong answer. my qestions is how to compare a long variable value is equals to Long variable value. please replay me as soon as possible.

Thankh you

This question is related to java

The answer is


It works as expected,

Try checking IdeOneDemo

 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 for me

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


I will share that How do I do it since Java 7 -

Long first = 12345L, second = 123L;
System.out.println(first.equals(second));

output returned : false

and second example of match is -

Long first = 12345L, second = 12345L;
System.out.println(first.equals(second));

output returned : true

So, I believe in equals method for comparing Object's value, Hope it helps you, thanks.


Since Java 7 you can use java.util.Objects.equals(Object a, Object b):

These utilities include null-safe or null-tolerant methods

Long id1 = null;
Long id2 = 0l;
Objects.equals(id1, id2));

On the one hand Long is an object, while on the other hand long is a primitive type. In order to compare them you could get the primitive type out of the Long type:

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

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

    public static void main(String[] args) {
        long a = 1111;
        Long b = 1113L;
        if(a == b.longValue())
    {
        System.out.println("Equals");
    }else{
        System.out.println("not equals");
    }
  }

or:

    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");
    }
  }

long a = 1111;
Long b = new Long(1113);

System.out.println(b.equals(a) ? "equal" : "different");
System.out.println((long) b == a ? "equal" : "different");