• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

narrowing primitive casts

 
Jeff Gaer
Ranch Hand
Posts: 103
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
how are the values determined in the following narrowing casts?
Is float f truncated or rounded to an int first? or are the bit patterns just assigned.

float f=2.3f;
byte b=(byte)f;
int b=(int)f;
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The java just trancates the float value. it wont round it.
~Kumar
------------------
Sun Certified Programmer for the Java�2 Platform
 
Peter den Haan
author
Ranch Hand
Posts: 3252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Incorrect, I'm afraid. In both cases, the floating point number will be rounded to an integer (JLS 5.1.3). In the conversion to byte, the integer is subsequently truncated to a byte value.
This two-step process can have remarkable side effects, for instanceThis printsThe explanation is left as an exercise for the reader
It would be impossible to truncate a float to an int anyway - the representations are completely different, you don't get an int by simply slicing a few bits off a float. In fact int and float have the same number of bits (32).
- Peter
[This message has been edited by Peter den Haan (edited November 26, 2001).]
 
Jeff Gaer
Ranch Hand
Posts: 103
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class IntTest {
/** Creates new IntTest */
public IntTest() {
}
public static void main(String [] args){
double d=9.9;
int i=(int)d;
byte b=(byte)d;
long l=(long)d;
System.out.println( "int =["+i+"] byte=["+b+"] long=["+l+"]");
}

}
outputs:
int =[9] byte=[9] long=[9]

looks like truncation is the right answer.
 
Marilyn de Queiroz
Sheriff
Posts: 9065
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Did you read JLS 5.1.3? "... the floating-point value is rounded to an integer value V, rounding toward zero using IEEE 754 round-toward-zero mode."
 
Jeff Gaer
Ranch Hand
Posts: 103
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Think its my sloppy use of truncate. By truncate, I meant truncate the decimal part, which is effectively rounding towards 0. Not truncate as it probably should be interpreted, truncating the bits in the float. Thanks for the clarification.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic