Java Function vs Method

In this article we want to learn about Java Function vs Java Method, so Java is an object oriented programming language that allows developers to create reusable pieces of code called functions and methods. and also in the terms of function and method are sometimes used interchangeably, they have distinct differences in Java.

 

 

What is Java Function ?

In Java a function is self contained block of code that performs specific task and can return a value to the calling program. Functions are standalone pieces of code that are not associated with any object. they are typically used to perform specific calculation or operation, such as computing square root of number or sorting an array.

 

 

This is an example of a Java function that calculates the factorial of a number.

This function takes an integer n as input and returns the factorial of n. it uses for loop to compute the product of all integers from 1 to n.

 

 

This will be the result

Java Function vs Method
Java Function vs Method

What is Java Method ?

In Java a method is a set of instructions that are associated with an object. Methods are similar to functions, but they are defined within a class and operate on the instance variables of that class. Methods can be used to perform different tasks from manipulating data to controlling the behavior of an object.

This method is defined within a class that represents a person, and it sets the name instance variable of that class to the value of the name parameter.

 

 

Differences between Functions and Methods

There are several key differences between functions and methods in Java:

  1. Association with an object: Functions are standalone pieces of code, but methods are associated with an object and operate on the instance variables of that object.
  2. Access modifiers: Functions can have public, private or protected access modifiers, but methods can have those access modifiers as well as package private.
  3. Return type: Functions can have return type, but methods can have a void return type it means that they do not return a value or a non void return type.
  4. Static vs non-static: Functions can be static or non static, but methods can be static, non static or final.
  5. Parameter passing: Functions can take parameters by value or by reference, but methods can take parameters by value, by reference or as an object.

 

 

Learn More

Leave a Comment