SlideShare a Scribd company logo
1 of 14
Computer
Programming 2
Lesson 15 – Java – Methods
Prepared by: Analyn G. Regaton
What is a
method?
In mathematics, we might have studied about functions.
For example, f(x) = x2 is a function that returns a squared
value of x.
If x = 2, then f(2) = 4
If x = 3, f(3) = 9
and so on.
Similarly, in computer programming, a function is a block
of code that performs a specific task.
In object-oriented programming, the method is a jargon
used for function. Methods are bound to a class and they
define the behavior of a class.
Types of Java
methods
Standard Library
Methods
User-defined Methods
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 and JRE.
For example,
 print() is a method of java.io.PrintSteam.
The print("...") method prints the string inside
quotation marks.
 sqrt() is a method of Math class. It returns the square
root of a number.
Here's a working example:
public class Main {
public static void main(String[] args) {
// using the sqrt() method
System.out.print("Square root of 4 is: " + Math.sqrt(4));
}
}
Output:
Square root of 4 is: 2.0
Types of Java
methods
Standard Library
Methods
User-defined Methods
User-defined Method
We can also create methods of our own choice to perform some task.
Such methods are called user-defined methods.
How to create a user-defined method?
Here is how we can create a method in Java:
public static void myMethod() {
System.out.println("My Function called");
}
Here, we have created a method named myMethod(). We can see that we
have used the public, static and void before the method name.
 public - access modifier. It means the method can be accessed from
anywhere. static - It means that the method can be accessed without
any objects.
 void - It means that the method does not return any value. We will
learn more about this later in this tutorial.
This is a simple example of how we can create a method. However, the
complete syntax of a method definition in Java is:
modifier static returnType nameOfMethod (parameters) {
// method body
}
Definition of
Terms
Modifier
Public
Private
Static keyword
For example, the sqrt() method of standard Math class is
static. Hence, we can directly call Math.sqrt() without
creating an instance of Math class.
returnType Type of value
returns
 If the method does not return a value, its return
type is void.
A method can return native data types (int, float, double, etc), native objects
(String, Map, List, etc), or any other built-in and user-defined objects.
Definition of
Terms
nameOf
Method
identifier
Particular method
Static keyword
For example
calculateArea(), display(), and so on
parameters(
arguments)
Values passed to a
method
Method
body
Statements
enclosed { }
Figure 1
How to call
java method?
Here's how
myMethod();
This statement calls myMethod() method that was declared earlier.
Working of the method call in Java
•While executing the program code, it encounters myFunction(); in the code.
•The execution then branches to the myFunction() method and executes code inside the
body of the method.
•After the execution of the method body, the program returns to the original state and
executes the next statement after the method call.
Example
program
Let's see how we can use methods in a Java program.
class Main {
public static void main(String[] args) {
System.out.println("About to encounter a method.");
// method call
myMethod();
System.out.println("Method was executed successfully!");
}
// method definition
private static void myMethod(){
System.out.println("Printing from inside myMethod()!");
}
}
Output:
About to encounter a method.
Printing from inside myMethod().
Method was executed successfully!
Another
example
class Main {
public static void main(String[] args) {
// create object of the Output class
Output obj = new Output();
System.out.println("About to encounter a method.");
// calling myMethod() of Output class
obj.myMethod();
System.out.println("Method was executed successfully!");
}
}
class Output {
// public: this method can be called from outside the class
public void myMethod() {
System.out.println("Printing from inside myMethod().");
}
}
Output:
About to encounter a method.
Printing from inside myMethod().
Method was executed successfully!
Since the method is not static, it is called using the object obj of the class.
obj.myMethod();
Method
Arguments
and Return
Value
Let's take an example of a method returning a
value.
class SquareMain {
public static void main(String[] args) {
int result;
// call the method and store returned value
result = square();
System.out.println("Squared value of 10 is: " +
result);
}
public static int square() {
// return statement
return 10 * 10;
}
}
Output:
Squared value of 10 is: 100
Example:
Method
Accepting
Arguments
and Returning
Value
public class Main {
public static void main(String[] args) {
int result, n;
n = 3;
result = square(n);
System.out.println("Square of 3 is: " +
result);
n = 4;
result = square(n);
System.out.println("Square of 4 is: " +
result);
}
// method
static int square(int i) {
return i * i;
}
}
Output:
Squared value of 3 is: 9
Squared value of 4 is: 16
We can also
pass more
than one
argument to
the Java
method by
using
commas.
For example,
public class Main {
// method definition
public static int getIntegerSum (int i, int j) {
return i + j;
}
// method definition
public static int multiplyInteger (int x, int y) {
return x * y;
}
public static void main(String[] args) {
// calling methods
System.out.println("10 + 20 = " + getIntegerSum(10, 20));
System.out.println("20 x 40 = " + multiplyInteger(20, 40));
}
}
Output:
10 + 20 = 30
20 x 40 = 800
What are the
advantages of
using
methods?
1. The main advantage is code reusability.
public class Main {
// method defined
private static int getSquare(int x){
return x * x;
}
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
// method call
int result = getSquare(i);
System.out.println("Square of " + i + " is: " + result);
}
}
}
Output:
Square of 1 is: 1
Square of 2 is: 4
Square of 3 is: 9
Square of 4 is: 16
Square of 5 is: 25
2. Methods make code more readable and easier to debug.

