Calculation

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   hear noise   go to next page

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.

Calculation

Here is the program again:

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 it is not necessary, but it does not hurt, and makes the program more readable.

QUESTION 8:

Would it be convenient to write some of those statements on two lines?