Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why final modifier has such impact

 
Sidharth Pallai
Ranch Hand
Posts: 134
Hibernate Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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.
 
Campbell Ritchie
Sheriff
Posts: 48454
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 134
Hibernate Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Campbell, I got how it works behind.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15208
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic