Method in Java with Programming Examples

Method in java:

In other programming languages, a method is often referred to as a function or procedure. As with attributes, certain naming conventions should be adhered to for methods. The name of a method in java should always start with a lowercase letter. Furthermore, the name of a method should be meaningful, i.e. the name should describe the interaction with the object.

The method is part of a class and can be declared and implemented only in a class. There are methods with one or no return value, i.e. it is not possible to assign more than one return value to a method in java. However, the return value of a method can assume any data type, so arrays or objects can also be used as the return value. However, any number of parameters can be passed to a method in java.

In Java, the transfer parameters are passed as “call-by-value”, i.e. a change in the transfer parameters within the called method does not affect the parameters of the caller. The caller retains the original values. In many other programming languages, unlike Java, the transfer parameters are passed as so-called ” method call-by-reference”.

A method in java can be overloaded as often as you like. Overloading means that there can be multiple methods with the same name.


Definition and declaration of a method in java:

In order to concentrate on the essentials, we will leave out the entire class view at this point and limit ourselves to just the method itself. The definition and declaration syntax of a method in java looks as follows:

Now let’s take a closer look at just the method header.

modifier return data type method name ( data type argument1, … )

The method head can be introduced by the so-called access modifier (public, protected, private). The access modifier gives information about the visibility of a method in java. There are other modifiers as well, but we’ll go into more detail about them later. A modifier is not a must and should be well considered. However, it is mandatory to specify the return data type. This specifies the data type to which the return value of the method belongs. This is followed by the method name, which should meaningfully represent the method in java. The method name is followed by a block in round brackets. The transfer parameters are defined in this block. The data type is specified for each parameter. The parameter can be used in the method as a local variable. The names of the passing arguments should be descriptive, as should the method name. However, a method does not necessarily have to receive transfer parameters. If no transfer parameters are used, the round brackets remain empty.

Let’s look directly at an example of a full method declaration.

In the example above, we have added the set_x_coordinate method to our Data class.

As a next example, let’s look at the well-known main method, which is called first when a program or a startup class is started.



Structure of the main method:

The main method in java has two access modifiers, public and static. As you will learn later, static is used to declare a class method. Class methods are not object-related, but – analogous to the class variables – apply to the entire class. This allows this method to be called before an object of this class has even been created. This is a requirement for the main method, otherwise no Java program could be started.

The return type of the main method is void, ie no value is returned from the main method. The name of the main method is main. The main method expects an array of strings as the digging parameter. You’re probably wondering, “What’s in this array when I call the startup class?” The content of the array is up to you. The array contains values ​​that are passed to the start class when it is started. In the examples used in this tutorial, the array will also remain empty.


Calling method in java:

Now that we know the structure and the declaration of methods, we want to look at how we call the method in java. To access a method of a class, we must first create an object from that class (exception: class methods declared with static). The method can then be accessed using point notation. For this purpose, we first create a starting class and create an object of our class dot from the preceding example. We then call the set_x_coordinate method.

Let’s now extend our Point class with the get_x_coordinate method.

As you can see again in this example, the method names are chosen to be meaningful. One is used to set (set) and the other to read (get) an attribute (in this case x_coordinate). These methods are also called getter or setter methods in java. A method that specifies a return data type must necessarily return a value of that type using the return keyword. For the get_x_coordinate method, this means that it must return a variable (in this case the x_coordinate attribute) of the int data type.

We now want to extend the Test class by calling the setter and getter methods in order to set the value of the coordinate and then read it out.

Methods are called in Java using a so-called “call-by-value”. This means that the value (contents) of the passed parameters is passed to the called method. These are copied there into local variables. Changes to the parameters within the method, therefore, have no effect outside. The parameters passed when the method is called remain unchanged.


Complete program:

Output:

method in java


Method Call by Reference:

Output:

method in java

The passed parameter is changed in the method1 method. However, since the transfer takes place via a “call-by-value”, only the value of the transferred variable is copied into the method. The caller, therefore, does not notice anything about the change, since the transferred parameter has not changed itself, but only a local copy of the value. Therefore, the second output of the variable var is also 20. However, it gets a little more complicated when passing objects. With object variables, you have to know that they only contain a reference to the object, but not the object itself. This reference is therefore copied into the local variable of the method.

However, since the copied reference now points to the same object as the one that was passed when it was called, all changes to the referenced object (e.g changing an attribute) also have a global effect. In this special case, this is similar to a “call-by-reference” as known in other programming languages.

When calling method2 we have such a case. We pass the ref object to method2. In the method, we change the x attribute of this object. Since we are accessing the referenced object, this change is also visible in the caller, and this time a 10 is output after calling the method.

We hope this short example helps you understand more about how objects and methods work and how they interact.



Method overloading in java

As already mentioned, methods can be overloaded. Overloading means that the same method name can be used multiple times in a class. Overloading often occurs with constructors or conversion methods.
In order for overloading to be possible, at least one of the following requirements must be met:

  1. The data type of at least one transfer parameter is different than in the other methods with the same name.
  2. The number of transfer parameters is different.

Here are a few examples from the Java class library java.lang.Math

In the abs method, the absolute value of the passed parameter is returned. Since all methods should provide the same functionality, the method is overloaded. Only the data type of the passed parameter is different. So you don’t have to choose a new name for every data type for a mathematical method that always does the same thing.

More examples of overloaded methods:


Method overloading by changing parameters in java:

Output:

method in java

 Method overloading by changing data type:

Output:

method in java


Method Iteration and recursion

Methods can be used both iteratively and recursively. An iteration (repetition) is the multiple executions of one or more instructions. The iteration is realized by loops (for, while…). The loop is terminated by a termination condition.

One speaks of recursion (from the Latin recurrere = run back) when a method calls itself again and again until a termination condition is met. Each recursion can also be converted into an iterative solution and vice versa.

Iterations have the advantage that they are more preformat. However, recursion usually requires less source code and is clearer, but more memory-intensive. However, recursions are often difficult to understand for novice programmers.

In the following examples, we calculate the factorial of an integer positive number (a “!” behind the number as a mathematical symbol) once iteratively and once recursively. Even the definition is recursive: 0! = 1, 1!= 1, (n>1)! = n * (n-1)!

Example: how to calculate factorial using method iteration in java:

Output:

method in java


Example: how to calculate factorial using method recursion in java:

Output:

method in java

To make recursion clear, let’s look at what happens in detail.

5: 5* Cal_Factorial (5-1)   
2.   4: 5* 4* Cal_Factorial (4-1)    
3.   3: 5* 4* 3* Cal_Factorial (3-1)    
4.   2: 5* 4* 3* 2* Cal_Factorial (2-1)    
5th 1: 5* 4* 3* 2* 1* Cal_Factorial (1-1)    
6th 0: 5* 4* 3* 2* 1* 1

The recursion is only completed with the sixth call and then returns the calculated value.

It should be mentioned that the example of the factorial is not one that would necessarily be solved recursively in practice. In this case, the loop is not only easier to read, but also more memory-efficient (each call uses up resources!) and its runtime behavior are also much better.
It seems that everything speaks against recursion. However, there are also problems that are very difficult (but never impossible!) to solve with loops.

Recommended For You

About the Author: Fawad

My name is Shahzada Fawad and I am a Programmer. Currently, I am running my own YouTube channel "Expertstech", and managing this Website. My Hobbies are * Watching Movies * Music * Photography * Travelling * gaming and so on...

Leave a Reply

%d bloggers like this: