Home >Java >javaTutorial >Why does Java throw an \'out of range\' error for a long literal despite the variable being declared as long?
"The Literal's Uneasy Journey from Int to Long"
In the realm of Java data types, encountering an enigmatic error message like "The literal xyz of type int is out of range" can leave even seasoned programmers perplexed. Uncover the solution to this perplexing puzzle below.
The Mystery Unraveled
Despite declaring the variable testLong as a long data type, Java interprets the literal value 9223372036854775807 as an integer, resulting in the error. The missing piece to this puzzle lies in a subtle omission: the addition of an uppercase "L" at the end of the literal.
The Secret Ingredient
Java requires literals to be explicitly specified as long, lest the compiler interpret them as integers. Appending the uppercase "L" to the literal, as seen in the corrected code below, resolves the issue:
<code class="java">long testLong = 9223372036854775807L;</code>
With this alteration, the compiler recognizes the literal as a long value, respecting its boundless range of -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.
The above is the detailed content of Why does Java throw an \'out of range\' error for a long literal despite the variable being declared as long?. For more information, please follow other related articles on the PHP Chinese website!