Home > Java > javaTutorial > Why Does Java Throw \'The Literal xyz of Type int Is Out of Range\' When Assigning to a Long Variable?

Why Does Java Throw \'The Literal xyz of Type int Is Out of Range\' When Assigning to a Long Variable?

Mary-Kate Olsen
Release: 2024-11-01 05:41:27
Original
999 people have browsed it

Why Does Java Throw

Fixing "The Literal xyz of Type int Is Out of Range"

When working with data types in Java, it's essential to understand their value ranges. However, you may encounter an error stating "The literal xyz of type int is out of range," even when assigning a value to a long variable.

To resolve this, the key is to explicitly specify the type of the value. In Java, integer values up to 2^31-1 can be represented by int, while larger values require long. However, Java implicitly interprets numeric literals as int unless explicitly specified otherwise.

In your case, the code assigns a value greater than 2^63-1 to a long variable named testLong. Since the literal 9223372036854775807 exceeds the range of int, the compiler interprets it as such, leading to the error.

To fix this, simply append a capital L to the end of the numeric literal to indicate that it represents a long value:

<code class="java">long testLong = 9223372036854775807L;</code>
Copy after login

By explicitly specifying the type of the literal, you ensure that the compiler correctly assigns it to the appropriate data type. This practice is particularly important when working with literals that are close to the maximum or minimum values of a data type to avoid potential errors.

The above is the detailed content of Why Does Java Throw 'The Literal xyz of Type int Is Out of Range' When Assigning to a Long Variable?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template