Creating a method in Java

Creating a method in Java

A method is a set of statements grouped together to perform an operation.

Generally there are two types of methods.

  • User defined methods : Usually a user creates to add additional functionality
  • Predefinde methods :  Such methods are already written and provided by java such as Math.pow()

General syntax for method is given bellow:

Note : 

  • formal parameters must seperated by comma  such as m(int a,int b, int c)
  • return type  can be one of the following( int , float, double , String , char , long, short,  void  etc) and return value at the end of method must return the similar value to return data type.
  • Method with a  return type void, has no return statement at the end of method body.

Example below describes how to define a method and invoke it.

method

Another Exapmle showing how the values are passed. Returned value recieved by K.

calling method

 

Caution : Method a in the following example is logically correct but it has a compilation error because the java compiler assumes that this method does not return any value.

methods2

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.