Home >Java >javaTutorial >Why does Java throw an \'out of range\' error for a long literal despite the variable being declared as long?

Why does Java throw an \'out of range\' error for a long literal despite the variable being declared as long?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-29 06:01:31794browse

Why does Java throw an

"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!

Statement:
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