• 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
  • Paul Clapham
  • Tim Cooke
  • Jeanne Boyarsky
  • Liutauras Vilda
Sheriffs:
  • Frank Carver
  • Henry Wong
  • Ron McLeod
Saloon Keepers:
  • Tim Moores
  • Frits Walraven
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Himai Minh

Confusion with Long Constructor

 
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
class A2 {
public static void main (String args[]) {
byte primitiveByte = 1;
int primitiveInt = 1;
long primitiveLong = 1L;
float primitiveFloat = 1f;
String s = "1";
Long i1 = new Long(primitiveByte);
Long i2 = new Long(primitiveInt);
Long i3 = new Long(primitiveLong);
Long i4 = new Long(primitiveFloat);//
Long i5 = new Long(s);
int i6 = i1.intValue() + i2.intValue() +
i3.intValue() +
i5.intValue();
System.out.print(i6);
float i7 =i4.floatValue();
System.out.println(i7);
}}
Long has two constructors: one accepts an argument of type primitive long; the other accepts an argument of type String.Here The class instance creation expression new Long(primitiveFloat) generates a compile-time error.
My doubt is, Long could accept upto 64bits value, then why it is not accepting float(32 bits) values.
Regards,
Rama
 
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Converting a float to a long is a narrowing conversion, therefore, it is disallowed. It isn't just the size of the variable that matters, but also the range of those variables.
Refer to the JLS, §5.1.3 Narrowing Primitive Conversions.
Corey
 
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Youll need an explicit cast here since there is a possibility of data loss(narowing conversion).
(long is a signed integral data type)
Long i4 = new Long((long)primitiveFloat);//
 
ramap prabhas
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I got it. Thanks.
Regards,
Rama
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic