Wednesday, November 30, 2016

How to Use methods in Java?

In this article,we will discuss about Java methods and what is the use of methods and how to call methods in java. A method  is a group of statements that perform a task. Here task means processing of data or calculation etc..

method syntax:

returndatatype  methodname(parameter-list)
{
//body of method;
}

In the above syntax method contains two parts: they are
  • method header
  • method body
method header:

It contains method name  that means name given to the method. After method name,we write some variables list in the braces. These variables are called parameters. These parameters are useful to receive data from outside into the method. Return data type is written before method name to represent what type of data the method is returning.

Let us Understand some methods with examples:

void add():

This method is not accepting any data from outside. Since after the method name we write empty braces(). This method does not return any value. So void is written before the method name. Here void means "no value".

we can call this method by using Objectname.methodname that means obj.add(),probably to calculate adding numbers and displaying result.



method body:

Whatever has below the method header is nothing but body of method. Method body consists of a group of statements which contains logic to perform the task.

Example:
{
statements;
}

In the above diagram we want to write a method that calculates adding of two numbers. Observe the method header,that method does not accept any values,we did not declare any parameters in the braces(). SO, this method does not return any values.







Recommended to Read: What is class and Object in Java?


How to call methods in Java:

Let us understand this concept with example:

class Test
{
private int a,b;
Test(int x,int y)
{
a=x;

b=y;
}
//method to calculate sum of a,b
void sum()
{
int res=a+b;
System.out.println("sum="+res);
}
}
class methods
{
public static void main(String[] args)
{
//create object and pass values 10 and 20 to constructor they will stored into a,b
Test t=new Test(10,20);
t.sum();
}
}

Output:

No comments:

Post a Comment

High Paying Jobs after Learning Python

Everyone knows Python is one of the most demand Programming Language. It is a computer programming language to build web applications and sc...