Java functions, function reuse and function overloading sample code

* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
package functions;

* @author dkenga
public class Functions {

* @param args the command line arguments
public static void main(String[] args) {
// TODO code application logic here
int addition;
int addition2;
addition = sum(3,4);
//Let us reuse the function sum
addition2 = sum(10,20);

substract(40, 20);


//This is function definition.
//This function returns something; an interger
//the name of the function is sum
//sum is a user defined function
//sum takes in 2 parameters i.e num1 and num2
static int sum(int num1, int num2){
int sum = num1 + num2;
return sum;

We have defined another function with the same name , sum, as the previous one
We changed some characteristics of the second sum function
This concept of using functions with similar name but performing different
functions is called function overloading

The are a number of ways in which you can achieve function overloading. they
1. Vary the number of parameters
1. Vary the data types of parameters
static void sum(double a, double b) {


//substract is a user defined function, which does not return any value
//So it is void
//however, it takes in 2 parameters
static void substract (int num1, int num2){
int sub = num1 - num2;
System.out.println("The difference is " + sub);
//the name of the function is printOutput
//it is void meaning that it does not return anything
//it does not take parameters
//it is user-defined
static void printOutput (){
System.out.println("I am a void function and i do not return anything !!");


Leave a Reply to George Cancel reply

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