web analytics

Java Functions

Java function also called java method is a group of java statements which is used multiple times when needed.
Why we use functions? to write a piece of for a certain task which we need to perform again and again. Instead of writing simple java statements to perform a task we write a function once and use it whenever we need to perform this task.

  • Java Functions usage is called function call.
  • We can pass some data to java functions.
  • Data is passed to java functions by java parameters.

How to create a Java function?

Java is a purely Object Oriented Programming language therefore java functions are created within java classes. Java function definition statrs with access specifier (i.e public, private, protected) followed by the data type function returns followed by function name which is followed by parentheses().

Here is an example of java function definition:


public class MyClass{
public int addInteger(int num1, int num2){
int sum = num1 + num2 ;
return sum ;
}
}

public is access specifier which indicates that this function can be called by functions of other classes. int is data type of value which function returns.

How to call a java function

Java functions are cannot be called directly. To call a java function either we need an object of class in which java function is defined or the function should be declared static to call function using name of class of function. Following is an example of function call using an object of class:


public class MyClass{
public void addInteger(int num1, int num2){
int sum = num1 + num2 ;
System.out.println("Sum of given numbers is: " + sum) ;
}
public static void main (String[] args){
// creating an object of MyClass.
MyClass obj = new MyClass();
// calling the function using created object.
obj.addInteger(100,200);
// calling the method again and again.
obj.addInteger(200,200);
obj.addInteger(300,200);
obj.addInteger(400,200);
}
}