• 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
  • Liutauras Vilda
  • Paul Clapham
Sheriffs:
  • paul wheaton
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Piet Souris
Bartenders:
  • Mike London

primitive casting

 
Ranch Hand
Posts: 134
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


Can anyone please explain casting needed in line2 but not in line1 for successful compilation even though both appear to have similar issue-converting int to byte.
 
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Wild guessing here, I haven't even tried it (too lazy ). I'm putting my java intuition to the test.

Could it be an assignment matter ? On line 1, the compiler can see that the value, although an int literal, holds in a byte (less than 127). So no casting needeed When you pass a parameter to a function, it's a type problem. All the compiler cares about is that types are compatible and in that case, you must downcast an int to a byte.

Please correct me if required !
 
Ranch Hand
Posts: 169
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
when it comes to assignment i.e byte b = 100, the compiler sees whether the value is in range or not and if not then gives compilation error.

but in case of passing values in methods, the least you can pass is an int literal..not byte not short
hence when you say :



then you are actually passing a int literal and trying to assign it to a byte..which cannot be done implicitly and hence you need to downcast it to byte like:

doThis((byte)100)
 
reply
    Bookmark Topic Watch Topic
  • New Topic