More Related Content

What's hot

Basic concept of class, method , command line-argument
Basic concept of class, method , command line-argumentBasic concept of class, method , command line-argument
Basic concept of class, method , command line-argumentSuresh Mohta
 
java Method Overloading
java Method Overloadingjava Method Overloading
java Method Overloadingomkar bhagat
 
Advanced Python : Static and Class Methods
Advanced Python : Static and Class Methods Advanced Python : Static and Class Methods
Advanced Python : Static and Class Methods Bhanwar Singh Meena
 
Std 12 computer chapter 8 classes and object in java (part 2)
Std 12 computer chapter 8 classes and object in java (part 2)Std 12 computer chapter 8 classes and object in java (part 2)
Std 12 computer chapter 8 classes and object in java (part 2)Nuzhat Memon
 
Inheritance and Polymorphism in java simple and clear
Inheritance and Polymorphism in java simple and clear Inheritance and Polymorphism in java simple and clear
Inheritance and Polymorphism in java simple and clear ASHNA nadhm
 
Java Foundations: Strings and Text Processing
Java Foundations: Strings and Text ProcessingJava Foundations: Strings and Text Processing
Java Foundations: Strings and Text ProcessingSvetlin Nakov
 
05. Java Loops Methods and Classes
05. Java Loops Methods and Classes05. Java Loops Methods and Classes
05. Java Loops Methods and ClassesIntro C# Book
 
Java Programs
Java ProgramsJava Programs
Java Programsvvpadhu
 
02. Data Types and variables
02. Data Types and variables02. Data Types and variables
02. Data Types and variablesIntro C# Book
 
Java Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, LoopsJava Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, LoopsSvetlin Nakov
 
Java căn bản - Chapter2
Java căn bản - Chapter2Java căn bản - Chapter2
Java căn bản - Chapter2Vince Vo
 
Java Foundations: Objects and Classes
Java Foundations: Objects and ClassesJava Foundations: Objects and Classes
Java Foundations: Objects and ClassesSvetlin Nakov
 
19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm Complexity19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm ComplexityIntro C# Book
 

What's hot (20)

Basic concept of class, method , command line-argument
Basic concept of class, method , command line-argumentBasic concept of class, method , command line-argument
Basic concept of class, method , command line-argument
 
java Method Overloading
java Method Overloadingjava Method Overloading
java Method Overloading
 
Methods in Java
Methods in JavaMethods in Java
Methods in Java
 
Advanced Python : Static and Class Methods
Advanced Python : Static and Class Methods Advanced Python : Static and Class Methods
Advanced Python : Static and Class Methods
 
Std 12 computer chapter 8 classes and object in java (part 2)
Std 12 computer chapter 8 classes and object in java (part 2)Std 12 computer chapter 8 classes and object in java (part 2)
Std 12 computer chapter 8 classes and object in java (part 2)
 
Java ppt
Java pptJava ppt
Java ppt
 
Inheritance and Polymorphism in java simple and clear
Inheritance and Polymorphism in java simple and clear Inheritance and Polymorphism in java simple and clear
Inheritance and Polymorphism in java simple and clear
 
Types of methods in python
Types of methods in pythonTypes of methods in python
Types of methods in python
 
