Professional Documents
Culture Documents
0 Java Language
4.5 Method
4.5.1 Introduction to Java Method
Learning Outcomes :
method(){
statement 1
statement 2 Performs a specific task
statement 3
}
}
Definition
❖ A method is a collection of statements that performs a specific task.
* Methods are bound to a class and they define the behavior of a class.
• All methods starts with a lowercase and ends with parentheses()
class Salary {
}
Definition
❖A method is a collection of statements that performs a specific task.
* Methods are bound to a class and they define the behavior of a class.
• All methods starts with a lowercase and ends with parentheses()
class Salary {
}
Find out how many methods do you have in this program.
import java.util.Scanner;
Lists of methods
class FindMethod{
public static void main(String[]args){
main()
Scanner in = new Scanner(System.in);
nextDouble()
double a,b;
pow()
a = in.nextDouble();
sqrt()
b = in.nextDouble();
println()
System.out.println(Math.pow(a,b));
System.out.println(Math.sqrt(a*a));
}
}
Purpose
❖Used to break complex program into small, manageable
pieces program.
Advantages
❖Code reusability (can be used many times)
❖Make code more readable
double a,b;
a = in.nextDouble(); // method nextDouble() used twice
b = in.nextDouble();
System.out.println(Math.pow(a,5));
// method println() and Math.pow() used
System.out.println(Math.pow(b,10)); twice
}
}