Download as pdf or txt
Download as pdf or txt
You are on page 1of 32

Object Oriented System Design - ICT 325 (3)

Java Methods

Dr. R. A. H. M. Rupasingha
Senior Lecturer in Computer Science
Content

• Java Methods
• Java Method Parameters
• Java Method Overloading

2
Java Methods

• Methods are used to perform certain actions, and they are also
known as functions.

Why use methods?


• Methods are time savers and allow us to reuse the code without
retyping the code.
• To reuse code: define the code once, and use it many times.

3
How it works?

• A method is a block of code which only runs when it is called.


• A method is a collection of statements that perform some
specific task and return the result to the caller.
•A method can perform some specific task without returning
anything.

4
Types of Java Methods

1. Standard library methods


2. User-defined methods

5
Types of Java Methods (Cont.)
1. Standard Library Methods
• The standard library methods are built-in methods in Java that are
already available for use.
• These standard libraries come along with the Java Class Library (JCL)
in a Java archive (*.jar) file with JVM and JRE.
• Eg:
• Java provides some pre-defined methods, such as
System.out.println(). print() is a method of java.io.PrintSteam.
The print("...") prints the string inside quotation marks.
• sqrt()
is a method of Math class. It returns square root of a
number.
6
Types of Java Methods (Cont.)
1. Standard Library Methods (Cont.)

Example 01
public class MyClass
{
public static void main(String[] args) {
System.out.print("Square root of 4 is: " + Math.sqrt(4));
}
}
Output:
Square root of 4 is: 2.0 7
Types of Java Methods (Cont.)

2. User-defined methods
• You can also define methods inside a class as per your wish.
Such methods are called user-defined methods.

• Before you can use (call a method), you need to define it.
• Let’s see how to define methods in Java.

8
Create a Method
• A method must be declared within a class.
• It is defined with the name of the method, followed by
parentheses (). You can pass data, known as parameters, into a
method.
Naming
• The 1st letter should be lower case and then normal camelcase
rules should be use.
• The names should typically be verb, nouns or phases.
• Eg: getBalance(); doCalculate(); setCustomerName();
9
Create a Method (Cont.)
modifier return type name of the method
public class MyClass {
Example 02
static void myMethod() {
Create a method inside MyClass: // code to be executed
}
}
• myMethod() is the name of the method.
• static means that the method belongs to the MyClass class and
not an object of the MyClass class. (You will learn more about
objects and how to access methods through objects later.)
• void means that this method does not have a return value. (You
will learn more about return values later.) 10
Call a Method
• Now you defined a method, you need to use it. For that, you
have to call the method.
• To call a method in Java, write the method's name followed by
two parentheses () and a semicolon;
- Eg: myMethod() ;
• In the following example, myMethod() is used to print a text (the
action), when it is called:

11
Call a Method (Cont.) myMethod();

myMethod();

1. While Java is executing the program code, it encounters myMethod(); in


the code.
2. The execution then branches to the myMethod() method, and executes
code inside the body of the method.
3. After the codes execution inside the method body is completed, the
program returns to the original state and executes the next statement.
12
Call a Method (Cont.)
Example 02 (Cont.)
• Inside main, call the myMethod() method:
public class MyClass {
static void myMethod() {
System.out.println("My first example");
}
Output:
public static void main(String[] args) { My first example
myMethod();
}
} 13
Call a Method (Cont.)
Example 02 (Cont.)
• A method can also be called multiple times:
public class MyClass {
static void myMethod() {
System.out.println("My first example");
}
public static void main(String[] args) {
myMethod(); Output:
myMethod(); My first example
myMethod(); My first example
} My first example
} 14
Content

• Java Methods
• Java Method Parameters
• Java Method Overloading

15
Parameters and Arguments

• 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.

16
Parameters and Arguments - Example 01
• 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:
type Parameter
public class MyClass {
static void myMethod(String fname) {
System.out.println(fname + " Perera");
}
Output:
public static void main(String[] args) {
myMethod("Kamal"); Kamal Perera
myMethod("Sumudhu"); Sumudhu Perera
myMethod("Nimal"); Nimal Perera
}
} Arguments 17
Multiple Parameters - Example 02
• You can have as many parameters as you like:
Parameter list
public class MyClass {
static void myMethod(String fname, int age) {
System.out.println(fname + " is " + age);
}
public static void main(String[] args) { Output:
myMethod("Kamal", 15); Kamal is 15
myMethod("Sumudu", 8); Sumudu is 8
myMethod("Nimal", 10); Nimal is 10
}
} Arguments 18
Components of Method Declarations
• In general, method declarations has five components :
2 3 4

