• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Devaka Cooray
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Carey Brown
  • Tim Holloway
Bartenders:
  • Martijn Verburg
  • Frits Walraven
  • Himai Minh

effect of final modifier. explain me.

 
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
class Test8
{
public static void main(String a[])
{
byte b = 1;
char c = 2;

c = b; // 1
}
}

When we compile Test8.java it gives compile time error at line marked 1, but when we make variable b as final, then program compiles and runs fine..
Explain me.

Pankaj Shinde
 
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
An expression may be assigned to a variable of type byte, short, or char if the expression represents a compile-time constant of type byte, short, char, or int that will "fit" in the variable type. (See JLS 5.2 Assignment Conversion.)

In this example, if the variable 'b' is not final, then it does not represent a compile-time constant, and therefore cannot be assigned to the char variable 'c' without an explicit cast.
 
If I'd had more time, I would have written a shorter letter. -T.S. Eliot such a short, tiny ad:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic