DEV Community

Chhavi Joshi
Chhavi Joshi

Posted on

Day 1 of daily coding: Functions is java

We know that functions in java are block of code written to perform a specific task. For example if we need to add two numbers multiple times in same code, it would be very tedious to rewrite the same code again and again, so instead we create a function or a method (a function inside a class is called method) in java. So that instead of writing the whole code we can just call that function.

The syntax of a function appears as follow:

<Access specifier>   <returntype>   <name of finction> (parameter){
...body of function
}
Enter fullscreen mode Exit fullscreen mode

Example:

Above is code for function that would print Hello World three times, we can see that at first we mentioned the access specifier then the type of function, as I wrote it in the main class that would contain the main function later in the code, i wrote static. Then comes the return type of this function, which here is void as it would not return anything, then is the name of function and inside it, is its
body.


If instead of void i would have mentioned int as the return type then, at the end of code i would've to return some value, so here i decided to return the number of times Hello World would be printed. Note that this return value is what the function caller gets back and is not displayed or printed.

output:

Another example would help us understand better:
Sum calculation function:

Here we wrote int as the return type and passed two parameters in the parenthesis. We can see two numbers in the parameter block this means that when we call the function we would need to provide two numbers to it as argument and the function would perform whatever task is mentioned in the body on those values. Then at the end the function returns some value to the caller.
Main method:

Here in the main method I asked for two numbers as input and then passed them as arguments to the function. You can notice that here the value of function call is assigned to a variable sum as:
int sum = calculateSum(a,b)
which means that sum would contain the value that the calculateSum function would return when a and b are passed as arguments in it.
Output:

And this is how the final output would look like.

Top comments (0)