Creating Our Own Methods
How to use methods?
In the previous chapter, we looked at creating a method that adds two numbers. Now let's see how we can actually call this method in our code:
You may have noticed that we added
staticbefore the method signature. For now, you don't need to pay attention to this keyword. We are using it only because the main method is
staticby default, and static methods can only use other static methods within them.
- We created two variables of type
intwith different values and then passed them as parameters to our method;
- Since our method returns an
inttype, we can initialize the variable
sumwith the result of calling the method;
- Thus, our method calculated and returned the
sumof the two numbers.
We can also pass arrays as parameters and return them from methods. Let's look at an example:
We have written a method that sorts and increments each element of an integer array (
int). Then we create an unsorted array and use the method on it, initializing a new array called
newArray with the returned value.
It is worth noting that we can use this method multiple times in the same code, for example:
Thus, we can see that we can use our method multiple times in the code. We have used it on two different integer arrays, and each of them is now sorted and incremented.
Everything was clear?