Wednesday, 25 April 2018

Core Java: Type Casting

In Java, you will get a compilation error if you try to assign a double or float value of to an int variable. This is because the fractional part would be lost. The compiler issues an error "possible loss in precision". For example,
 
double d = 3.5;
int i;
i = d;            // Compilation Error: possible loss of precision (assigning a double value to an int variable)
int sum = 55.66f; // Compilation Error: possible loss of precision (assigning a float value to an int variable)
 
Explicit Type-Casting and Type-Casting Operator
 
To assign the a double value to an int variable, you need to invoke the so-called type-casting operator - in the form of (int)value - to operate on the double operand and return a truncated value in int. In other words, you tell the compiler you concisely perform the truncation and you are aware of the possible loss of precision. You can then assign the truncated int value to the int variable. 
 
For example,
double d = 3.5;
int i;
i = (int) d;    // Cast double value of 3.5 to int 3. Assign the resultant value 3 to i
                // Casting from double to int truncates.
 
Type-casting is an operation which takes one operand. It operates on its operand, and returns an equivalent value in the specified type.
 
There are two kinds of type-casting in Java:
1.      Explicit type-casting via a type-casting operator in the prefix form of (new-type)operand, as described above, and
 
2.      Implicit type-casting performed by the compiler automatically, if there is no loss of precision.
 
Implicit Type-Casting in Assignment
 
Explicit type-casting is not required if you assign an int value to a double variable, because there is no loss of precision. The compiler will perform the type-casting automatically (i.e., implicit type-casting). For example,,
 
int i = 3;
double d;
d = i;           // OK, no explicit type casting required
                 // d = 3.0
d = (double) i;  // Explicit type casting operator used here
double aDouble = 55;   // Compiler auto-casts int 55 to double 55.0
double nought = 0;     // Compiler auto-casts int 0 to double 0.0
                       // int 0 and double 0.0 are different.
 
The following diagram shows the order of implicit type-casting performed by compiler. The rule is to promote the smaller type to a bigger type to prevent loss of precision, known as widening conversion. Narrowing conversion requires explicit type-cast to inform the compiler that you are aware of the possible loss of precision. Take note that char is treated as an 16-bit unsigned integer in the range of [0, 65535]. boolean value cannot be type-casted (i.e., converted to non-boolean).
 
 
Example: Suppose that you want to find the average (in double) of the integers between 1 and 100. Study the following codes:
 
public class Sum1To100 {
   public static void main(String[] args) {
      int sum = 0;
      double average;
      int number = 1;
      while (number <= 100) {
         sum += number;      // Final sum is int 5050
         ++number;
      }
      average = sum / 100;   // Won't work (average = 50.0 instead of 50.5)
      System.out.println("Average is " + average);  // Average is 50.0
   }
}
 
This is because both the sum and 100 are int. The result of division is an int, which is then implicitly casted to double and assign to the double variable average. To get the correct answer, you can do either:
 
average = (double)sum / 100;     // Cast sum from int to double before division
average = sum / (double)100;     // Cast 100 from int to double before division
average = sum / 100.0;
average = (double)(sum / 100);   // Won't work. why?

No comments:

Post a Comment

Please write your view and suggestion....