• 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

what is the rule here ?

 
Ranch Hand
Posts: 417
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
byte b = 125; //implicit narrowing
well in this case below a cast is needed.
Byte b = new Byte(125) //cast needed
why ?
constructor for Byte says
new Byte(byte value)
so why is implicit narrowing not done when the value is within range ? why ?
this is not consistent ?
 
Author & Gold Digger
Posts: 7617
6
IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
mark,
from 5.3 Method Invocation Conversion


Method invocation conversion is applied to each argument value in a method or constructor invocation (�15.9, �15.12): the type of the argument expression must be converted to the type
of the corresponding parameter. Method invocation contexts allow the use of an identity conversion (�5.1.1), a widening primitive conversion (�5.1.2), or a widening reference conversion
(�5.1.4).
...

Method invocation conversions specifically do not include the implicit narrowing of integer constants which is part of assignment conversion (�5.2). The designers of the Java
programming language felt that including these implicit narrowing conversions would add additional complexity to the overloaded method matching resolution process (�15.12.2). Thus,
the example:


HIH
[ January 29, 2002: Message edited by: Valentin Crettaz ]
 
Bartender
Posts: 2205
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hehe, the simple answer is that this automatic assignement narrowing is an exception to the rule that only widening conversions are performed automatically for you.
byte b = 15; //This the only exception to this rule!
when you write new Byte(125), that 125 is still an int literal. There is no constructor in Byte() that takes an int. That's why it doesn't work.

Rob
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic