This week's book giveaway is in the OO, Patterns, UML and Refactoring forum.
We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line!
See this thread for details.
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: 43993
    
  33
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: 14953
    
  26

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
 
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com
 
subject: Why final modifier has such impact
 
jQuery in Action, 3rd edition