Java Foundations: Strings and Text Processing
Java Foundations: Strings and Text ProcessingJava Foundations: Strings and Text Processing
Java Foundations: Strings and Text Processing
 
05. Java Loops Methods and Classes
05. Java Loops Methods and Classes05. Java Loops Methods and Classes
05. Java Loops Methods and Classes
 
Java Programs
Java ProgramsJava Programs
Java Programs
 
02. Data Types and variables
02. Data Types and variables02. Data Types and variables
02. Data Types and variables
 
Overloadingmethod
OverloadingmethodOverloadingmethod
Overloadingmethod
 
Java Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, LoopsJava Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, Loops
 
Hemajava
HemajavaHemajava
Hemajava
 
Java căn bản - Chapter2
Java căn bản - Chapter2Java căn bản - Chapter2
Java căn bản - Chapter2
 
Interface in java
Interface in javaInterface in java
Interface in java
 
Java Foundations: Objects and Classes
Java Foundations: Objects and ClassesJava Foundations: Objects and Classes
Java Foundations: Objects and Classes
 
Chap08
Chap08Chap08
Chap08
 
19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm Complexity19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm Complexity
 

Similar to Computer programming 2 Lesson 15

EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...vekariyakashyap
 
CJP Unit-1 contd.pptx
CJP Unit-1 contd.pptxCJP Unit-1 contd.pptx
CJP Unit-1 contd.pptxRAJASEKHARV10
 
Working with Methods in Java.pptx
Working with Methods in Java.pptxWorking with Methods in Java.pptx
Working with Methods in Java.pptxmaryansagsgao
 
Object Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsObject Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsMuhammadTalha436
 
9781439035665 ppt ch08
9781439035665 ppt ch089781439035665 ppt ch08
9781439035665 ppt ch08Terry Yoast
 
Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIEduardo Bergavera
 
Java căn bản - Chapter7
Java căn bản - Chapter7Java căn bản - Chapter7
Java căn bản - Chapter7Vince Vo
 
Lecture 4_Java Method-constructor_imp_keywords
Lecture   4_Java Method-constructor_imp_keywordsLecture   4_Java Method-constructor_imp_keywords
Lecture 4_Java Method-constructor_imp_keywordsmanish kumar
 
Chap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptxChap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptxchetanpatilcp783
 
Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0BG Java EE Course
 
Introduction of Object Oriented Programming Language using Java. .pptx
Introduction of Object Oriented Programming Language using Java. .pptxIntroduction of Object Oriented Programming Language using Java. .pptx
Introduction of Object Oriented Programming Language using Java. .pptxPoonam60376
 
21UCAC31 Java Programming.pdf(MTNC)(BCA)
21UCAC31 Java Programming.pdf(MTNC)(BCA)21UCAC31 Java Programming.pdf(MTNC)(BCA)
21UCAC31 Java Programming.pdf(MTNC)(BCA)ssuser7f90ae
 
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sirAdvanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sirAVINASH KUMAR
 

Similar to Computer programming 2 Lesson 15 (20)

EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
 
Inheritance
InheritanceInheritance
Inheritance
 
Methods in Java
Methods in JavaMethods in Java
Methods in Java
 
CJP Unit-1 contd.pptx
CJP Unit-1 contd.pptxCJP Unit-1 contd.pptx
CJP Unit-1 contd.pptx
 
Working with Methods in Java.pptx
Working with Methods in Java.pptxWorking with Methods in Java.pptx
Working with Methods in Java.pptx
 
Object oriented concepts
Object oriented conceptsObject oriented concepts
Object oriented concepts
 
Object Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsObject Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ Exams
 
9781439035665 ppt ch08
9781439035665 ppt ch089781439035665 ppt ch08
9781439035665 ppt ch08
 
Core & Advance Java Training For Beginner-PSK Technologies Pvt. Ltd. Nagpur
Core & Advance Java Training For Beginner-PSK Technologies Pvt. Ltd. NagpurCore & Advance Java Training For Beginner-PSK Technologies Pvt. Ltd. Nagpur
Core & Advance Java Training For Beginner-PSK Technologies Pvt. Ltd. Nagpur
 
Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part II
 
Java căn bản - Chapter7
Java căn bản - Chapter7Java căn bản - Chapter7
Java căn bản - Chapter7
 
