Java Reference
In-Depth Information
Note
To assign a variable of the int type to a variable of the short or byte type, explicit
casting must be used. For example, the following statements have a compile error:
int i = 1 ;
byte b = i; // Error because explicit casting is required
However, so long as the integer literal is within the permissible range of the target vari-
able, explicit casting is not needed to assign an integer literal to a variable of the short
or byte type (see Section 2.10, Numeric Literals).
The program in Listing 2.7 displays the sales tax with two digits after the decimal point.
L ISTING 2.7 SalesTax.java
1 import java.util.Scanner;
2
3 public class SalesTax {
4 public static void main(String[] args) {
5 Scanner input = new Scanner(System.in);
6
7 System.out.print( "Enter purchase amount: " );
8
double purchaseAmount = input.nextDouble();
9
10 double tax = purchaseAmount * 0.06 ;
11 System.out.println( "Sales tax is $" +
12 }
13 }
casting
( int )(tax * 100 ) / 100.0 );
Enter purchase amount:
Sales tax is $11.85
197.55
line#
purchaseAmount
tax
output
8
197.55
10
11.853
11
11.85
The variable purchaseAmount is 197.55 (line 8). The sales tax is 6% of the purchase, so
the tax is evaluated as 11.853 (line 10). Note that
formatting numbers
tax * 100 is 1185.3
(int)(tax * 100) is 1185
(int)(tax * 100) / 100.0 is 11.85
So, the statement in line 11 displays the tax 11.85 with two digits after the decimal point.
2.21
Can different types of numeric values be used together in a computation?
Check
2.22
Point
What does an explicit casting from a double to an int do with the fractional part of
the double value? Does casting change the variable being cast?
2.23
Show the following output:
float f = 12.5F ;
int i = ( int )f;
 
Search WWH ::




Custom Search