nadirbasalamah
Posted on June 3, 2021
Function is a piece of code that can be useful to make a certain code reusable. Function is also useful to break a big logic in a code into many pieces to create a code that easy to understand. This is the basic syntax to create a function in Java.
modifier static_type return_value func_name(params) {
// code..
}
There are two main types of function including void function that has not return value and a function with return value.
Void function
Void function is a function that does not return any value. The basic syntax looks like this.
modifier static_type void func_name(params) {
// code..
}
This is the example of using void function.
public class MyApp {
public static void main(String[] args) {
// call a function called sum and printGreeting
sum(14,15);
printGreeting();
}
// create a new function without any params
public static void printGreeting() {
System.out.println("Hello World!");
}
// create a new function to calculate the sum of two integers
public static void sum(int a, int b) {
int result = a + b;
System.out.println("The result is: " + result);
}
}
Output
The result is: 29
Hello World!
Based on the code above, the two functions called sum()
and printGreeting()
is a static function. these functions is declared as static
because these functions is executed inside main()
function that has a static
keyword. Basically, static
function can be executed inside another static
function.
The variadic arguments or parameters is also available in Java, these variadic arguments can be used to a void function and a function that has a return value. This is the basic syntax to create a variadic arguments.
data_type ... arg_name
This is the example of using variadic arguments to calculate a sum of a integers.
public class MyApp {
public static void main(String[] args) {
// call a function called sum with variadic args
sum(14,15);
sum(14,15,16,17);
sum(1,2,3,4);
}
// create a new function to calculate the sum of many integers
public static void sum(int ... nums) {
int result = 0;
// calculate the sum using for each
for (int tmp: nums) {
result += tmp;
}
System.out.println("The result is: " + result);
}
}
Output
The result is: 29
The result is: 62
The result is: 10
Based on the code above, the variadic arguments illustrated as a list of integers in this case. The nums
argument can be iterated using foreach
to calculate the sum of many integers.
Variadic arguments must be located in the last of the arguments
// true implementation
public static void average(int size, int ... nums) { }
// false, throw an error
public static void average(int ... nums, int size) { }
Function with Return Value
Function can also has a return value. This is the basic syntax of a function with return value.
modifier static_type return_type func_name(params) {
// code..
}
This is the example of using function with return value.
public class MyApp {
public static void main(String[] args) {
// create a array of integers
int[] nums = {1,2,3,4,5};
// call the average function
int avgResult = average(nums);
// print out the result
System.out.println("Average result: " + avgResult);
}
public static int average(int[] nums) {
// perform average calculation
int result = 0;
for (int tmp: nums) {
result += tmp;
}
return result / nums.length;
}
}
Output
Average result: 3
Based on the code above, the average()
function returns int
that the returned value is stored inside avgResult
variable with the int
type.
Overloading functions
Overloading functions is a function that has a same name but with different number of arguments or parameters inside the function. The example looks like this.
// these functions has a same name called "greet"
// without args
public static void greet() {
System.out.println("Hello World!");
}
// with one argument
public static void greet(String name) {
System.out.println("Hello, " + name + "!");
}
// with two arguments
public static void greet(String name, int age) {
System.out.println("Hello, " + name + "!");
System.out.println("Your age is: " + age + " years old.");
}
Static and Non Static Function
Static function is a function that can be called inside static
function. Static function is a function that available to use without creating an object or an instance of a specific class. The example of a static
function is a functions that available in a Math
class. these functions is available in a Math
class
without creating an object of Math
class.
// call a pow() function directly from Math class
Math.pow(3,2);
Non static function is a function that available to use if the object or an instance of a specific class is created. This is the example of non static function called sum()
in a class called Calculator
.
// create a class called Calculator
class Calculator {
// create a fields of integers
int numOne;
int numTwo;
// create a constructor
public Calculator(int numOne, int numTwo) {
this.numOne = numOne;
this.numTwo = numTwo;
}
// create a non static function to calculate the sum
public int sum() {
return numOne + numTwo;
}
}
public class MyApp {
public static void main(String[] args) {
// create an object of Calculator Class
Calculator calculator = new Calculator(2,3);
// call the sum function from the calculator object
System.out.println("The sum result: " + calculator.sum());
}
}
Output
The sum result: 5
Based on the code above, the sum()
function is only available if the object of Calculator
class is created.
Lambda
Lambda is an anonymous function that can be used to perform certain operation. This is the basic syntax of lambda in Java.
// The expression's result is directly returned. The complex logic is not allowed.
(param) -> expression
// With two parameters, The expression's result is directly returned.
// The complex logic is not allowed.
(param1, param2) -> expression
// With two parameters, The code block may contains complex logic.
// Use return keyword if the code block is returning the value.
(param1, param2) -> { code block }
This is the example of lambda usage in ArrayList
to multiply every value inserted by 2.
import java.util.ArrayList;
import java.util.List;
public class MyApp {
public static void main(String[] args) {
// create a new list of integers
List<Integer> numbers = new ArrayList<>();
// add some integers
numbers.add(1);
numbers.add(2);
numbers.add(3);
// using lambda function
numbers.forEach((num) -> System.out.println(num * 2));
}
}
Output
2
4
6
Based on the code above, the forEach()
function is using lambda function to multiply the value by 2 and prints out the result. This is the lambda function that used in that code.
(num) -> System.out.println(num * 2)
Recursive Function
The recursive function basically is available in many programming languages including Java. Recursive function is a function that called itself inside it's own function. Some problem can be solve using recursive function including fibonacci sequence calculation. Check this link to learn more about fibonacci sequence.
public class MyApp {
public static void main(String[] args) {
int result = fibonacci(5);
System.out.println(result);
}
// using recursive function
public static int fibonacci(int num) {
if (num <= 2) // base case
return 1;
else // recursive case
return fibonacci(num - 1) + fibonacci(num - 2);
}
}
Output
5
Based on the code above, there are two main components in recursive function. The components are base case and recursive case. Base case is basically to tell when the recursive execution stop. The recursive case is an operation that executed until the base case.
This is the illustration of fibonacci()
function works.
When using recursive function, make sure the input is not too large to avoid Stack Overflow exception.
Sources
Learn more about variadic arguments in Java in this link.
Learn more about static keyword in this link.
Learn more about lambda function in this link.
Lambda function's documentation can be checked here.
I hope this article is helpful for learning the Java programming language. If you have any thoughts or comments you can write in the discussion section below.
Posted on June 3, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.