2

This is my Example java code.

class Example{
    public static void main(String args[]){
        int x = 65;
        final int y = 65;
        final int z;
        z = 65;
        char ch;
        ch = 'A';
        ch = 65;
        ch =(char) x; // narrow casting
        ch = y;         //line 2 
        ch = z;         //line 3 compile time error
    }
}

why when final variable y initialize value inline that variable compatible to smaller data type without casting but final variable z initialize value after declared it that occurs compiler error.

Please tell me technically why this happens.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • 2
    Because when the variable is `final`, `final int y = 65;` is a *compile-time constant* and the compiler can see that its value, 65, is compatible with `char`. If you assigned 100000 to `y`, it wouldn't compile because the value 100000 isn't compatible with `char`. (And of course, without `final` the compiler doesn't necessarily know what the value would be as of the assignment, which is why `final` matters.) See the linked questions' answers for details. :-) – T.J. Crowder Nov 15 '19 at 14:48
  • Good solid question, btw. Enough code, clear expression of what you're asking about, etc. – T.J. Crowder Nov 15 '19 at 14:50
  • 1
    @T.J.Crowder If I understand the question right, he asked while `ch=z`gives a compile error – Reporter Nov 15 '19 at 14:51
  • 3
    @reporter - The target covers that, too, but I should have included it above. Basically, the JLS only considers finals that are *initialized* with their values to be constant variables ([§4.12.4](https://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.12.4)). A blank final that's *assigned* a value later isn't. I'm guessing this is for managing complexity in the compiler... :-) – T.J. Crowder Nov 15 '19 at 14:57
  • @T.J.Crowder I think your third comment is the correct answer to the question. Also the question is not a duplicate of the questions it is marked a duplicate of. – Tom Hawtin - tackline Nov 15 '19 at 20:37
  • @T.J.Crowder (Also if the `final` is assigned later it's the moral equivalent of `final int z = fn() ? 65 : 66;` where `fn()` is a function call or some other non-*compile-time constant expression*. – Tom Hawtin - tackline Nov 15 '19 at 21:15

0 Answers0