Java - tutorial - 08/13 - methods

revision:


Java - methods

A method is a block of code which only runs when it is called. You can pass data, known as parameters, into a method. Methods are used to perform certain actions, and they are also known as functions. Methods are used to reuse code: define the code once, and use it many times.

A method must be declared within a class. It is defined with the name of the method, followed by parentheses (). Java provides some pre-defined methods - such as System.out.println() - but you can also create your own methods to perform certain actions.

example:

      public class Main {
        static void myMethod() {
          // code to be executed
        }
      }
    

example explained: myMethod() is the name of the method; "static" means that the method belongs to the Main class and not an object of the Main class. "void" means that this method does not have a return value.

To call a method in Java, write the method's name followed by two parentheses () and a semicolon;. A method can also be called multiple times.

example:

        public class Main {
          static void myMethod() {
            System.out.println("I just got executed!");
          }
        
          public static void main(String[] args) {
            myMethod();
          }
        }
        //----------------------------------------------------
        public class Main {
          static void myMethod() {
            System.out.println("I just got executed!");
          }
        
          public static void main(String[] args) {
            myMethod();
            myMethod();
            myMethod();
          }
        }
    

method parameters

Information can be passed to methods as parameter. Parameters act as variables inside the method. Parameters are specified after the method name, inside the parentheses. You can add as many parameters as you want, just separate them with a comma.

example:

      public class Main {
        static void myMethod(String fname) {
          System.out.println(fname + " Luyckx");
        }
      
        public static void main(String[] args) {
          myMethod("Emiel");
          myMethod("Jaak");
          myMethod("Mia");
        }
        // Emiel Luyckx
        // Jaak Luyckx
        // Mia Luyckx
      }
    

The example has a method that takes a String called "fname" as parameter. When the method is called, we pass along a first name, which is used inside the method to print the full name.

When a parameter is passed to the method, it is called an argument. So, from the example above: "fname" is a parameter, while "Emiel", "Jaak" and "Mia" are arguments.

You can have as many parameters as you like. However, when you are working with multiple parameters, the method call must have the same number of arguments as there are parameters, and the arguments must be passed in the same order.

example:

      public class Main {
            static void myMethod(String fname) {
                System.out.println(fname + " is " + age);
            }

            public static void main(String[] args) {
                myMethod("Emiel", 5);
                myMethod("Jaak", 8);
                myMethod("Mia", 31);
            }
            // Emiel is 5
            // Jaak is 8
            // Mia is 31
        }
    

return values: the "void" keyword indicates that the method should not return a value. If you want the method to return a value, you can use a primitive data type (such as int, char, etc.) instead of void, and use the "return" keyword inside the method.

example:

      public class Main {
          static int myMethod(int x) {
            return 5 + x;
          }
        
          public static void main(String[] args) {
            System.out.println(myMethod(3)); // 8
          }
      }
    

It is common to use if...else statements inside methods

example:

      public class Main {
        // Create a checkAge() method with an integer parameter called age
        static void checkAge(int age) {
          // If age is less than 18, print "access denied"
          if (age < 18) {
            System.out.println("Access denied - You are not old enough!"); 
          // If age is greater than, or equal to, 18, print "access granted"
          } else {
            System.out.println("Access granted - You are old enough!"); 
          }
          
        } 
      
        public static void main(String[] args) { 
          checkAge(20); // Call the checkAge method and pass along an age of 20
        } 
        // Access granted - You are old enough!
      }
    

method overloading

With method overloading, multiple methods can have the same name with different parameters: int myMethod(int x), float myMethod(float x), double myMethod(double x, double y).

example:

      public class Main {
        static int plusMethod(int x, int y) {
          return x + y;
        }
        
        static double plusMethod(double x, double y) {
          return x + y;
        }
        
        public static void main(String[] args) {
          int myNum1 = plusMethod(8, 5);
          double myNum2 = plusMethod(4.3, 6.26);
          System.out.println("int: " + myNum1);
          System.out.println("double: " + myNum2);
        }
        // int: 13
           double: 10.559999999999999
      }
    

Multiple methods can have the same name as long as the number and/or type of parameters are different.


Java - scope

In Java, variables are only accessible inside the region they are created. This is called scope.

method scope: variables declared directly inside a method are available anywhere in the method following the line of code in which they were declared.

example:

      public class Main {
        public static void main(String[] args) {
            // Code here cannot use x
            int x = 100;
            // Code here can use x
            System.out.println(x); // 100
        }
      }
    

block scope: a block of code refers to all of the code between curly braces {}. Variables declared inside blocks of code are only accessible by the code between the curly braces, which follows the line in which the variable was declared.

example:

      public class Main {
        public static void main(String[] args) {
              // Code here CANNOT use x
            { // This is a block
              // Code here CANNOT use x
              int x = 100;
              // Code here CAN use x
              System.out.println(x);
            } // The block ends here
            // Code here CANNOT use x
          }
      }
    

A block of code may exist on its own or it can belong to an "if", "while" or "for" statement. In the case of "for" statements, variables declared in the statement itself are also available inside the block's scope.


Java - recursion

Recursion is the technique of making a function call itself. This technique provides a way to break complicated problems down into simple problems which are easier to solve.

example:

      public class Main {
        public static void main(String[] args) {
          int result = sum(10);
          System.out.println(result);
        }
        public static int sum(int k) {
          if (k > 0) {
            return k + sum(k - 1);
          } else {
            return 0;
          }
        }
        // 55
      }
    

example explained: when the sum() function is called, it adds parameter k to the sum of all numbers smaller than k and returns the result. When k becomes 0, the function just returns 0. When running, the program follows these steps:
10 + sum(9)
10 + ( 9 + sum(8) )
10 + ( 9 + ( 8 + sum(7) ) )
...
10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + sum(0)
10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + 0
Since the function does not call itself when k is 0, the program stops there and returns the result.

Just as loops can run into the problem of infinite looping, recursive functions can run into the problem of infinite recursion.

Infinite recursion is when the function never stops calling itself. Every recursive function should have a halting condition, which is the condition where the function stops calling itself.

example:

        public class Main {
          public static void main(String[] args) {
            int result = sum(5, 10);
            System.out.println(result);
          }
          public static int sum(int start, int end) {
            if (end > start) {
              return end + sum(start, end - 1);
            } else {
              return end;
            }
          }
        }
      

example explained: the function adds a range of numbers between a start and an end. The "halting condition" for this recursive function is "when end is not greater than start".