Java Reference
In-Depth Information
When a long literal is assigned to a variable of type long , the Java compiler checks the value being assigned and
makes sure that it is in the range of the long data type; otherwise it generates a compile time error. For example
// One more than maximum positive value for long. This will generate a compiler error
long num1 = 9223372036854775808L;
Because the int data type has a lower range than long data type, the value stored in an int variable can always
be assigned to a long variable.
int num1 = 10;
long num2 = 20; // OK to assign int literal 20 to a long variable num2
num2 = num1; // OK to assign an int to a long
The assignment from int to long is valid, because all values that can be stored in an int variable can also be
stored in a long variable. However, the reverse is not true. You cannot simply assign the value stored in a long variable
to an int variable. There is a possibility of value overflow. For example,
int num1 = 10;
long num2 = 2147483655L;
If you assign the value of num2 to num1 as
num1 = num2;
the value stored in num2 cannot be stored in num1 , because the data type of num1 is int and the value of num2 falls
outside the range that the int data type can handle. To guard against making such errors inadvertently, Java does not
allow you to write code like
// A compile-time error. long to int assignment is not allowed in Java
num1 = num2;
Even if the value stored in a long variable is well within the range of the int data type, the assignment from long
to int is not allowed, as shown in the following example:
int num1 = 5;
long num2 = 25L;
// A compile-time error. Even if num2's value 25 which is within the range of int.
num1 = num2;
If you want to assign the value of a long variable to an int variable, you have to explicitly mention this fact in your
code, so that Java makes sure you are aware that there may be data overflow. You do this using “cast” in Java, like so:
num1 = (int)num2; // Now it is fine because of the "(int)" cast
By writing (int)num2 , you are instructing Java to treat the value stored in num2 as an int . At runtime, Java will use
only the 32 least significant bits of num2 , and assign the value stored in those 32 bits to num1 . If num2 has a value that is
outside the range of the int data type, you would not get the same value in num1 .
Search WWH ::




Custom Search