23.11.2014 Views

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

double d1 = 3.2;<br />

double d2 = 3.9999;<br />

<strong>in</strong>t i1 = (<strong>in</strong>t)d1; // i1 has value 3<br />

<strong>in</strong>t i2 = (<strong>in</strong>t)d2; // i2 has value 3<br />

double d3 = (double)i2; // d3 has value 3.0<br />

Cast<strong>in</strong>g with Operators<br />

Certa<strong>in</strong> b<strong>in</strong>ary operators, like division, will have different results depend<strong>in</strong>g on<br />

the variable types they are used with. We must take care to make sure operations<br />

perform their computations on values of the <strong>in</strong>tended type. When used with<br />

<strong>in</strong>tegers, division does not keep track of the fractional part, for example. When<br />

used with doubles, division keeps this part, as is illustrated <strong>in</strong> the follow<strong>in</strong>g<br />

example:<br />

<strong>in</strong>t i1 = 3;<br />

<strong>in</strong>t i2 = 6;<br />

dresult = (double)i1 / (double)i2;// dresult has<br />

value 0.5<br />

dresult = i1 / i2;<br />

value 0.0<br />

// dresult has<br />

Notice that when i1 <strong>and</strong> i2 were cast to doubles, regular division for real<br />

numbers was performed. When i1 <strong>and</strong> i2 were not cast, the " /" operator<br />

performed an <strong>in</strong>teger division <strong>and</strong> the result of i1 / i2 was the <strong>in</strong>t 0. Then,<br />

<strong>Java</strong><strong>Java</strong> then did an implicit cast to assign an <strong>in</strong>t value to the double result.<br />

We discuss implicit cast<strong>in</strong>g next.<br />

Implicit Cast<strong>in</strong>g <strong>and</strong> Autobox<strong>in</strong>g/Unbox<strong>in</strong>g<br />

There are cases where <strong>Java</strong> will perform an implicit cast, accord<strong>in</strong>g to the type of<br />

the assignment variable, provided there is no loss of precision. For example:<br />

<strong>in</strong>t iresult, i = 3;<br />

double dresult, d = 3.2;<br />

dresult = i / d;<br />

cast to a double<br />

// dresult is 0.9375. i was<br />

49

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!