Our website uses cookies to enhance your browsing experience.
Accept
to the top
>
>
>
V6131. Casting to a type with a...
menu mobile close menu
Additional information
toggle menu Contents

V6131. Casting to a type with a smaller range will result in an overflow.

May 26 2025

The analyzer has detected that an integer value is cast to a data type with a smaller size, which leads to an overflow. This happens because a source value is outside the valid range of the target type.

The example of such an overflow:

static final long MAX_CHUNK_SIZE = 4L * 1024 * 1024 * 1024;

void makeChunks(int fileSize) {
    int chunkSize = Math.min(fileSize, (int) MAX_CHUNK_SIZE);

    ....
}

The 4L * 1024 * 1024 * 1024 expression equals 4,294,967,296 (2^32), which is then cast to int. This value exceeds the valid int range ([-2^31..2^31-1]). As a result, the value becomes 0 instead of the expected maximum.

To avoid the overflow, use the long type for all variables and parameters involved in the calculations:

static final long MAX_CHUNK_SIZE = 4L * 1024 * 1024 * 1024;

void makeChunks(long fileSize) {
    long chunkSize = Math.min(fileSize, MAX_CHUNK_SIZE);

    ....
}

This diagnostic is classified as: