aspose file tools*
The moose likes Beginning Java and the fly likes Why final modifier has such impact Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Why final modifier has such impact" Watch "Why final modifier has such impact" New topic
Author

Why final modifier has such impact

Sidharth Pallai
Ranch Hand

Joined: Apr 21, 2008
Posts: 134


The above code produces compilation error but if "i" is decalred as "final",it doesn't!. Can anyone explain the impact of final on widening of primitive types.


Thanks & Regards
Sidharth Pallai
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39436
    
  28
You're not widening, you are narrowing. You would normally require a cast for the b = i; assignment. I can only presume that the compiler can tell that final int i = 2; implies the value of i will always be within the range of a byte. Try changing i to 128, and see whether it still works; 128 is outwith the possible range for bytes.
Sidharth Pallai
Ranch Hand

Joined: Apr 21, 2008
Posts: 134

Thanks Campbell, I got how it works behind.
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14272
    
  21

Campbell is right: If you make i final, then the value of i becomes a compile-time constant: a value which is fixed and known at compile-time - so the compiler can check if it fits into a byte.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
 
Consider Paul's rocket mass heater.
 
subject: Why final modifier has such impact