WHAT'S NEW?

Methods

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;
}

0 comments:

Post a Comment