Lecture_5-Methods_And_Method OverLoading.pptx
Lecture_5-Methods_And_Method OverLoading.pptx
2
Topic – 1: Methods in Java
3
Java Methods
4
Types of Methods:
• Standard Library Methods: These are built-in methods in Java that are
available to use. Such as, print(), nextInt(), sqrt() and many more
5
Syntax of Defining a function
6
Here,
• Modifier: it defines the access type of the method
7
Categories of User-Defined Methods:
8
Example -1: Add two integer values using method
9
A method is always invoked with respect to an object.
10
Example- 2:
• Define a method called max(). This method takes two parameters num1
and num2 and returns the maximum between the two.
Try yourself!
11
Solution 1:
*Without using object
If we want to call any method
without any object,
then we have to declare
the method as static.
12
Solution 2:
*Using object
13
Example-3 : Convert this UML to Java Code
14
Solution
15
Visit the links for more details:
• https://www.javatpoint.com/method-in-java
• https://www.tutorialspoint.com/java/java_methods.htm
• https://www.w3schools.com/java/java_methods.asp
16
Topic –Method
2: MethodOverloading
Overloading in Java
17
Try?
• Write a program that will add two integer numbers, and three integer
numbers using two different methods and display two result.
• Write a program that will add two integer numbers, and two double numbers
two different methods and display two result.
18
Method Overloading
• When a class has two or more methods by same name but different
parameters, it is known as method overloading.
19
Different ways to overload the method
20
1. By changing number of arguments
public class MethodOverloading {
21
2. By changing data type of argument
public class MethodOverloading2 {
In this example, we have created two
void sum(int a,int b) overloaded methods that differs in
{ data type. The first sum method
System.out.println(a+b); receives two integer arguments and
} second sum method receives two
double arguments.
void sum(double a, double b)
{
System.out.println(a+b);
}
• Find out the maximum value between two integer numbers, three integer
numbers and two double numbers.
23
Thank you!
24