WHAT'S NEW?
Showing posts with label parameters. Show all posts
Showing posts with label parameters. Show all posts
Parameters

Parameters are something which is enclosed inside parenthesis of a method.

For example:

 public void square(int num)

Text marked in green color are the parenthesis of method square(),
hence int num is the parameter.

So simply, ANYTHING WITHIN THE PARENTHESIS OF A METHOD IS PARAMETER.


Arguments

Arguments are the values passed to the parameter.

For example:

obj.square(5);

Hence 5 is argument passed to the parameter of the method we discussed earlier in parameters.

Arguments can be any of the stated below.

1) Constant

obj.square(5);

This one is simple to understand. We can pass directly a value which is a constant.

2) Variable

int z=25;
obj.square(z);

We can make a variable and pass it as an argument.
It is like wrapping the constant in a variable and passing it.

3) Expression

int i=2;
int j=4;

obj.square((i+j));

Expression is collection of operator(+,-,*,/,%) and operands (here i and j).

Hence an expression will be first executed and then output of expression will be passed as argument.

So here first i+j will be executed that will give the output 6 and it will be passed as an argument.

4)Method returning some value

public int divideHalf(int num)
{
int ans=num/2;
return ans;
}

obj.square(divideHalf(30));

Only those method which returns some value and of course those values should match with the parameter can be passed as an argument.

If method returning some value are passed then the method is executed first, so here divideHalf() will get executed first and yield an output 15, and it will be passed as an argument to square()

Defining a method in Java

Methods are considered as behavior in a Java Program.
Any changes to variables or any other objects in class are done using methods.

Structure of a method.

access-specifier return-type method-name(parameters)
{
}

Simple example of a method:

public void sayHello()
{
System.out.println("Hello Tom !!");
}

A method can have one or more parameters. 
Example consider a method to add two numbers

public void add(int num1,int num2)
{
int sum=num1+num2;
}

A method with return type void means that the method will not return anything, but if a method requires to return back something it will have return type other than void.
And a point to remember here is that it will require to include a return statement at the end of the method.
Or in simple words. IF A METHOD RETURN SOMETHING ,LAST STATEMENT IN THE METHOD WILL be the return statement.

Example of a method with return statement

public int square(int num)
{
int i=num*num;
return i;
}