JAVA.DANGEROUS_CAST

Detects the use of dangerous casts. Patterns detected as dangerous casts are "int / short / long to byte", "float to int / short / long", and "double to float".

Vulnerability and risk

Unintended operation may be caused due to loss of digits.

Mitigation and prevention

Unless you have an explicit reason, you should avoid using casts that can cause unintended behavior.

Example 1

Copy
public class C07 {

    void dangerousIntegerNarrowing() {
        int i = 128;
        short s = 128;
        long l = 128;
        byte b = (byte) i;// NG
        b = (byte)s;//NG
        b = (byte)l;//NG

        float fmin = Float.MIN_VALUE;
        float fmax = Float.MAX_VALUE;
        short sfmin = (short) fmin; // NG
        int ifmax = (int) fmax; // NG
        long lfmax = (long)fmax;//NG

        double dmin = Double.MIN_VALUE;
        double dmax = Double.MAX_VALUE;
        float fdmin = (float) dmin; // NG
        float fdmax = (float) dmax; // NG
    }
}