Lesson Objective
Understand the concept of Subroutines in Java.
- Methods
- Parameters
- Overloading
- Scope
- Recursion
KS3, GCSE, A-Level Computing Resources
Understand the concept of Subroutines in Java.
A method is a block of code that only runs when it is called.
You can pass data (parameters) into a method.
Methods are used to carry out specific tasks. They are also known as functions.
Methods are also used to save time and effort. You write the code once and use it over and over again, instead of repeating yourself.
public class Hello_World_1{ static void myMethod() { } }
A method must be declared within a class and can be declared by specifying its name followed by parentheses ().
Java offers a range of built-in methods, such as System.out.println().
public class Hello_World_1 { static void myMethod() { System.out.println("This is a Methods!"); } public static void main(String[] args) { myMethod(); myMethod(); myMethod(); } } // To call a method in Java, write the method's name followed by two parentheses () and a semicolon;
This is a Methods! This is a Methods! This is a Methods!
Methods in Java can receive information through parameters, which function as variables within the method.
These parameters are specified within the parentheses following the method name.
It is possible to include multiple parameters by separating them with commas, allowing for flexible and customizable method behavior.
The following 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.
public class Hello_World_1 { static void myMethod(String fname) { System.out.println(fname + " is a person"); } public static void main(String[] args) { myMethod("Meran"); myMethod("Ramzan"); myMethod("Gasper"); } }
Meran is a person Ramzan is a person Gasper is a person
When a parameter is passed to the method, it is called an argument.
fname = Parameter
“Meran” = Argument
You can also use multiple parameters in a method.
public class Hello_World_1 { static void myMethod(String fname, int age) { System.out.println(fname + " is " + age); } public static void main(String[] args) { myMethod("Fei", 35); myMethod("Mhela", 8); myMethod("Sheikh", 7); } }
Fei is 35 Mhela is 8 Sheikh is 7
Note:
When calling a method with multiple parameters, you must provide the same number of arguments as the method expects, and those arguments must be passed in the same order that they are declared in the method definition.
The “void” keyword, which is used in most of the given examples, signifies that the method is not intended to generate a result.
If you want the method to provide a return value, you can substitute “void” with a primitive data type (like int, char, etc.) and employ the “return” keyword within the method.
This example returns the addition of the defined method's two parameters.
public class Hello_World_1{ static int myMethod(int x, int y) { return x + y; } public static void main(String[] args) { int z = myMethod(5, 3); System.out.println(z); System.out.println(myMethod(5, 4)); } } // You can also store the result in a variable. This is recommended, as it is easier to read and maintain in the future. // The example shows how to store the result into a variable, and also how to simply display the result.
8 9
In Java, variables have limited accessibility and are accessible to the specific portion of code where they are defined. This concept is referred to as "scope."
When variables are declared within a method, they can be accessed anywhere within that method.
public class Hello_World_1 { public static void main(String[] args) { // Code here CANNOT use x int x = 100; // Code here can use x System.out.println(x); } }
A block of code refers to all the code enclosed within a pair of curly braces {}.
Variables that are declared within these code blocks are only accessible within the specific block of code in which they are defined.
public class Hello_World_1 { 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.
Recursion is when a function calls itself - Not endless.
A recursive function has a base case, a simple version of the problem that the function can solve directly. The function then breaks down more complex problems into this simpler form, calling itself on the smaller pieces until it reaches the base case.
For example, imagine a function that calculates factorials. A factorial is the product of all positive integers less than or equal to a number. So, 5! (factorial of 5) is 5 x 4 x 3 x 2 x 1. The recursive function to solve this could say:
The factorial of 1 is 1 (the base case).
For any other number, the factorial is that number times the factorial of the number minus 1.
The example below uses recursion to add all of the numbers up to 10.
public class Hello_World_1 { 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
The developer should be very careful with recursion as it can be quite easy to slip into writing a function which never terminates, or one that uses excess amounts of memory or processor power.
However, when written correctly recursion can be a very efficient and mathematically-elegant approach to programming.