go to previous page   go to home page   go to next page hear noise highlighting

Why did the program print the first 40 without a decimal point, but printed the second one with a decimal point as 40.0 ?

Answer:

The first value was stored in a variable of data type long, an integer type. Integers do not have fractional parts. The second forty was the result of a calculation involving a variable of data type double, a floating point type, which does have a fractional part. (Here, the fractional part was zero.)


Calculation

public class Example
{
  public static void main ( String[] args )
  {
    long   hoursWorked = 40;    
    double payRate = 10.0, taxRate = 0.10;    

    System.out.println("Hours Worked: " + hoursWorked );
    System.out.println("pay Amount  : " + (hoursWorked * payRate) );
    System.out.println("tax Amount  : " + (hoursWorked * payRate * taxRate) );
  }
}

Look carefully at the statement highlighted in red. The parentheses around

(hoursWorked * payRate)

force the multiplication to be done first. After it is done, the result is converted to characters and appended to the string "pay Amount : ".

When you have a calculation as part of a System.out.println() statement, it is a good idea to surround the calculation with parentheses to show that you want it done first. Sometimes this is not necessary, but it does not hurt, and makes the program more readable.


QUESTION 8:

Would it be better to write some of those statements on two lines instead one one?


go to previous page   go to home page   go to next page