• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

casting

 
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Consider the following.
char c='a';
char d=c+1; //line 1.
char e=4+4; //line 2.
I know line 1 gives error as it requires explicit casting.
I do not understand why line 2 does not give an error. 4+4 results in 8 which is of type int. why does it not require an explicit casting?
 
Ranch Hand
Posts: 504
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
4 is an int literal and also a compile time constant. When you add two constants to each other, the result is a constant as well. In this case, if the resulting int const fits into char, the compiler allows such an assignment.
 
Ranch Hand
Posts: 150
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Sonali
Btw, if you declare c as final, line 1 would compile fine too.
Cheers
Harwinder
 
Vad Fogel
Ranch Hand
Posts: 504
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Harwinder Bhatia:
Sonali
Btw, if you declare c as final, line 1 would compile fine too.
Cheers
Harwinder


The same rule applies: if the compiler figures out the assignment as a result of operations on compile time constants fitting the size to the left, it'll allow it.
 
Maybe he went home and went to bed. And took this tiny ad with him:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic