Page 476 - Introduction to Programming with Java: A Problem Solving Approach
P. 476
442 Chapter 11 Type Details and Alternate Coding Mechanisms
to the type of the wider operand. In the first statement above, the int 3 is narrower than the double 4.5, so the JVM promotes 3 to a double, before adding it to 4.5. In the second statement above, do you know which operand, ‘f’ or 5, gets promoted to match the other one? ‘f’ is a char and 5 is an int, and Fig- ure 11.5 shows that char is narrower than int. Thus, the JVM promotes ‘f’ to an int. More specifically, since f’s underlying numeric value is 102 (see Figure 11.4), the JVM promotes ‘f’ to 102. Then the JVM adds 102 to 5 and assigns the resulting 107 to num.
Promotions typically occur as part of assignment statements, mixed expressions, and method calls. You’ve already seen examples with assignment statements and mixed expressions; now let’s examine pro- motions with method calls. As mentioned above, conversions take place any time there’s an attempt to use a narrower type in a place that expects a wider type. So if you pass an argument to a method and the method’s parameter is defined to be a wider type than the argument’s type, the argument’s type promotes to match the parameter’s type. Figure 11.6’s program provides an example of this behavior. Can you determine what promotion takes place within the program? The x argument is a float and it promotes to a double. The 3 argument is an int and it promotes to a double as well.
/***************************************************
*
MethodPromotion.java
Dean & Dean
Promote type in method call
***************************************************/
Apago PDF Enhancer
public static void main(String[] args)
*
*
*
public class MethodPromotion
{
{
float x = 4.5f;
printSquare(x);
printSquare(3);
}
// end class MethodPromotion
}
automatic promotion
private static void printSquare(double num)
{
}
Output:
20.25
9.0
System.out.println(num * num);
Figure 11.6 Program that demonstrates type promotion in method call Type Casting
Type casting is an explicit type conversion. It occurs when you use a cast operator to convert an expression’s type. Here’s the syntax for using a cast operator:
(type) expression