19
Components of Method Declarations (Cont.)

1. Modifier-: Defines access type of the method i.e. from where it


can be accessed in your application. In Java, there are 4 type of the
access specifiers.
1. public: accessible in all class in your application.
2. protected: accessible within the class in which it is defined and
in its subclass(es)
3. private: accessible only within the class in which it is defined.
4. default (declared/defined without using any modifier):
accessible within same class and package within which its class
is defined.
20
Components of Method Declarations (Cont.)
2. The return type : The data type (Eg: int, char) of the value
returned by the method or void if does not return a value.
3. Method Name : The rules for field names apply to method
names.
4. Parameter list : Comma separated list of the input parameters are
defined, preceded with their data type, within the enclosed
parenthesis. If there are no parameters, you must use empty
parentheses ().
5. Method body : It is enclosed between braces. The code you need
to be executed to perform your intended operations. 21
Return Values

• The void keyword, used in the examples above, 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.

22
Return Values - Example 03

public class MyClass {


static int myMethod(int x) {
return 5 + x;
}
Output:
public static void main(String[] args) { 8
System.out.println(myMethod(3));
}
}
23
Return Values - Example 04
• This example returns the sum of a method's two parameters:

public class MyClass {


static int myMethod(int x, int y) {
return x + y;
}
Output:
8
public static void main(String[] args) {
System.out.println(myMethod(5, 3));
}
}
24
Return Values - Example 05
• You can also store the result in a variable (recommended, as it is
easier to read and maintain).
public class MyClass {
static int myMethod(int x, int y) {
return x + y;
} Output:
8
public static void main(String[] args) {
int z = myMethod(5, 3);
System.out.println(z);
}
} 25
A Method with If...Else - Example 06
public class MyClass {
// Create a checkAge() method with an integer variable called age
static void checkAge(int age) {

• It is common to use // If age is less than 18, print "student"


if...else statements if (age < 18) {
inside methods: System.out.println("student");
// If age is greater than 18, print "not a student"
} else {
System.out.println("not a student");
}
}
Output: public static void main(String[] args) {
not a student // Call the checkAge() method and pass along an age of 20
checkAge(20); }
} 26
Content

• Java Methods
• Java Method Parameters
• Java Method Overloading

27
Method Overloading

• With method overloading, multiple methods can have the same


name with different parameters:
• Example:
int myMethod(int x)
float myMethod(float x)
double myMethod(double x, double y)

28
Method Overloading public class MyClass {
- Example 01 static int plusMethodInt(int x, int y) {
return x + y;
• Consider the following }
static double plusMethodDouble(double x, double y) {
example, which have two
return x + y;
methods that add numbers
}
of different type:
public static void main(String[] args) {
int myNum1 = plusMethodInt(8, 5);
double myNum2 = plusMethodDouble(4.3, 6.26);
System.out.println("int: " + myNum1);
Output System.out.println("double: " + myNum2);
int: 13 }
double: 10.559999999999999 } 29
Method Overloading - Example 01 (Cont.)
public class MyClass {
static int plusMethod(int x, int y) {
• Instead of defining two methods return x + y;
that should do the same thing, }
it is better to overload one. static double plusMethod(double x, double y) {
• In the example below, we return x + y;
}
overload the plusMethod
public static void main(String[] args) {
method to work for both int and
int myNum1 = plusMethod(8, 5);
double: double myNum2 = plusMethod(4.3, 6.26);
• Note: Multiple methods can System.out.println("int: " + myNum1);
have the same name as long as System.out.println("double: " + myNum2);
the number and/or type of }
} Output
parameters are different. int: 13
30
double: 10.559999999999999
Summary
• Java Methods
• How it works?
• Types of Java Methods
• Create a Method
• Call a Method
• Java Method Parameters
• Parameters and Arguments
• Multiple Parameters
• Components of Method Declarations
• Return Values
• A Method with If...Else
• Java Method Overloading 31

• Method Overloading with Examples


Questions?

End. 32

You might also like