aspose file tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes narrowing primitive casts Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "narrowing primitive casts" Watch "narrowing primitive casts" New topic

narrowing primitive casts

Jeff Gaer
Ranch Hand

Joined: Jun 04, 2001
Posts: 99
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;

Sun Certified Java Programmer Java 2<P>Jeff Gaer
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
The java just trancates the float value. it wont round it.
Sun Certified Programmer for the Java�2 Platform
Peter den Haan
Ranch Hand

Joined: Apr 20, 2000
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

Joined: Jun 04, 2001
Posts: 99
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+"]");

int =[9] byte=[9] long=[9]

looks like truncation is the right answer.
Marilyn de Queiroz

Joined: Jul 22, 2000
Posts: 9055
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."

"Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt
Jeff Gaer
Ranch Hand

Joined: Jun 04, 2001
Posts: 99
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.
rocket mass heater kickstarter
subject: narrowing primitive casts