7. Using Methods
Let's now use some different methods to keep the code simple and easy to read and understand. After all, even though you may write your code only once, you want it to remain maintainable forever.
Methods help you to organize your code. Each method does one specific thing, either with or without input values.
- First, look at the import statements at the top. Because we use methods that are not part of "basic Java", we need to tell our program which additional classes need to be imported.
- Then two methods are defined. By calling these methods from the main method, we can keep the code in the main method very clean and readable.
- "getTotal(int quantity, float price)" which returns a calculated value
- "getNow()" which returns the current timestamp as a readable formatted String
- Run the code, as shown below.
$ java UsingMethod.java 2 x Raspberry Pi 4 4Gb, price: 119.9000015258789 Euro Current date and time is: 2022.12.09 21:35:23