Methods in Java

Imagine you as a leader of a crowd of 15000 people. Everyone are gathered in a stadium. You want to find a person who's name is Praveen without any mic or help. Can you find him?

Yeah you can find him, but this is very difficult. Right?

Same like this in programming, if you code many number of lines in main function, it could be very difficult to find errors or anything in code and cannot modify any code easily at necessary times.

For this, we can divide large number of lines of statements into meaningful fragments or functions which can help in understanding of program easily. These are known as methods or member functions.

General Syntax for a method

return_type method_name(parameter(s)){

//statements

}

Return type is simply a datatype of the value which should be returned to the point of calling when a function is completed executing.

Parameters are values that should be passed when called.

Example

int addition(int a, int b){

int sum=a+b;

return sum;

}

We can call by its name with suitable parameters. For eg. addition(2,3);

We can get returned value by assigning the function to suitable variable. For eg. int value=addition(2,3); where value=5 here.

If we don't want to return any value, you can use void datatype.

Example for void

void addition(int a, int b){

int sum=a+b;

System.out.print("Sum is "+sum);

}


Do you know about function and main function?

If you don't know, you can learn from here.