From the course: Java Cheat Codes: Most Popular Functions
Defining methods - Java Tutorial
From the course: Java Cheat Codes: Most Popular Functions
Defining methods
- [Instructor] Defining methods. Methods often referred to as functions are reusable blocks of codes within the class. They encapsulate specific tasks, promoting code organization and modularity. For key components and syntax of methods. We have starting off with the name, this is a unique identifier for the method, and then you have different naming conventions, like a camo case. Next would be parameters. These are the inputs the method expects allowing it to operate on different data. Then you have the return type, the data type of the value, the method returns or it can be void if it doesn't return anything. And then you have the body. This is the code block containing the instructions that execute when the method is called. So here on the screen, we have an example of what that could look like. Starting with your access modifier, your return type, your method name, the parameter list, and then your method body. Let's use the built-in Math class in Java as an example. The Math class offers a variety of methods for performing various mathematical operations, saving the effort of writing them from scratch. So some commonly used methods would be math.abs, which would be to return the absolute value of a number. Or Math.maxthxy so you can return the larger of two numbers. Math.sign, co-sign, or tan. You can calculate the sign co-sign or tangent of an angle, and so on and so forth. Using the math methods is pretty straightforward. You call them just like any other method but without the need to create an instance of the math class since it's static. So for example, we see here, double result equals math square root 16. You want to calculate the square root, and you want to output the result, which should print for. And so here you see, we did not have to recreate what it would mean to get the square root of the number. An important note is that while the math class offers convenience, remember that not all mathematical functions are included. For more specialized calculations, you might need to explore other libraries or implement your own methods. To explore further, you can refer to the Java documentation for a complete lists of available methods, not only in the Math class, but in other libraries. And so I suggest that you experiment with different methods. Try out their behavior to solidify your understanding, and to remember, using predefined methods like these can save you time and effort while improving code readability, and maintainability. Feel free to ask any questions you might have about specific methods or their applications in your Java projects. Let's continue learning, and practicing Java together.