Reputation: 2884
I am trying to assign 4294967295 to a long. That is (2^32-1) java(netbeans) gives the following error message "integer number too large"
in fact I tried to figure out the largest number that an int can handle(did it manually by hand) and found that it is 2147483647 (of course as obvious it is 2^31-1)
But surprisingly I found out that even the long type cannot handle a number larger than that. Isn't there any difference between int and long?java doc says long is 64 bit
Am I missing something?
Upvotes: 2
Views: 2367
Reputation: 380
From The Java™ Tutorials - Primitive Data Types:
int: By default, the int data type is a 32-bit signed two's complement integer, which has a minimum value of -231 and a maximum value of 231-1. In Java SE 8 and later, you can use the int data type to represent an unsigned 32-bit integer, which has a minimum value of 0 and a maximum value of 232-1. Use the Integer class to use int data type as an unsigned integer. See the section The Number Classes for more information. Static methods like compareUnsigned, divideUnsigned etc have been added to the Integer class to support the arithmetic operations for unsigned integers.
So 232-1 = 4294967295
Upvotes: 0
Reputation: 69495
Use the lower l
to show the compiler that it is an long value.
long l = 4294967295l ;
Upvotes: 3
Reputation: 1503579
The problem is that you're using 4294967295 as an int
literal - but it's not a valid int
value. You want it to be a long
literal, so you need to put the L
suffix on it. This is fine:
long x = 4294967295L;
From JLS section 3.10.1:
An integer literal is of type long if it is suffixed with an ASCII letter L or l (ell); otherwise it is of type int (§4.2.1).
Upvotes: 12