Lesson+05+-+Mixed+Data+types,+Casting,+Constants

=Java doesn't like to lose data= double y = 5.2; int x = y; ///*illegal because .2 would be lost// To fix: int x = (int)y; /*releases //double y = 5;// /*legal because no information lost

If there is a double in the formula, the answer will be a double (unless there is casting to int). 20 + 5 * 6.0 = 20 + 30.0 /* do multiplication first */ = 50.0

(int)(3.0 +4)/(1+4.0)*2-3 =(int)(7.0)/(5.0)*2-3 ///*//Took care of parens first */ =7/5.0*2-3 /*Took care of cast before any arithmetic (* / + - ) */ =1.4*2-3 /*Did division resulting in double */ =2.8-3 /*Did multiplication */ =-.2 /*Did subtraction */

=Similar but different= Order of operations/precedence says parens always come first, then casting, then arithmetic

(double) 5/4 = 5.0/4 = 1.25 /* do cast first, then divide */ (double)(5/4) = (double)1 = 1.0 /* do parens first, then cast */ = = =Constants= final int NUM_STUDENTS = 100; OR final int NUM_STUDENTS; NUM_STUDENTS = 100;

However, this is illegal: final int NUM_STUDENTS = 100; NUM_STUDENTS = 50; /* illegal because can't change constant */

=Implied Casting with Compound Operators= With compound operators like j *= 5, there is an implied cast to the result to whatever data type j is. Thus j *=5 is the same as j = (int)(j*5); /* note the cast applies to the whole right side after you put it back in normal form, so put parens around the whole right side. */