About Lesson
Scenario : Can you assign a long
value to an int
variable? If not, why?
Answer:
No, you cannot assign a long
value to an int
variable because a long
has a larger range than an int
(64-bit vs. 32-bit). This can lead to data loss if the long
value exceeds the maximum value that an int
can hold. Java will give a compilation error unless you explicitly cast the long
to int
, but this is risky and can result in truncation.
Example:
long l = 10000000000L; int i = (int) l; // Explicit casting is required System.out.println(i); // Output: -1610612736 (due to overflow)