SlideShare a Scribd company logo
1 of 59
Download to read offline
JAVA Programming-I
Lecturer: Mr. Lim Lyheng Tel/Telegram: +855 11 855297 @LimLyheng
1
ែចកចំេណះនិងបទពិេសធន៍
2
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
Contents
1. Java Method Introduction
2. Types of Methods
1. Standard Library Methods
2. User-defined Methods
3. How to create a user-defined methods
4. Recursive Methods
5. Method Overloading
6. Method Overriding
7. Method Overloading Vs Overriding
8. Constructors
3
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
1.Introduction
 In mathematics, you might have studied about functions.
For example, f(x) = x2 is a function that returns squared
value of x.
If x = 2, then f(2) = 4
If x = 3, f(3) = 9 and so on.
 Similarly, in programming, a function is a block of code
that performs a specific task.
 In Java, method is a jargon used for function.
 Methods are bound to a class and they define the behavior
of a class.
4
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
2.Type of Java Methods
 Depending on whether a method is defined by the user, or
available in standard library, there are two types of
methods:
1. Standard Library Methods
2. User-defined Methods
 What are the advantages of using methods?
 The main advantage is code reusability.
 You can write a method once, and use it multiple times.
 You do not have to rewrite the entire code each time. Think of it
as, "write once, reuse multiple times."
5
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
2.1 Standard Library Methods
 The standard library methods are built-in methods in Java
that are readily available for use.
 These standard libraries come along with the Java Class
