Explanation
1. Purpose
This program demonstrates how to write a reusable custom method that takes input values, performs a calculation (calculating a price with tax), and returns the result to be displayed.
2. Key Concepts
- Static Methods: Methods that belong to the class itself and can be called directly from
mainwithout creating an object instance. - Parameters and Arguments: Defining inputs in the method header (
price,taxRate) and passing concrete values (12.50,0.08) when calling it. - Return Value: Using the
returnkeyword to send the calculateddoublevalue back to the caller. - Formatted Printing (
printf): Using%.2fto round and format a floating-point number to two decimal places.
3. Code Walkthrough
- Lines 2–4 (
finalPricemethod):
Declares a static method that accepts twodoubleparameters. It calculates the tax (price * taxRate), adds it to the originalprice, and returns the total. - Line 7 (Method Call):
Insidemain, the program callsfinalPrice(12.50, 0.08). The method runs, returns13.50, and stores that value in the variabletotal. - Line 8 (Display Output):
System.out.printfformats thetotalvariable to 2 decimal places (%.2f) and moves to a new line (%n).
4. Output
Total: 13.50