Methods

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.

Syntax:

JavaMethodSyntax

 

There are some methods below. Try to relate it with the above syntax you learned.JavaMethod


Types of Method:

  1. P     =  Parameter  –>  (a, b)
  2. R     =  Return Type –> (int, string)
  3. NP  =  No Parameter
  4. NR  =  No Return Type

javaMethofCodeeasy

  • 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)
  • Objects

 

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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s