Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How downcasting takes place by using the 'final' keyword in Java

Tags:

java

final

Consider:

class UnderstandingConversion {
    public static void main(String[] args) {

        int a=10, b=20;

        byte c = (a>b) ? 40 : 50;

        System.out.println(c);
        // output : lossy conversion error
    }
}

This code is giving an error as 'lossy conversion' which I understand, but if I use the final keyword in the code as shown below, it is working fine.

class UnderstandingConversion {
    public static void main(String[] args) {

        final int a=10, b=20;

        byte c = (a>b)? 40 : 50;

        System.out.println(c);
        // Output: 50

    }
}

How is final working here and how does downcasting take place?

like image 767
Yash Deole Avatar asked Aug 31 '25 15:08

Yash Deole


1 Answers

The JLS has predefined rules for assignment conversion.

If the expression is a constant expression (§15.28) of type byte, short, char, or int:

A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable.

The definition of constant expression:

  • Literals of primitive type and literals of type String
  • Simple names (§6.5.6.1) that refer to constant variables (§4.12.4).
  • The relational operators <, <=, >, and >= (but not instanceof) (§15.20)

The §4.12.4 defines what final variable is

A variable of primitive type or type String, that is final and initialized with a compile-time constant expression (§15.28), is called a constant variable.

like image 148
aviad Avatar answered Sep 14 '25 11:09

aviad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!