Lecture 4_Java Method-constructor_imp_keywords
Lecture   4_Java Method-constructor_imp_keywordsLecture   4_Java Method-constructor_imp_keywords
Lecture 4_Java Method-constructor_imp_keywords
 
Chap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptxChap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptx
 
Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0
 
Oop
OopOop
Oop
 
Introduction of Object Oriented Programming Language using Java. .pptx
Introduction of Object Oriented Programming Language using Java. .pptxIntroduction of Object Oriented Programming Language using Java. .pptx
Introduction of Object Oriented Programming Language using Java. .pptx
 
Polymorphism.pptx
Polymorphism.pptxPolymorphism.pptx
Polymorphism.pptx
 
21UCAC31 Java Programming.pdf(MTNC)(BCA)
21UCAC31 Java Programming.pdf(MTNC)(BCA)21UCAC31 Java Programming.pdf(MTNC)(BCA)
21UCAC31 Java Programming.pdf(MTNC)(BCA)
 
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sirAdvanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
 
OOPs & Inheritance Notes
OOPs & Inheritance NotesOOPs & Inheritance Notes
OOPs & Inheritance Notes
 

More from MLG College of Learning, Inc (20)

PC111.Lesson2
PC111.Lesson2PC111.Lesson2
PC111.Lesson2
 
PC111.Lesson1
PC111.Lesson1PC111.Lesson1
PC111.Lesson1
 
PC111-lesson1.pptx
PC111-lesson1.pptxPC111-lesson1.pptx
PC111-lesson1.pptx
 
PC LEESOON 6.pptx
PC LEESOON 6.pptxPC LEESOON 6.pptx
PC LEESOON 6.pptx
 
PC 106 PPT-09.pptx
PC 106 PPT-09.pptxPC 106 PPT-09.pptx
PC 106 PPT-09.pptx
 
PC 106 PPT-07
PC 106 PPT-07PC 106 PPT-07
PC 106 PPT-07
 
PC 106 PPT-01
PC 106 PPT-01PC 106 PPT-01
PC 106 PPT-01
 
PC 106 PPT-06
PC 106 PPT-06PC 106 PPT-06
PC 106 PPT-06
 
PC 106 PPT-05
PC 106 PPT-05PC 106 PPT-05
PC 106 PPT-05
 
PC 106 Slide 04
PC 106 Slide 04PC 106 Slide 04
PC 106 Slide 04
 
PC 106 Slide no.02
PC 106 Slide no.02PC 106 Slide no.02
PC 106 Slide no.02
 
pc-106-slide-3
pc-106-slide-3pc-106-slide-3
pc-106-slide-3
 
PC 106 Slide 2
PC 106 Slide 2PC 106 Slide 2
PC 106 Slide 2
 
PC 106 Slide 1.pptx
PC 106 Slide 1.pptxPC 106 Slide 1.pptx
PC 106 Slide 1.pptx
 
Db2 characteristics of db ms
Db2 characteristics of db msDb2 characteristics of db ms
Db2 characteristics of db ms
 
Db1 introduction
Db1 introductionDb1 introduction
Db1 introduction
 
Lesson 3.2
Lesson 3.2Lesson 3.2
Lesson 3.2
 
Lesson 3.1
Lesson 3.1Lesson 3.1
Lesson 3.1
 
Lesson 1.6
Lesson 1.6Lesson 1.6
Lesson 1.6
 
Lesson 3.2
Lesson 3.2Lesson 3.2
Lesson 3.2
 

Recently uploaded

Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docxPoojaSen20
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 

Recently uploaded (20)

Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docx
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 

