Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Float and Byte

 
Serghei Jelauc
Ranch Hand
Posts: 128
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

1 compiles without any error but 2 doesn't compile. Why? And Float and Byte do not have constructor with int argument, but only Byte says "cannot resolve symbol
symbol : constructor Byte (int)
location: class java.lang.Byte
Byte b = new Byte(123);"
Thanks in advance.
 
Richard Quist
Ranch Hand
Posts: 96
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would assume that the int value passed to the Float constructor is being promoted to a float value (valid, legal, automatic widening conversion), but the compiler isn't doing an automatic narrowing conversion of the int value to a byte. Casting to a byte as in Byte b = new Byte((byte) 123); should work
 
Serghei Jelauc
Ranch Hand
Posts: 128
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First: Yes I agree, but I would understad "Incompatible types" error, but here "cannot resolve symbol constructor Byte (int)" error. The Float as the Byte does not has constructor which receives int parameter.
Second: I passed in Byte constructor int value which is go in byte size.
[ April 09, 2004: Message edited by: Serghei Jelauc ]
[ April 09, 2004: Message edited by: Serghei Jelauc ]
 
Richard Quist
Ranch Hand
Posts: 96
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Serghei Jelauc:
First: Yes I agree, but I would understad "Incompatible types" error, but here "cannot resolve symbol constructor Byte (int)" error. The Float as the Byte does not has constructor which receives int parameter.
Second: I passed in Byte constructor int value which is go in byte size.
[ April 09, 2004: Message edited by: Serghei Jelauc ]
[ April 09, 2004: Message edited by: Serghei Jelauc ]

For point 1: My understanding is that the compiler will do the widening conversion (from smaller type to a larger) for you automatically since there's no loss of precision...so in your case it would have casted the int literal to a float type...the JLS describes this: Widening conversion
For point 2: The compiler will, I believe, accept the assignment of the value 123 to a variable declared as a byte type because the value is small enough to fit into a byte, but will not do the automatic cast to the smaller type (from the int literal to a byte) in the method call...here's a link in the JLS about this: No Narrowing Conversion in Method calls
Hope that helps
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic