This week's book giveaway is in the Security forum.We're giving away four copies of Penetration Testing Basics and have Ric Messier on-line!See this thread for details.
Win a copy of Penetration Testing Basics this week in the Security forum!

# narrowing primitive casts

Jeff Gaer
Ranch Hand
Posts: 103
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
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
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
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: 9067
12
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
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.