Library (JCL) in a Java archive (*.jar) file with JVM( Java
Virtual Machine and JRE (Java Runtime Environment).
 For example, 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
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
Example-1 standard library method sqrt()
7
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
Example-2 standard library method Date()
8
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
Example-3 standard library method Math.pow()
9
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
2.2 User-defined Methods
 You can also define methods inside a class as per your
wish. Such methods are called user-defined methods.
 How to create a user-defined method?
 Before you can use (call a method), you need to define
it. Here is how you define methods in Java.
 Here, a method named myMethod() is defined.
public static void myMethod() {
System.out.println(“My Function called”);
}
10
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
Example user-defined method
11
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
3. How to create a user-defined method?
Syntax for a method:
The syntax shown above includes:
 modifier − It defines the access type of the method and it is optional to use.
 returnType − Method may return a value.
 nameOfMethod − This is the method name. The method signature consists of
the method name and the parameter list.
 Parameter List − The list of parameters, it is the type, order, and number of
parameters of a method. These are optional, method may contain zero
parameters.
 method body − The method body defines what the method does with the
statements.
modifier returnValueType methodName(list of parameters){
// Method body;
}
12
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
public static int max(int num1, int num2){
int result;
if if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
Example-Define a method
int z = max(x, y);
Invoke a method
modifier
return value
type
method name
formal parameters
parameter list
return value
method
body
actual parameters
(arguments)
 A parameter is a special kind of
variable in computer
programming language that is
used to pass information
between functions or procedures.
 The actual information passed is
called an argument.
13
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
3.1 Method Calling
 For using a method, it should be called. There are two ways in
which a method is called:
1. method returns a value
2. returning nothing (no return value).
 The process of method calling is simple. When a program
invokes a method, the program control gets transferred to the
called method. This called method then returns control to the
caller in two conditions, when
1. the return statement is executed.
2. it reaches the method ending closing brace.
For example
The method returning value can be understood by the following example:
int result = sum(6, 9);
System.out.println("This is return nothing!")
14
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
Example: Method Calling Return Value
15
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
3.2. The void Keyword (method not return Value)
 The void keyword allows us to create methods
which do not return a value.
 This method is a void method, which does not
return any value.
 Call to a void method must be a statement
i.e. methodRankPoints(499.50);. It is a Java
statement which ends with a semicolon as shown in
the following example.
16
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
Example: Void Method( not return value)
17
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
3.3 Passing data in Java (Passing Values to Method)
 When it comes to Java programming, one of the trickiest questions is:
 Does Java pass variables to methods by reference or by value?
 This has been raising a lot of debates and making confusion for beginners.
 However, the ultimate answer is crystal clear:
Java always passes variables by value.
 Or in other words:
Java passes object references to methods by value.
 Pass-by-value: A copy of the passed-in variable is copied into the argument of
the method. Any changes to the argument do not affect the original one.
 Pass-by-reference: The argument is an alias of the passed-in variable. Any
changes to the argument will affect the original one.
Note: There is only call by value in java, not call by reference
18
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
Example-1: Java passes object references to methods by value:
19
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
3.4 Java Methods with Arguments and Return Value
A Java method can have zero or more parameters. And, they may
return a value.
20
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
3.5 Method Accepting Arguments and Returning Value
21
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
3.6 passing more than one argument to method by using
commas
22
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
Example: Get Squared Value Of Numbers from 1 to 5
23
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
4.Recursive Method
 A method that calls itself is known as a recursive
method.
 And, this technique is known as recursion.
 A physical world example would be to place two
parallel mirrors facing each other.
 Any object in between them would be reflected
recursively.
24
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
4.1 How recursion works?
 recurse() method is called from inside the main method at first
(normal method call).
 Also, recurse() method is called from inside the same method,
recurse(). This is a recursive call.
25
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
Example: Factorial of a Number Using Recursion
26
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
4.2 Advantages and Disadvantages of Recursion
 When a recursive call is made, new storage
location for variables are allocated on the stack.
 As, each recursive call returns, the old variables
and parameters are removed from the stack.
 Hence, recursion generally use more memory and
are generally slow.
 On the other hand, recursive solution is much
simpler and takes less time to write, debug and
maintain.
27
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
5. Method Overloading
 Method Overloading is a feature that allows a class
to have more than one method having the same
name, if their argument lists are different.
 It is similar to constructor overloading in Java, that
allows a class to have more than one constructor
having different argument lists.
void func() { ... }
void func(int a) { ... }
float func(double a) { ... }
float func(int a, float b) { ... }
28
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
5.1 Ways to create Method Overloading
In Java, two or more methods can have same name if they
differ in parameters:
1. different number of parameters
2. different types of parameters, or both.
29
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
Example-1 Overloading by changing number of arguments
30
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
Example-2 By changing the datatype of parameters
31
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
5.2 Why method overloading?
 Suppose, you have to perform addition of the given numbers but
there can be any number of arguments (let’s say either 2 or 3
arguments for simplicity).
 In order to accomplish the task, you can create two methods
sum2num(int, int) and sum3num(int, int, int) for two and three
parameters respectively.
 However, other programmers as well as you in future may get
confused as the behavior of both methods is same but they differ by
name.
 The better way to accomplish this task is by overloading methods.
And, depending upon the argument passed, one of the overloaded
methods is called. This helps to increase readability of the program
32
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
Example method overloading
33
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
Example method overloading
34
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
6. Method Overriding
 If subclass (child class) has the same method as
declared in the parent class, it is known as method
overriding in java.
 In other words, If subclass provides the specific
implementation of the method that has been
provided by one of its parent class, it is known as
method overriding.
35
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
6.1 Usage of Method Overriding
 Method overriding is used to provide specific
implementation of a method that is already
provided by its super class.
 Method overriding is used for runtime
polymorphism
36
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
6.2 Rules for Java Method Overriding
1. method must have same name as in the parent class
2. method must have same parameter as in the parent
class.
3. must be IS-A relationship (inheritance).
37
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
Example of Java Method Overriding
Consider a scenario, Bank is a class that provides functionality to get
rate of interest. But, rate of interest varies according to banks. For
example, SBI, ICICI and AXIS banks could provide 8%, 7% and 9%
rate of interest.
38
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
Example of Method Overriding
39
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
7. Method Overloading Vs Overriding
40
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
8. Constructors in Java
 Constructor is a block of code that initializes the newly
created object.
 A constructor resembles an instance method in java but it’s
not a method as it doesn’t have a return type.
 Constructor has same name as the class and looks like this
in a java code.
 Note that the constructor name matches with the class
name and it doesn’t have a return type.
41
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
8.1 How does a constructor work
 Here we have created an object obj of class Hello and then we
displayed the instance variable name of the object.
 The output ‘‘BeginnersBook.com’’passed to the name during
initialization in constructor.
 This shows that when we created the object obj the constructor got
invoked. this keyword refers to the current object, object obj in this
example.
42
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
8.1 How does a constructor work
 To understand the working of constructor, lets take an example.
 lets say we have a class MyClass. When we create the object of
MyClass like this: MyClass obj = new MyClass()
 The new keyword here creates the object of class MyClass and
invokes the constructor to initialize this newly created object.
43
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
8.2 Types of Constructor works
There are three types of constructors:
 Default,
 No-arg constructor
 Parameterized.
44
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
8.2.1 Default constructor
 If you do not implement any constructor in your
class, Java compiler inserts a default constructor
into your code on your behalf.
 This constructor is known as default constructor.
 You would not find it in your source code(the java
file) as it would be inserted into the code during
compilation and exists in .class file.
 This process is shown in the diagram below:
45
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
8.2.1 Default constructor ( Cont’d)
If you implement any constructor then you no longer
receive a default constructor from Java compiler.
46
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
8.2.2 no-argument constructor
 Constructor with no arguments is known as no-arg
constructor.
 The signature is same as default constructor, however body
can have any code unlike default constructor where the
body of the constructor is empty.
 Although you may see some people claim that that default
and no-arg constructor is same but in fact they are not,
even if you write public Demo() { } in your class Demo it
cannot be called default constructor since you have written
the code of it.
47
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
Example no-argument constructor
48
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
8.2.3 Parameterized constructor
 Constructor with arguments(or you can say
parameters) is known as Parameterized constructor.
 Example: parameterized constructor
 In this example we have a parameterized
constructor with two parameters id and name.
While creating the objects obj1 and obj2 I have
passed two arguments so that this constructor gets
invoked after creation of obj1 and obj2.
49
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
Example1- Parameterized constructor
50
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
Example2- Parameterized constructor
 In this example, we have two
constructors, a default
constructor and a parameterized
constructor.
 When we do not pass any
parameter while creating the
object using new keyword then
default constructor is invoked,
however
 when you pass a parameter then
parameterized constructor that
matches with the passed
parameters list gets invoked.
51
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
8.3 Constructor Chaining
When A constructor calls another constructor of same class then this is
called constructor chaining.
52
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
8.3.1 Constructor Chaining: super()
Whenever a child class constructor gets invoked it implicitly invokes
the constructor of parent class. You can also say that the compiler inserts
a super(); statement at the beginning of child class constructor.
53
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
8.4 Constructor Overloading
Constructor overloading is a concept of having more than one
constructor with different parameters list, in such a way so that each
constructor performs a different task.
54
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
Example-Constructor Overloading
55
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
Example-Constructor Overloading
56
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
Example-Constructor Overloading
57
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
Powerpoint Templates 58
Lecturer: Mr. Lim Lyheng Tel/Telegram: +855 11 855297 @LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
Powerpoint Templates
End of Chapter 4
59
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍

More Related Content

Similar to Chapter4__Method_Lim Lyheng_RULE (2).pdf

Corejavainterviewquestions.doc
Corejavainterviewquestions.docCorejavainterviewquestions.doc
Corejavainterviewquestions.doc
Joyce Thomas
 
JAVA VIVA QUESTIONS_CODERS LODGE.pdf
JAVA VIVA QUESTIONS_CODERS LODGE.pdfJAVA VIVA QUESTIONS_CODERS LODGE.pdf
JAVA VIVA QUESTIONS_CODERS LODGE.pdf
nofakeNews
 
INDUMATHY- UNIT 1 cs3391 oops introduction to oop and java.pptx
INDUMATHY- UNIT 1 cs3391 oops introduction to oop and java.pptxINDUMATHY- UNIT 1 cs3391 oops introduction to oop and java.pptx
INDUMATHY- UNIT 1 cs3391 oops introduction to oop and java.pptx
Indu65
 

Similar to Chapter4__Method_Lim Lyheng_RULE (2).pdf (20)

OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
 
Computer programming 2 Lesson 15
Computer programming 2  Lesson 15Computer programming 2  Lesson 15
Computer programming 2 Lesson 15
 
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
 
Lecture5_Method_overloading_Final power point presentation
Lecture5_Method_overloading_Final power point presentationLecture5_Method_overloading_Final power point presentation
Lecture5_Method_overloading_Final power point presentation
 
Lecture4_Method_overloading power point presentaion
Lecture4_Method_overloading power point presentaionLecture4_Method_overloading power point presentaion
Lecture4_Method_overloading power point presentaion
 
UNIT1-JAVA.pptx
UNIT1-JAVA.pptxUNIT1-JAVA.pptx
UNIT1-JAVA.pptx
 
Class
ClassClass
Class
 
Mca2030 object oriented programming – c++
Mca2030  object oriented programming – c++Mca2030  object oriented programming – c++
Mca2030 object oriented programming – c++
 
Mca2030 object oriented programming – c++
Mca2030  object oriented programming – c++Mca2030  object oriented programming – c++
Mca2030 object oriented programming – c++
 
Corejavainterviewquestions.doc
Corejavainterviewquestions.docCorejavainterviewquestions.doc
Corejavainterviewquestions.doc
 
Learn java lessons_online
Learn java lessons_onlineLearn java lessons_online
Learn java lessons_online
 
JAVA VIVA QUESTIONS_CODERS LODGE.pdf
JAVA VIVA QUESTIONS_CODERS LODGE.pdfJAVA VIVA QUESTIONS_CODERS LODGE.pdf
JAVA VIVA QUESTIONS_CODERS LODGE.pdf
 
E3
E3E3
E3
 
Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...
Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...
Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...
 
INDUMATHY- UNIT 1 cs3391 oops introduction to oop and java.pptx
INDUMATHY- UNIT 1 cs3391 oops introduction to oop and java.pptxINDUMATHY- UNIT 1 cs3391 oops introduction to oop and java.pptx
INDUMATHY- UNIT 1 cs3391 oops introduction to oop and java.pptx
 
Java Polymorphism: Types And Examples (Geekster)
Java Polymorphism: Types And Examples (Geekster)Java Polymorphism: Types And Examples (Geekster)
Java Polymorphism: Types And Examples (Geekster)
 
Polymorphism.pptx
Polymorphism.pptxPolymorphism.pptx
Polymorphism.pptx
 
Object oriented programming in python
Object oriented programming in pythonObject oriented programming in python
Object oriented programming in python
 
Suga java training_with_footer
Suga java training_with_footerSuga java training_with_footer
Suga java training_with_footer
 
Java method present by showrov ahamed
Java method present by showrov ahamedJava method present by showrov ahamed
Java method present by showrov ahamed
 

Recently uploaded

Personalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes GuàrdiaPersonalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes Guàrdia
EADTU
 
Orientation Canvas Course Presentation.pdf
Orientation Canvas Course Presentation.pdfOrientation Canvas Course Presentation.pdf
Orientation Canvas Course Presentation.pdf
Elizabeth Walsh
 
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lessonQUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
httgc7rh9c
 
MuleSoft Integration with AWS Textract | Calling AWS Textract API |AWS - Clou...
MuleSoft Integration with AWS Textract | Calling AWS Textract API |AWS - Clou...MuleSoft Integration with AWS Textract | Calling AWS Textract API |AWS - Clou...
MuleSoft Integration with AWS Textract | Calling AWS Textract API |AWS - Clou...
MysoreMuleSoftMeetup
 

Recently uploaded (20)

How to Add a Tool Tip to a Field in Odoo 17
How to Add a Tool Tip to a Field in Odoo 17How to Add a Tool Tip to a Field in Odoo 17
How to Add a Tool Tip to a Field in Odoo 17
 
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdfFICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
Personalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes GuàrdiaPersonalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes Guàrdia
 
AIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptAIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.ppt
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
Orientation Canvas Course Presentation.pdf
Orientation Canvas Course Presentation.pdfOrientation Canvas Course Presentation.pdf
Orientation Canvas Course Presentation.pdf
 
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lessonQUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Simple, Complex, and Compound Sentences Exercises.pdf
Simple, Complex, and Compound Sentences Exercises.pdfSimple, Complex, and Compound Sentences Exercises.pdf
Simple, Complex, and Compound Sentences Exercises.pdf
 
What is 3 Way Matching Process in Odoo 17.pptx
What is 3 Way Matching Process in Odoo 17.pptxWhat is 3 Way Matching Process in Odoo 17.pptx
What is 3 Way Matching Process in Odoo 17.pptx
 
VAMOS CUIDAR DO NOSSO PLANETA! .
VAMOS CUIDAR DO NOSSO PLANETA!                    .VAMOS CUIDAR DO NOSSO PLANETA!                    .
VAMOS CUIDAR DO NOSSO PLANETA! .
 
Including Mental Health Support in Project Delivery, 14 May.pdf
Including Mental Health Support in Project Delivery, 14 May.pdfIncluding Mental Health Support in Project Delivery, 14 May.pdf
Including Mental Health Support in Project Delivery, 14 May.pdf
 
MuleSoft Integration with AWS Textract | Calling AWS Textract API |AWS - Clou...
MuleSoft Integration with AWS Textract | Calling AWS Textract API |AWS - Clou...MuleSoft Integration with AWS Textract | Calling AWS Textract API |AWS - Clou...
MuleSoft Integration with AWS Textract | Calling AWS Textract API |AWS - Clou...
 
Model Attribute _rec_name in the Odoo 17
Model Attribute _rec_name in the Odoo 17Model Attribute _rec_name in the Odoo 17
Model Attribute _rec_name in the Odoo 17
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx
 

Chapter4__Method_Lim Lyheng_RULE (2).pdf

  • 1. JAVA Programming-I Lecturer: Mr. Lim Lyheng Tel/Telegram: +855 11 855297 @LimLyheng 1 ែចកចំេណះនិងបទពិេសធន៍
  • 3. Contents 1. Java Method Introduction 2. Types of Methods 1. Standard Library Methods 2. User-defined Methods 3. How to create a user-defined methods 4. Recursive Methods 5. Method Overloading 6. Method Overriding 7. Method Overloading Vs Overriding 8. Constructors 3 @LimLyheng ែចកចំេណះនិងបទពិេសធន៍
  • 4. 1.Introduction  In mathematics, you might have studied about functions. For example, f(x) = x2 is a function that returns squared value of x. If x = 2, then f(2) = 4 If x = 3, f(3) = 9 and so on.  Similarly, in programming, a function is a block of code that performs a specific task.  In Java, method is a jargon used for function.  Methods are bound to a class and they define the behavior of a class. 4 @LimLyheng ែចកចំេណះនិងបទពិេសធន៍
  • 5. 2.Type of Java Methods  Depending on whether a method is defined by the user, or available in standard library, there are two types of methods: 1. Standard Library Methods 2. User-defined Methods  What are the advantages of using methods?  The main advantage is code reusability.  You can write a method once, and use it multiple times.  You do not have to rewrite the entire code each time. Think of it as, "write once, reuse multiple times." 5 @LimLyheng ែចកចំេណះនិងបទពិេសធន៍
  • 6. 2.1 Standard Library Methods  The standard library methods are built-in methods in Java that are readily available for use.  These standard libraries come along with the Java Class Library (JCL) in a Java archive (*.jar) file with JVM( Java Virtual Machine and JRE (Java Runtime Environment).  For example, 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 @LimLyheng ែចកចំេណះនិងបទពិេសធន៍
  • 7. Example-1 standard library method sqrt() 7 @LimLyheng ែចកចំេណះនិងបទពិេសធន៍
  • 8. Example-2 standard library method Date() 8 @LimLyheng ែចកចំេណះនិងបទពិេសធន៍
  • 9. Example-3 standard library method Math.pow() 9 @LimLyheng ែចកចំេណះនិងបទពិេសធន៍
  • 10. 2.2 User-defined Methods  You can also define methods inside a class as per your wish. Such methods are called user-defined methods.  How to create a user-defined method?  Before you can use (call a method), you need to define it. Here is how you define methods in Java.  Here, a method named myMethod() is defined. public static void myMethod() { System.out.println(“My Function called”); } 10 @LimLyheng ែចកចំេណះនិងបទពិេសធន៍
  • 12. 3. How to create a user-defined method? Syntax for a method: The syntax shown above includes:  modifier − It defines the access type of the method and it is optional to use.  returnType − Method may return a value.  nameOfMethod − This is the method name. The method signature consists of the method name and the parameter list.  Parameter List − The list of parameters, it is the type, order, and number of parameters of a method. These are optional, method may contain zero parameters.  method body − The method body defines what the method does with the statements. modifier returnValueType methodName(list of parameters){ // Method body; } 12 @LimLyheng ែចកចំេណះនិងបទពិេសធន៍
  • 13. public static int max(int num1, int num2){ int result; if if (num1 > num2) result = num1; else result = num2; return result; } Example-Define a method int z = max(x, y); Invoke a method modifier return value type method name formal parameters parameter list return value method body actual parameters (arguments)  A parameter is a special kind of variable in computer programming language that is used to pass information between functions or procedures.  The actual information passed is called an argument. 13 @LimLyheng ែចកចំេណះនិងបទពិេសធន៍
  • 14. 3.1 Method Calling  For using a method, it should be called. There are two ways in which a method is called: 1. method returns a value 2. returning nothing (no return value).  The process of method calling is simple. When a program invokes a method, the program control gets transferred to the called method. This called method then returns control to the caller in two conditions, when 1. the return statement is executed. 2. it reaches the method ending closing brace. For example The method returning value can be understood by the following example: int result = sum(6, 9); System.out.println("This is return nothing!") 14 @LimLyheng ែចកចំេណះនិងបទពិេសធន៍
  • 15. Example: Method Calling Return Value 15 @LimLyheng ែចកចំេណះនិងបទពិេសធន៍
  • 16. 3.2. The void Keyword (method not return Value)  The void keyword allows us to create methods which do not return a value.  This method is a void method, which does not return any value.  Call to a void method must be a statement i.e. methodRankPoints(499.50);. It is a Java statement which ends with a semicolon as shown in the following example. 16 @LimLyheng ែចកចំេណះនិងបទពិេសធន៍
  • 17. Example: Void Method( not return value) 17 @LimLyheng ែចកចំេណះនិងបទពិេសធន៍
  • 18. 3.3 Passing data in Java (Passing Values to Method)  When it comes to Java programming, one of the trickiest questions is:  Does Java pass variables to methods by reference or by value?  This has been raising a lot of debates and making confusion for beginners.  However, the ultimate answer is crystal clear: Java always passes variables by value.  Or in other words: Java passes object references to methods by value.  Pass-by-value: A copy of the passed-in variable is copied into the argument of the method. Any changes to the argument do not affect the original one.  Pass-by-reference: The argument is an alias of the passed-in variable. Any changes to the argument will affect the original one. Note: There is only call by value in java, not call by reference 18 @LimLyheng ែចកចំេណះនិងបទពិេសធន៍
  • 19. Example-1: Java passes object references to methods by value: 19 @LimLyheng ែចកចំេណះនិងបទពិេសធន៍
  • 20. 3.4 Java Methods with Arguments and Return Value A Java method can have zero or more parameters. And, they may return a value. 20 @LimLyheng ែចកចំេណះនិងបទពិេសធន៍
  • 21. 3.5 Method Accepting Arguments and Returning Value 21 @LimLyheng ែចកចំេណះនិងបទពិេសធន៍
  • 22. 3.6 passing more than one argument to method by using commas 22 @LimLyheng ែចកចំេណះនិងបទពិេសធន៍
  • 23. Example: Get Squared Value Of Numbers from 1 to 5 23 @LimLyheng ែចកចំេណះនិងបទពិេសធន៍
  • 24. 4.Recursive Method  A method that calls itself is known as a recursive method.  And, this technique is known as recursion.  A physical world example would be to place two parallel mirrors facing each other.  Any object in between them would be reflected recursively. 24 @LimLyheng ែចកចំេណះនិងបទពិេសធន៍
  • 25. 4.1 How recursion works?  recurse() method is called from inside the main method at first (normal method call).  Also, recurse() method is called from inside the same method, recurse(). This is a recursive call. 25 @LimLyheng ែចកចំេណះនិងបទពិេសធន៍
  • 26. Example: Factorial of a Number Using Recursion 26 @LimLyheng ែចកចំេណះនិងបទពិេសធន៍
  • 27. 4.2 Advantages and Disadvantages of Recursion  When a recursive call is made, new storage location for variables are allocated on the stack.  As, each recursive call returns, the old variables and parameters are removed from the stack.  Hence, recursion generally use more memory and are generally slow.  On the other hand, recursive solution is much simpler and takes less time to write, debug and maintain. 27 @LimLyheng ែចកចំេណះនិងបទពិេសធន៍
  • 28. 5. Method Overloading  Method Overloading is a feature that allows a class to have more than one method having the same name, if their argument lists are different.  It is similar to constructor overloading in Java, that allows a class to have more than one constructor having different argument lists. void func() { ... } void func(int a) { ... } float func(double a) { ... } float func(int a, float b) { ... } 28 @LimLyheng ែចកចំេណះនិងបទពិេសធន៍
  • 29. 5.1 Ways to create Method Overloading In Java, two or more methods can have same name if they differ in parameters: 1. different number of parameters 2. different types of parameters, or both. 29 @LimLyheng ែចកចំេណះនិងបទពិេសធន៍
  • 30. Example-1 Overloading by changing number of arguments 30 @LimLyheng ែចកចំេណះនិងបទពិេសធន៍
  • 31. Example-2 By changing the datatype of parameters 31 @LimLyheng ែចកចំេណះនិងបទពិេសធន៍
  • 32. 5.2 Why method overloading?  Suppose, you have to perform addition of the given numbers but there can be any number of arguments (let’s say either 2 or 3 arguments for simplicity).  In order to accomplish the task, you can create two methods sum2num(int, int) and sum3num(int, int, int) for two and three parameters respectively.  However, other programmers as well as you in future may get confused as the behavior of both methods is same but they differ by name.  The better way to accomplish this task is by overloading methods. And, depending upon the argument passed, one of the overloaded methods is called. This helps to increase readability of the program 32 @LimLyheng ែចកចំេណះនិងបទពិេសធន៍
  • 35. 6. Method Overriding  If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in java.  In other words, If subclass provides the specific implementation of the method that has been provided by one of its parent class, it is known as method overriding. 35 @LimLyheng ែចកចំេណះនិងបទពិេសធន៍
  • 36. 6.1 Usage of Method Overriding  Method overriding is used to provide specific implementation of a method that is already provided by its super class.  Method overriding is used for runtime polymorphism 36 @LimLyheng ែចកចំេណះនិងបទពិេសធន៍
  • 37. 6.2 Rules for Java Method Overriding 1. method must have same name as in the parent class 2. method must have same parameter as in the parent class. 3. must be IS-A relationship (inheritance). 37 @LimLyheng ែចកចំេណះនិងបទពិេសធន៍
  • 38. Example of Java Method Overriding Consider a scenario, Bank is a class that provides functionality to get rate of interest. But, rate of interest varies according to banks. For example, SBI, ICICI and AXIS banks could provide 8%, 7% and 9% rate of interest. 38 @LimLyheng ែចកចំេណះនិងបទពិេសធន៍
  • 39. Example of Method Overriding 39 @LimLyheng ែចកចំេណះនិងបទពិេសធន៍
  • 40. 7. Method Overloading Vs Overriding 40 @LimLyheng ែចកចំេណះនិងបទពិេសធន៍
  • 41. 8. Constructors in Java  Constructor is a block of code that initializes the newly created object.  A constructor resembles an instance method in java but it’s not a method as it doesn’t have a return type.  Constructor has same name as the class and looks like this in a java code.  Note that the constructor name matches with the class name and it doesn’t have a return type. 41 @LimLyheng ែចកចំេណះនិងបទពិេសធន៍
  • 42. 8.1 How does a constructor work  Here we have created an object obj of class Hello and then we displayed the instance variable name of the object.  The output ‘‘BeginnersBook.com’’passed to the name during initialization in constructor.  This shows that when we created the object obj the constructor got invoked. this keyword refers to the current object, object obj in this example. 42 @LimLyheng ែចកចំេណះនិងបទពិេសធន៍
  • 43. 8.1 How does a constructor work  To understand the working of constructor, lets take an example.  lets say we have a class MyClass. When we create the object of MyClass like this: MyClass obj = new MyClass()  The new keyword here creates the object of class MyClass and invokes the constructor to initialize this newly created object. 43 @LimLyheng ែចកចំេណះនិងបទពិេសធន៍
  • 44. 8.2 Types of Constructor works There are three types of constructors:  Default,  No-arg constructor  Parameterized. 44 @LimLyheng ែចកចំេណះនិងបទពិេសធន៍
  • 45. 8.2.1 Default constructor  If you do not implement any constructor in your class, Java compiler inserts a default constructor into your code on your behalf.  This constructor is known as default constructor.  You would not find it in your source code(the java file) as it would be inserted into the code during compilation and exists in .class file.  This process is shown in the diagram below: 45 @LimLyheng ែចកចំេណះនិងបទពិេសធន៍
  • 46. 8.2.1 Default constructor ( Cont’d) If you implement any constructor then you no longer receive a default constructor from Java compiler. 46 @LimLyheng ែចកចំេណះនិងបទពិេសធន៍
  • 47. 8.2.2 no-argument constructor  Constructor with no arguments is known as no-arg constructor.  The signature is same as default constructor, however body can have any code unlike default constructor where the body of the constructor is empty.  Although you may see some people claim that that default and no-arg constructor is same but in fact they are not, even if you write public Demo() { } in your class Demo it cannot be called default constructor since you have written the code of it. 47 @LimLyheng ែចកចំេណះនិងបទពិេសធន៍
  • 49. 8.2.3 Parameterized constructor  Constructor with arguments(or you can say parameters) is known as Parameterized constructor.  Example: parameterized constructor  In this example we have a parameterized constructor with two parameters id and name. While creating the objects obj1 and obj2 I have passed two arguments so that this constructor gets invoked after creation of obj1 and obj2. 49 @LimLyheng ែចកចំេណះនិងបទពិេសធន៍
  • 51. Example2- Parameterized constructor  In this example, we have two constructors, a default constructor and a parameterized constructor.  When we do not pass any parameter while creating the object using new keyword then default constructor is invoked, however  when you pass a parameter then parameterized constructor that matches with the passed parameters list gets invoked. 51 @LimLyheng ែចកចំេណះនិងបទពិេសធន៍
  • 52. 8.3 Constructor Chaining When A constructor calls another constructor of same class then this is called constructor chaining. 52 @LimLyheng ែចកចំេណះនិងបទពិេសធន៍
  • 53. 8.3.1 Constructor Chaining: super() Whenever a child class constructor gets invoked it implicitly invokes the constructor of parent class. You can also say that the compiler inserts a super(); statement at the beginning of child class constructor. 53 @LimLyheng ែចកចំេណះនិងបទពិេសធន៍
  • 54. 8.4 Constructor Overloading Constructor overloading is a concept of having more than one constructor with different parameters list, in such a way so that each constructor performs a different task. 54 @LimLyheng ែចកចំេណះនិងបទពិេសធន៍
  • 58. Powerpoint Templates 58 Lecturer: Mr. Lim Lyheng Tel/Telegram: +855 11 855297 @LimLyheng ែចកចំេណះនិងបទពិេសធន៍
  • 59. Powerpoint Templates End of Chapter 4 59 @LimLyheng ែចកចំេណះនិងបទពិេសធន៍