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
Release: 2024-10-29 06:01:31
Original
843 people have browsed it

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>
Copy after login

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!

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