Search code examples
javalogic

Why java does not compare accurately large value at its upper range?


for input value of x = 200000000 and y = 20000000000000000, x and y lines will hold equal values after input(x^2 will be equal to 2*y), but on comparing these it prints NO i.e. x==y is false.

public static void main (String[] args) throws java.lang.Exception
{
    Scanner scn = new Scanner(System.in);
    int t = scn.nextInt();
    Long x = (long)Math.pow(scn.nextLong(),2);
    Long y = 2*scn.nextLong();
    System.out.println((x==y)?"YES":"NO");
}

Meanwhile, if I

System.out.println((x-y==0)?"YES":"NO");

It prints YES. So why it is happening?


Solution

  • Your problem is auto boxing.

    Long x = (long)Math.pow(scn.nextLong(),2);
    Long y = 2*scn.nextLong();
    

    x and y are Objects of type Long

    either use Object equality test

    System.out.println(x.equals(y)?"YES":"NO");
    

    or use primitives

    long x = (long)Math.pow(scn.nextLong(),2);
    long y = 2*scn.nextLong();
    System.out.println((x==y)?"YES":"NO");