Computer programming 2 Lesson 15

  • 1. Computer Programming 2 Lesson 15 – Java – Methods Prepared by: Analyn G. Regaton
  • 2. What is a method? In mathematics, we might have studied about functions. For example, f(x) = x2 is a function that returns a squared value of x. If x = 2, then f(2) = 4 If x = 3, f(3) = 9 and so on. Similarly, in computer programming, a function is a block of code that performs a specific task. In object-oriented programming, the method is a jargon used for function. Methods are bound to a class and they define the behavior of a class.
  • 3. Types of Java methods Standard Library Methods User-defined Methods 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 and JRE. For example,  print() is a method of java.io.PrintSteam. The print("...") method prints the string inside quotation marks.  sqrt() is a method of Math class. It returns the square root of a number. Here's a working example: public class Main { public static void main(String[] args) { // using the sqrt() method System.out.print("Square root of 4 is: " + Math.sqrt(4)); } } Output: Square root of 4 is: 2.0
  • 4. Types of Java methods Standard Library Methods User-defined Methods User-defined Method We can also create methods of our own choice to perform some task. Such methods are called user-defined methods. How to create a user-defined method? Here is how we can create a method in Java: public static void myMethod() { System.out.println("My Function called"); } Here, we have created a method named myMethod(). We can see that we have used the public, static and void before the method name.  public - access modifier. It means the method can be accessed from anywhere. static - It means that the method can be accessed without any objects.  void - It means that the method does not return any value. We will learn more about this later in this tutorial. This is a simple example of how we can create a method. However, the complete syntax of a method definition in Java is: modifier static returnType nameOfMethod (parameters) { // method body }
  • 5. Definition of Terms Modifier Public Private Static keyword For example, the sqrt() method of standard Math class is static. Hence, we can directly call Math.sqrt() without creating an instance of Math class. returnType Type of value returns  If the method does not return a value, its return type is void. A method can return native data types (int, float, double, etc), native objects (String, Map, List, etc), or any other built-in and user-defined objects.
  • 6. Definition of Terms nameOf Method identifier Particular method Static keyword For example calculateArea(), display(), and so on parameters( arguments) Values passed to a method Method body Statements enclosed { }
  • 8. How to call java method? Here's how myMethod(); This statement calls myMethod() method that was declared earlier. Working of the method call in Java •While executing the program code, it encounters myFunction(); in the code. •The execution then branches to the myFunction() method and executes code inside the body of the method. •After the execution of the method body, the program returns to the original state and executes the next statement after the method call.
  • 9. Example program Let's see how we can use methods in a Java program. class Main { public static void main(String[] args) { System.out.println("About to encounter a method."); // method call myMethod(); System.out.println("Method was executed successfully!"); } // method definition private static void myMethod(){ System.out.println("Printing from inside myMethod()!"); } } Output: About to encounter a method. Printing from inside myMethod(). Method was executed successfully!
  • 10. Another example class Main { public static void main(String[] args) { // create object of the Output class Output obj = new Output(); System.out.println("About to encounter a method."); // calling myMethod() of Output class obj.myMethod(); System.out.println("Method was executed successfully!"); } } class Output { // public: this method can be called from outside the class public void myMethod() { System.out.println("Printing from inside myMethod()."); } } Output: About to encounter a method. Printing from inside myMethod(). Method was executed successfully! Since the method is not static, it is called using the object obj of the class. obj.myMethod();
  • 11. Method Arguments and Return Value Let's take an example of a method returning a value. class SquareMain { public static void main(String[] args) { int result; // call the method and store returned value result = square(); System.out.println("Squared value of 10 is: " + result); } public static int square() { // return statement return 10 * 10; } } Output: Squared value of 10 is: 100
  • 12. Example: Method Accepting Arguments and Returning Value public class Main { public static void main(String[] args) { int result, n; n = 3; result = square(n); System.out.println("Square of 3 is: " + result); n = 4; result = square(n); System.out.println("Square of 4 is: " + result); } // method static int square(int i) { return i * i; } } Output: Squared value of 3 is: 9 Squared value of 4 is: 16
  • 13. We can also pass more than one argument to the Java method by using commas. For example, public class Main { // method definition public static int getIntegerSum (int i, int j) { return i + j; } // method definition public static int multiplyInteger (int x, int y) { return x * y; } public static void main(String[] args) { // calling methods System.out.println("10 + 20 = " + getIntegerSum(10, 20)); System.out.println("20 x 40 = " + multiplyInteger(20, 40)); } } Output: 10 + 20 = 30 20 x 40 = 800
  • 14. What are the advantages of using methods? 1. The main advantage is code reusability. public class Main { // method defined private static int getSquare(int x){ return x * x; } public static void main(String[] args) { for (int i = 1; i <= 5; i++) { // method call int result = getSquare(i); System.out.println("Square of " + i + " is: " + result); } } } Output: Square of 1 is: 1 Square of 2 is: 4 Square of 3 is: 9 Square of 4 is: 16 Square of 5 is: 25 2. Methods make code more readable and easier to debug.