User-Defined Methods
Learn how to make your own methods.
We know that built-in methods are like standard ready-to-cook recipes everyone knows how to use. We also know how to use these built-in methods inside our main method. But did you know we can create our own customized methods as well? After all, we can’t possibly have a ready-made method for every need in the world. Imagine if we wanted to create YouTube, and there was a built-in method buildYouTubeForMe("please")
? It doesn’t work like that, right? Instead, Java lets us create methods of our own that we can then use as and when required, just like we can use built-in methods.
All in all, methods help create modular and reusable code, such as displaying a standard message, generating random numbers, or performing other predefined tasks.
What are user-defined methods?
Here’s the basic structure of a method:
public void methodName(int parameter1, int parameter2) { // this method takes 2 inputs of datatype integer// Method body where you will write the Java code// ...// because this method had a return type set to void, this will return nothing}
The structure is just like the main
method we’ve already seen so many times. The only thing different ...