user650521
user650521

Reputation: 583

Error with Long datatype in java

Actually my system gives Long.MAX_VALUE as 9223372036854775807

But when I write my program like this,

package hex;

/**
 *
 * @author Ravi
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here

        long x = 9223372036854775807;

        System.out.println(x);

    }

}

I am getting compile time error. Can anyone explain the reason?

Upvotes: 2

Views: 620

Answers (4)

Cassio
Cassio

Reputation: 3102

You might want to try using like this:

long x = 9223372036854775807L;

Without the L at the end, you'll be declaring an int.

Upvotes: 4

Michał Šrajer
Michał Šrajer

Reputation: 31182

if you don't specify what kind of number literal is, then int is assumed. You need to specify that you want long by adding "l" or "L" (better, because "l" looks like 1) at the end of the number:

long x = 9223372036854775807L;

instead of:

long x = 9223372036854775807;

Upvotes: 0

SLaks
SLaks

Reputation: 887807

9223372036854775807 is an int literal, and it's too big to fit in an int.
The fact that yo assign the int literal to a long makes no difference.

You need to create a long literal using the L suffix.

Upvotes: 3

Chris Dodd
Chris Dodd

Reputation: 126408

With no suffix, it's an int constant (and it overflows), not a long constant. Stick an L on the end.

Upvotes: 8

Related Questions