How to write a method (function) in Java

Functions play a major role in programming languages. The main use of a function can be described as below.

Imagine that you need to run a particular code segment at different places in the main method. Normally what you do is to type the same code again and again in required places. But what if we can write the code in one place and call its name to run it. That is where functions come into play. You can write a function and call its name whenever you want.

Basically you find 3 main types of functions.

  • Functions that give an output and returns a value
  • Functions that give an output but returns nothing
  • Functions that only return a value

Just take a look at the following code segment.


I wrote a method to add 2 given values.

public static int

We use the words “public” and “private” to state the accessibility of the function while the words “static” and “dynamic” to describe the behavior of the function.

The words “Int”,”Boolean”,”String”,”Void” etc are used to describe the returning value of the function.

Then we have to give the name of the function and the parameters that the function requires.

In my function, I am returning a integer. So i have to use int when declaring the method. I need 2 inputs to be taken to add. So whatever the inputs the caller give, will be used as “x” and “y” inside the function. Finally I am returning the summation of the two values.


How to call a function?

Just type the function name along with the required parameters.


What is the meaning of void?

As i mentioned earlier, there are functions that doesn’t return any value. Since we have to mention the type of the returning value when declaring a function, we use “void” to tell that there is nothing that returns.

In this way you can call a functions anywhere you want.

See you in the next post.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s