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:
1 2 3 4 |
Method // Method head declaration { // Beginning of method body // Statements } // End of method body |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
class Data            // declaration of the new class name Data {    int x_coordinate ;    // x-position of our point    int y_coordinate ;    // y position of our point    // Method head with the access modifier public (visible everywhere)    // The return data type void indicates that there is no return value    // Method name set_x_coordinate    // Transfer parameter X_coordinate to be added of data type int    public void set_x_coordinate(int X_coordinate to be added )    {       /* Here the attribute x_coordinate of an object       set the value of X_coordinate to be added. */       this.x_coordinate = X_coordinate to be added ;    } } |
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:
1 2 3 4 5 6 7 |
public static void main (String []args ) { Â Â Â // statements } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
class Test {               public static void main ( String [ ] args )       {               point point_one = new point ( ) ;           point_one. set_x_coordinate (100) ;        }  } |
Let’s now extend our Point class with the get_x_coordinate method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
class point         {    int x_coordinate ;     int y_coordinate ;       public void set_x_coordinate ( int X_coordinate )    {        this . x_coordinate = X_coordinate ;    }    public int get_x_coordinate ( )    {        return this . x_coordinate ;    } } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
class Test {            public static void main ( String [ ] args )       {               point point_one = new point ( ) ;               point_one. set_x_coordinate (100) ;                                     int returned_value = point_one . get_x_coordinate ( ) ;                 System . out . println ( "Returned value is: " + returned_value ) ;        }  } |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
class Test {        public static void main ( String [ ] args )       {               point point_one = new point ( ) ;                     point_one. set_x_coordinate (100) ;                                           int returned_value = point_one . get_x_coordinate ( ) ;           System . out . println ( "Returned value is: " + returned_value ) ;        }  } class point         {    int x_coordinate ;     int y_coordinate ;       public void set_x_coordinate ( int X_coordinate )    {        this . x_coordinate = X_coordinate ;    }    public int get_x_coordinate ( )    {             return this . x_coordinate ;    } } |
Output:
Method Call by Reference:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
class RefTyp { // Attribute x int x ; } class Test { // method1 with transfer parameters of data type int static void method1 ( int par ) { // par is changed to 10 here par = 10 ; } // method2 static void method2 ( RefTyp refParam ) { // Here the attribute x of the object refParam is changed refParam. x= 10 ; } // main method public static void main ( String [ ] args ) { // variable var with value 20 int var = 20 ; // Creation of an object of the class RefTyp RefTyp ref = new RefTyp ( ) ; // Set the x attribute of our ref object to the value 20 ref. x = 20 ; // output from var System . out . println ("current value before method1 for var:" + var ) ; // call the method method1 with our variable var method1 ( var ) ; // Output of var after calling the method method1 System . out . println ( "current value after method1 for var : " + var ) ; // Output from the x attribute of our ref System. out . println ( "current value before method2 for ref.x : " + ref.x ) ; // call the method method2 with our object ref method2 ( ref ) ; /* Output from the x attribute of our ref object after calling the method2 method */ System . out . println ( "current value after method2 for ref.x : " + ref.x ) ; } } |
Output:
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:
- The data type of at least one transfer parameter is different than in the other methods with the same name.
- The number of transfer parameters is different.
Here are a few examples from the Java class library java.lang.Math
1 2 3 4 |
public static int abs ( int ) public static float abs ( float ) public static long abs ( long ) public static double abs ( double ) |
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:
1 2 3 4 5 6 7 |
public void set values ( int value1, int value2 ) public void set values ( int value1, int value2, int value3 ) public void set values ( int value1, float value2 ) public void set values ( int value1, short value2 ) public void set values ( int value1, String value2 ) public void setValues ( float value1, int value2, int value3 ) public void setValues ( int value1, byte [ ] value2, int value3 ) |
Method overloading by changing parameters in java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
class Test{ private static void method1(int a){ System.out.println("Method1 Arguments: " + a); } private static void method2(int a, int b){ System.out.println("Method2 Arguments: " + a + " and " + b); } public static void main(String[] args) { method1(10); method2(20, 20); } } |
Output:
 Method overloading by changing data type:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
class Sum{ static int add(int a, int b){ return a+b; } static double add(double a, double b){ return a+b; } } class Test{ public static void main(String[] args){ System.out.println("The Sum of int data type: "+Sum.add(20,30)); System.out.println("The Sum of double data type: "+Sum.add(10.5,50.4)); } } |
Output:
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
class Test { // Method for calculating the factorial static long calculate( int n ) { long data= 1 ; // Iterative calculation for ( int i = 1 ; i <= n ; i ++ ) { data *= i ; } return data; } public static void main ( String [ ] args ) { long data= calculate(7 ) ; System . out . println ( "7! = " + data) ; } } |
Output:
Example: how to calculate factorial using method recursion in java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
class Test { static long Cal_Factorial( int n ) { System . out . println (n ) ; if ( n >= 1 ) { // recursive call (calls itself) return n * Cal_Factorial( n - 1 ) ; } else { // termination condition of the recursion return 1 ; } } public static void main ( String [ ] args ) { long data= Cal_Factorial( 5 ) ; System . out . println ( "5! = " + data) ; } } |
Output:
To make recursion clear, let’s look at what happens in detail.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
if ( n >= 1 )        {              // recursive call (calls itself)              return n * Cal_Factorial( n - 1 ) ;        }        else        {              // termination condition of the recursion              return 1 ;        } |
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.