Methods or functions in java

What is the difference between methods and functions in Java?

Many candidates are rejected or down-leveled in technical interviews due to poor performance in behavioral or cultural fit interviews. Ace your interviews with this free course, where you will practice confidently tackling behavioral interview questions.

A function in JavaScript is a statement that performs a task or calculates a value, takes in an input, and returns an output as a result of the relationship between the input. A method is a property of an object that contains a function definition. Methods are functions stored as object properties.

Let us use an object called rectangle .

We want to use the code to find the area of a rectangle to establish the difference between a function and a method.

//We create an object called Rectangle
class Rectangle
//We initialize the constructor
constructor(width, height)
this.height = height;
this.width = width;
>
//A function local to the Rectangle class
getArea()
return this.width * this.height;
>
>
//Let us initalize a new Rectangle with a width of 10 and 5
AreaOfRect = new Rectangle(10, 5);
console.log(AreaOfRect.getArea());
//console.log(getArea())

Let us go into functions before we do our comparison.

const AreaRect = (width, height) =>
return console.log(width * height);
>;
AreaRect(10,5); //50

A method, like a function, is a collection of instructions that perform a task, but a method is associated with an object and a function is not.

So, if we want to call a method from our code, we will use AreaOfRect.getArea() . If we use getArea() here, we will get an error because getArea() is local to the AreaOfRect object. We need to access the getArea() function as an object property from the AreaOfRect object.

We can assume our AreaRect() function is global, meaning it can be called without being used as an object property. I can simply call AreaRect(5,10) and it gives me an output of 50.

Источник

Java Methods or Functions

A Java method is a block of code or collection of statements that performs a particular task and returns a result. A (Void) method in Java can perform a particular task without returning any result.

Methods in Java execute only when they are called by any of the caller methods.

Methods in Java help us implement the DRY (Do Not Repeat Yourself) Principle. The idea behind the principle is that repeating yourself is a bad thing to do when coding, because having the same code in different places makes maintainability harder, once changes in the code will have to happen in many places, instead of one.

Now after reading this you must be thinking that the methods in Java are the same as functions in other languages like C/C++. The answer is pretty much YES. We can say that the ‘Method’ is the object-oriented word for ‘Function’.

The only difference between Methods and functions is that you can invoke a function anywhere by just mentioning its name with the given arguments.

While talking about the methods then the method is specifically associated with an object, which means you can only invoke a method by mentioning its object before it with a dot(.) notation or operator. Every method must be a part of some class.

Declaration of method:

There are total 6 components in the Java method declaration and they are as follows:

  1. Access-Modifier: it defines how the method will be accessed or from where the method will be accessed. In Java, there are four types of access modifiers and they are as follows:
    Public: Public classes are accessible by all the classes that are present in the application.
    Protected: Protected classes can only be accessed within the class in which they are defined or in their subclasses.
    Private: Private classes can only be accessed within the class in which they are defined.
    Default: Default classes are defined/declared without using any access modifier. It is accessible within the same class in which it is defined.
  2. The return type: The type of data(i.e Data-type)that the method returns after the execution of the code inside it are called as return type of that method. If the method does not return any kind of value then it is called a Void method.
  3. Method Name: The name of the method should be defined according to a task that a particular method is performing.
  4. Parameter list: The list of input parameters preceding their data types, Being separated by a comma and enclosed with parentheses is called a parameter list. If there are no parameters, just use empty parentheses ().
  5. Exception list: The exceptions you expect by the method can throw, you can specify these exception(s).
  6. Method body: The block of code which is enclosed between curly braces, is the body of the method.

Types of Methods in Java

There are two types of methods in Java:

  1. Predefined Method: The methods which are predefined or already defined in the Java class libraries are known as predefined Methods / Built-in Methods. These methods are the same as STL (Standard template library) in the C++ language. We can directly use these methods just by calling them in our program.
  2. User-defined Method: The methods which are written or created by the user or programmer are known as User-defined Methods.

Calling a Method

The method needs to be called for using its functionality. There can be three situations when a method is called:

A method returns to the code that invoked it when:

  • It completes all the statements in the method
  • It reaches a return statement
  • Throws an exception

Example 1: Multiplication of two numbers with the help of methods in Java

Java Code

// Class 1 // Helper class class Product < // Initially taking multiplication as 1 int mul = 1; // Method // To find product of two numbers public int Multiplication(int a, int b) < // Multiplying two integer value mul = a * b; // Returning product of two values return mul; >> // Class 2 // Helper class class TUF < // Main driver method public static void main(String[] args) < // Creating object of class 1 inside main() method Product pro = new Product(); // Calling method of above class // to multiply two integer // using instance created int ans = pro.Multiplication(2, 5); // Printing the product of two numbers System.out.println("Product of given two values is :" + ans); >>

Output: Product of given two values is : 10

Example 2: To check if the given number is Even or Odd

Java Code

// Class 1 // Helper class class Check < // Method // To check if given number is even or odd public boolean EvenOrNot(int num) < // Cheacking if the number is even or odd if (num % 2 != 0) < return false; // the number is odd >return true; // the number is even > > // Class 2 // Helper class class TUF < // Main driver method public static void main(String[] args) < // Creating object of class 1 inside main() method Check chk = new Check(); // Calling method of above class // to check the number is even or odd // using instance created boolean ans = chk.EvenOrNot(5); // Printing the result if (ans) < System.out.println("The number is Even. "); >else < System.out.println("The number is odd. "); >> >

Output: The number is odd.

Special thanks to Abhishek Yadav for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this article

Источник

What’s the difference between a function and a method?

I’ve heard that methods are more Object-Oriented than functions. I was wondering if someone could show me an example of a function and a method and explain the differences between methods and functions? I have taken 3 quarters of Java programming and functions have never been mentioned, I want to know the differences, strengths and weaknesses.

«function» is not a useful differentiation in this context. An object’s method is just a special case of «function» attached to an object. Many languages, like JavaScript, even use the keyword function when writing methods.

A function is a block of code with no state. A closure (function with captured variables) is a function with state and is like an object with exactly one method. An object is like a collection of closures capturing common variables (the object’s state). So, you use functions when you need no state, and closures or objects when you do need state. Functions can be thought of as stateless methods, and methods as statefull functions. Once you understand this, you can pick the corresponding constructs in your language of choice. In Java you can use static methods to represent functions.

Voting to leave open. The answers and a few of the comments do an excellent job at explaining the difference between the two terms as well as when it’s appropriate to use each term.

I agree to @GlenH7 that your question should not be closed for the reason he gave, but I downvoted it because it is so very unclear what you really want to know. Please consider to edit it to make it clearer.

4 Answers 4

Speaking strictly, a procedure is a subroutine that is executed purely for its side effects (like printing something to the screen) and returns no values. A function is a subroutine that always returns the same value given the same inputs and has no side effects. A method is a procedure or function that is associated with a class or object.

The confusing part is when people use these terms, they’re not always referring to the pure definitions. For the sake of convenience and consistency, programming languages don’t always make a distinction between functions, procedures, and methods. They have one or two ways to declare a subroutine, and whether it’s technically a function, procedure, or method depends on how the programmer is using it.

In Java, for example, a procedure is created by having a void return type on a method. A function is a method with a return type and no side effects, like:

People whose only programming experience is in a language like Java often don’t even realize there’s a difference, because in Java it usually doesn’t matter in a practical sense. In a java-only context, programmers often refer to any subroutine as a function , even by those who know the difference, and they mostly go uncorrected except by the very pedantic.

. and Pascal/Delphi. Noteworthy detail that Prism/Oxygene uses method . BTW, the OPs question was about function/method, not procedure/function. 😉

Getter methods aren’t usually functions in the pure sense, because they potentially return a different value different times you call them. Getters of immutable objects are functions though.

While the distinction between [pure] functions and [effectful] procedures is important, I don’t see what does it have to do with the distinction of either from methods. You can easily have standalone procedures that return void and produce side effects; stdlib.h declares a few. You can have immutable objects with all methods being pure, see java.lang.String for an example. It’s passing of an object instance in a special way that makes a method; semantically things like stream.write(data) and write(stream, data) may be equivalent.

I woould actually use different terminology. What you call «function», I would call «pure function». Anything that may have side-effects but still returns a value, I would call «function» and anything with only side effects is, as you state, a «procedure».

There are no functions per se in Java. All you’ve got is methods. To imitate functions, Java generally uses static methods (as in java.lang.Math ).

There is a number of object-oriented languages that provide free-standing functions, though: among them Python, Ruby, JavaScript, C++, Object Pascal, and even (yuck) PHP. There’s a good reason behind that.

A method is basically a function with one extra parameter (invisible in Java). You refer to it as this . That this thing allows you to access the object whose method is being called, so you can think that the entire object is always an implicit parameter to a method, additionally to parameters you normally define.

A method makes sense if it makes use of its object: calls other methods and/or accesses data members. For example, a list can have a getLength() method that knows how to calculate list’s length, e.g. by scanning each member. It obviously uses the implicit this object, that is, the list. This is why it needs no explicit parameters.

Else, a function is enough. For instance, to compute a cosine of an angle you only need the angle, and no other state, so cos(float angle) could be a function, and only depend on the explicit angle parameter.

Another important thing is method overriding. (To my ming, this is a dubious practice, but Java uses it very widely.) You declare a certain class (call it Z ) a subclass of another class (call it A ), and change implementation of some of its methods (suppose we overrode method foo() ).

The subclass works like the base class (it is said to provide the same interface) but does it by different means. According to Liskov substitution principle, you can declare a variable of type A , assign to it an instance of type Z , and invoke method foo() ; what will be invoked is Z ‘s implementation of foo() , not A ‘s. That is, the method to call will be looked up at runtime, based on the actual type of the object. This is know as «dynamic method dispatch» or «virtual methods».

What method overriding provides automatically is not easy to directly emulate with functions. (With functions, similar things are usually done with «callbacks» or «higher-order functions»).

In certain languages, such as Java and C#, you can define «static methods» that do not receive a this parameter. They work exactly like «standalone» functions and use the class as a namespace. Such namespacing may sometimes make sense, when a static method of a class is used to look up or create new instances of that class.

I hope you now have a better picture.

Источник

Читайте также:  All php source codes
Оцените статью