Creating and Calling Methods
In the last chapter, we looked at the concept of methods. In this chapter, we will look at the syntax for creating methods and using them.
A very basic method can be created using the following syntax:
We will be exploring
parameters in the later chapters, for now we will use
void as the
returnValue and nothing in place of parameters as they are optional. For-example, we can create a method called
countToTen from the previous chapter:
We can execute a method using the following syntax:
We can execute the
countToTen method in the following way as we explored in the last chapter:
Note that this way of calling a method only works with a method that is
void and has no parameters. In the later chapters, we will learn about the term
void and how to make a method that has parameters, along with how to call such methods.
You don't need to understand the
static part in detail on this level but to understand
static you should know that a method is always a part of a class:
The above is how a method will look like in a full program. In this case the class is called
Program. If we don't use the term
static before a method then it means we cannot use that method until an instance if a class is created, which might not make a lot of sense in this chapter so right now you don't need to worry about all the complexities of the term
What will be the output of the following code? (This quiz can be a lesson in itself that meaningful method naming matters)
Select the correct answer
Everything was clear?