Methods Part-1 (Lesson-23)

When solving a complex problem, it becomes necessary to break down the problem into small parts and solve those parts separately. This is where the concept of methods and Object Oriented Programming (OOP) comes in. For this lesson, we will concentrate on methods only. A method is a set of statements that can be used any number of times in a program.
Do you know? You have been using methods since your first program. It was the main method.

public static void main(String[] args) {
}

The main method is the first method which is called when a program starts. It means when you run a java program, the Java Virtual Machine (JVM) run the main method of your program.

Now we will learn how we can create our own methods. First we'll see where we have to type our new method:

Now we will write our new method:

public static void myNewMethod()
{
System.out.println("Wow! My new method");
}

Let's see how it looks:

A method can not run on its own. It must be called from somewhere else. Now let's call our method from the main method. To call our method named "myNewMethod", we will use:

myNewMethod();

Let's see how it works:

You can call a method as many times as you wish.

Let's take the last example of this lesson. Take a closer look at the code and observe the output.

You have only studied a simple "method". It takes no input and gives no output. We will learn more about methods in the next lesson.

Post a Comment

0 Comments