It is a block of code to perform a particular task like add(), subtract(), print() etc. (do refer Code Structure tutorial to know method structure).
Earlier, you performed a basic program where you called the System.out.print(” “) method to display a sentence between ” ” , where system executes several statements to display a message on the console. Some of these methods are already present in java class.
So, we need to create our own methods to perform a task that we require in our code. But, first we need to know method syntax and its types.
There are some methods below. Try to relate it with the above syntax you learned.
Types of Method:
- P = Parameter –> (a, b)
- R = Return Type –> (int, string)
- NP = No Parameter
- NR = No Return Type
- Java supports multiple parameters separated by commas.
E.g. void add (int a, int b).
- If method is in same class, we need to create the object of that class to access it (will learn creating objects in next tutorials).
- We cannot define a method in another method we can just call a method in another method.
(You can refer any code in your books and distinguish between different methods written from above)
What is Parameter?
Parameters are given in method definition.
E.g. In above examples we have int a, int b, String name as parameters.
What is Argument?
Arguments are the VALUES passed in method calling. It is that value which is passed when we create object and access its method.
E.g. add(6,5) , display (“Java”)
There are 4 types of arguments:
- Constant: add(3, 4)
- Variable: add(a, b)
- Expression: add(a+b, b-a)
In order to call and perform this method in any code we need to make object in main class. Refer Object Tutorial to know how to create objects.
In upcoming tutorials, you will learn about Method-Overloading & Method-Overriding.