Search code examples
javalong-integerprimitive-types

Can anyone tell me why it is giving error, while using long datatype


long x = sc.nextLong();
if (x < 9223372036854775807 && x > -9223372036854775808) 
{
System.out.println("* long");
}

It's having error at if() condition line

The literal 9223372036854775807 of type int is out of range

Can anyone tell me how to reslove it?


Solution

  • long x = sc.nextLong();
    
    if (x < 9223372036854775807L && x > -9223372036854775808L) {
        System.out.println("* long");
    }
    

    To specify a numeric literal as a long instead of an int , add an L (for long) to the end of the literal. Without "L" in the end, the compiler is identifying the numbers as integers and the specified integers in the if statement are out of bounds of an Integer.