Lecture 4: Methods / Functions
Concept
Mr. Tarus
Outline
Introduction to methods in Java.
Java class Methods.
Types of Method.
Method Calling in Java.
Role of methods in Java
Method Overloading
Recursion
Introduction: Methods Method1Demo.java
Nb: Method definition, types, method declaration, how to call methods in java.
Block of code or collection of statements or a set of code grouped together to
perform a certain task or operation.
Block of code which only runs when it is called.
Methods allow / facilitate code re-use
Provides easy modification and readability of code.
Provide the location and isolation of faulty functions.
Improves efficiency and organization of the program.
Important method in Java : main()
Reasons: (Role of main())
To initiate and terminate program execution.
To control and coordinate other functions and classes in the
program
PTO…
Nb: Java methods must be declared inside a class. Method1Demo.java
Syntax of a Method
<access_modifier> <return_type> <method_name>( list_of_parameters)
{
//body
}
Pto…
Key Components of a Method Declaration
Modifier: It specifies the method’s access level (e.g., public, private, protected,
or default).
Return Type: The type of value returned, or void if no value is returned.
Method Name: It follows Java naming conventions; it should start with a
lowercase verb and use camel case for multiple words.
Parameters: A list of input values (optional). Empty parentheses are used if no
parameters are needed.
Exception List: The exceptions the method might throw (optional).
Method Body: It contains the logic to be executed (optional in the case of
abstract methods).
Java main() method
main() is the starting point for JVM to start execution of java program.
Without the main() method, JVM will not execute the program.
syntax of the main() method:
Explanation
• Public:
• Access specifier
• public keyword before the main() method aids JVM to identify the
execution point of the program.
• Static:
• Implies that main method can be called without an object.
• Any function that is preceded by the keyword static is a static method.
• Static methods: methods that can be invoked without using/creating an
object.
Pto…
void:
Return type.
Void acknowledges the compiler that main() does not return any value.
main():
Default signature which is predefined in the JVM.
Called by JVM to execute a program.
String args[]:
Implies that main() accepts data from the user.
Accepts a group of strings (string array), and used to hold the command
line arguments in the form of string values.
Execution Process
First, JVM executes the static block.
Secondly, JVM executes static methods.
Thirdly, creates the object needed by the program.
Finally, executes the instance methods.
Nb: JVM executes a static block on the highest priority basis.
Demo2X .java
public class Demo2X {
static void oneTwo() //static block
{
System.out.println("Static block");
}
public static void main(String args[]) //static method
{
System.out.println("Static method");
Demo2 d = new Demo2();
} }
Demo2.java = Demo2.class
Java class Methods Demo2X.java
Instance methods:
Methods that belong to a class
Non-static methods defined in the class.
To call instance methods, compulsory create an object of its class.
Two types: StudentXy.java
Accessor Method / Getter methods
Mutator Method / Setter methods
Accessor Method
Method(s) that reads the instance variable(s).
Prefixed with the word get
Also known as getters.
Returns the value of the private field.
Used to get the value of the private field.
Mutator Method
Method(s) that read the instance variable(s) and also modify the values.
Prefixed with the word set.
Also known as setters or modifiers.
Does not return anything.
Accepts a parameter of the same data type that depends on the field.
Used to set the value of the private field.
Pto…
Static Method:
Methods preceded by the keyword static.
Methods that belong to the class.
Methods that can be accessed without using/creating an object.
Can be invoked by using the class name.
StaticDemo.java
Types of Method
1. Predefined Methods / Library Methods
2. User-defined Methods
Predefined / Standard library / Built-in method.
Methods that are already defined in the Java class libraries.
Use these methods directly by just by calling them in the program.
Examples: length(), equals(), compareTo(), sqrt(), etc.
Nb: Every predefined method is defined inside a class. Demo3.java
public class Demo3
{
public static void main(String[] args)
{
// using the max() method of Math class
System.out.print("The maximum number is: " + Math.max(9,7));
System.out.print("The abslute number is: " + Math.abs(-10));
System.out.print("The squareroot number is: " + Math.sqrt(25));
User-defined Method
Methods written by a user at time of coding. E.g., myMethod(), addition()
import java.util.Scanner; //user defined method
public class EvenOdd
public static void findEvenOdd(int num)
{
public static void main (String args[]) {
{ if(num%2==0)
//creating Scanner class object System.out.println(num+" is
Scanner scan=new Scanner(System.in); even");
System.out.print("Enter the number: "); else
System.out.println(num+" is
//reading value from user odd");
int num=scan.nextInt();
}
//method calling
findEvenOdd(num); } nb: Addition5.java
Method Declaration
Methods are user defined data types.
Declaration provides information about method attributes, such as visibility,
return-type, name, and arguments.
Syntax:
Explanation
Method Signature:
Includes method name and parameter list.
Access Specifier / Modifier:
Access type of the method.
To specify the visibility of the method. (4 types).
• Public: Method is accessible by all classes.
• Private: Method is accessible only in the classes in which it is defined.
• Protected: Method is accessible within the same package or subclasses in a
different package.
• Default: When we do not use any access specifier in the method
declaration, Java uses default access specifier by default. It is visible only
from the same package only.
PTO…
Return Type:
data type that the method returns. Eg, int, float, double String,void
Method Name:
A valid identifier / name selected to be the name of the method.
Parameter List:
list of parameters args and their return types.
Method Body:
The part contains all the actions to be performed.
Method Calling in Java
Calling without parameters MethodCalling.java
Call by value. Same as C language: CallByValue.java
NB: No call by reference.
Return Values
Value that the method returns after executing;
Examples: void, primitive data types (int, float, double, String, Char).
ReturnDemo.java
Advantages of Methods
Reusability: Methods allow us to write code once and use it many times.
Abstraction: Methods allow us to abstract away complex logic and provide a
simple interface for others to use.
Encapsulation: Allow to encapsulate complex logic and data
Modularity: Methods allow us to break up your code into smaller, more
manageable units, improving the modularity of your code.
Customization: Easy to customize for specific tasks.
Improved performance: By organizing your code into well-structured methods,
you can improve performance by reducing the amount of code.
Method Overloading
Method Overloading allows different methods to have the same name, but different
signatures where the signature can differ by the number of input parameters or type
of input parameters, or a mixture of both.
Also known as Compile-time Polymorphism, Static Polymorphism, or Early
binding OverloadDemo.java, SumOverload.java
int myMethod(int x)
int myMethod(int x,int y)
float myMethod(float x)
Different Ways of Method Overloading in Java
Changing the Number of Parameters. DriverClass.java
Changing Data Types of the Arguments. DriverClass1.java
Changing the Order of the Parameters of Methods. DriverClass3.java
Advantages of Method Overloading
Method overloading improves the Readability and reusability of the program.
Method overloading reduces the complexity of the program.
Using method overloading, programmers can perform a task efficiently and
effectively.
Using method overloading, it is possible to access methods performing related
functions with slightly different arguments and types.
Objects of a class can also be initialized in different ways using the
constructors.
Java Recursion RecursionExample1.java
Technique which provides a way to break complicated problems down into
simple problems which are easier to solve.
Example: RecursionExample2.java
class RecursionExample1 {
static void p(){
System.out.println("hello");
p();
}
public static void main(String[] args) {
p();
}
}
import java.util.Scanner;
public class RecursionExample1 {
static int factorial(int n){
if (n == 1)
return 1;
else
return(n * factorial(n-1));
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number");
int num = sc.nextInt();
System.out.println("Factorial of entered number is: " + factorial(num));