SlideShare a Scribd company logo
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 (20)

PPTX
Basic concept of class, method , command line-argument
Suresh Mohta
 
PPTX
java Method Overloading
omkar bhagat
 
PDF
Methods in Java
Jussi Pohjolainen
 
PPTX
Advanced Python : Static and Class Methods
Bhanwar Singh Meena
 
PPTX
Std 12 computer chapter 8 classes and object in java (part 2)
Nuzhat Memon
 
PPT
Java ppt
Rohan Gajre
 
PPTX
Inheritance and Polymorphism in java simple and clear
ASHNA nadhm
 
PPTX
Types of methods in python
Aravindreddy Mokireddy
 
PPTX
Java Foundations: Strings and Text Processing
Svetlin Nakov
 
PPTX
05. Java Loops Methods and Classes
Intro C# Book
 
PPTX
Java Programs
vvpadhu
 
PPTX
02. Data Types and variables
Intro C# Book
 
PPTX
Java Foundations: Basic Syntax, Conditions, Loops
Svetlin Nakov
 
PPTX
Hemajava
SangeethaSasi1
 
PPT
Java căn bản - Chapter2
Vince Vo
 
PPTX
Interface in java
Kavitha713564
 
PPTX
Java Foundations: Objects and Classes
Svetlin Nakov
 
PPT
Chap08
Terry Yoast
 
PPTX
19. Data Structures and Algorithm Complexity
Intro C# Book
 
Basic concept of class, method , command line-argument
Suresh Mohta
 
java Method Overloading
omkar bhagat
 
Methods in Java
Jussi Pohjolainen
 
Advanced Python : Static and Class Methods
Bhanwar Singh Meena
 
Std 12 computer chapter 8 classes and object in java (part 2)
Nuzhat Memon
 
Java ppt
Rohan Gajre
 
Inheritance and Polymorphism in java simple and clear
ASHNA nadhm
 
Types of methods in python
Aravindreddy Mokireddy
 
Java Foundations: Strings and Text Processing
Svetlin Nakov
 
05. Java Loops Methods and Classes
Intro C# Book
 
Java Programs
vvpadhu
 
02. Data Types and variables
Intro C# Book
 
Java Foundations: Basic Syntax, Conditions, Loops
Svetlin Nakov
 
Hemajava
SangeethaSasi1
 
Java căn bản - Chapter2
Vince Vo
 
Interface in java
Kavitha713564
 
Java Foundations: Objects and Classes
Svetlin Nakov
 
Chap08
Terry Yoast
 
19. Data Structures and Algorithm Complexity
Intro C# Book
 

Similar to Computer programming 2 Lesson 15 (20)

DOCX
Methods in Java
Kavitha713564
 
PPTX
OOPSCA1.pptx
Soumyadipchanda2
 
PPT
Methods intro-1.0
BG Java EE Course
 
PPTX
Working with Methods in Java.pptx
maryansagsgao
 
PPTX
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
vekariyakashyap
 
PPTX
Functions & Methods in Java: A Beginner's Guide.pptx
Chris Lewis
 
PPTX
Java Method Presentation - Java Programming NC III.pptx
ArvieJayLapig
 
PDF
CIS 1403 lab 3 functions and methods in Java
Hamad Odhabi
 
PDF
Class and Object JAVA PROGRAMMING LANG .pdf
sameer2543ynr
 
PPT
Explain Classes and methods in java (ch04).ppt
ayaankim007
 
PPTX
Class and Object.pptx from nit patna ece department
om2348023vats
 
PDF
Week 7 Java Programming Methods For I.T students.pdf
JaypeeGPolancos
 
PPTX
CJP Unit-1 contd.pptx
RAJASEKHARV10
 
PPT
123 JAVA CLASSES, OBJECTS AND METHODS.ppt
mcjaya2024
 
PPTX
Methods in Java its a presentation that .pptx
anasraufmoh
 
DOCX
The Java Learning Kit Chapter 5 – Methods and Modular.docx
arnoldmeredith47041
 
PPTX
Chap2 class,objects contd
raksharao
 
PPT
Methods.ppt
ankurgupta857016
 
PPTX
JAVA METHODS PRESENTATION WITH EXAMPLES DFDFFD FDGFDGDFG FGGF
NagarathnaRajur2
 
Methods in Java
Kavitha713564
 
OOPSCA1.pptx
Soumyadipchanda2
 
Methods intro-1.0
BG Java EE Course
 
Working with Methods in Java.pptx
maryansagsgao
 
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
vekariyakashyap
 
Functions & Methods in Java: A Beginner's Guide.pptx
Chris Lewis
 
Java Method Presentation - Java Programming NC III.pptx
ArvieJayLapig
 
CIS 1403 lab 3 functions and methods in Java
Hamad Odhabi
 
Class and Object JAVA PROGRAMMING LANG .pdf
sameer2543ynr
 
Explain Classes and methods in java (ch04).ppt
ayaankim007
 
Class and Object.pptx from nit patna ece department
om2348023vats
 
Week 7 Java Programming Methods For I.T students.pdf
JaypeeGPolancos
 
CJP Unit-1 contd.pptx
RAJASEKHARV10
 
123 JAVA CLASSES, OBJECTS AND METHODS.ppt
mcjaya2024
 
Methods in Java its a presentation that .pptx
anasraufmoh
 
The Java Learning Kit Chapter 5 – Methods and Modular.docx
arnoldmeredith47041
 
Chap2 class,objects contd
raksharao
 
Methods.ppt
ankurgupta857016
 
JAVA METHODS PRESENTATION WITH EXAMPLES DFDFFD FDGFDGDFG FGGF
NagarathnaRajur2
 
Ad

More from MLG College of Learning, Inc (20)

PPTX
PC111.Lesson1
MLG College of Learning, Inc
 
PPTX
PC111-lesson1.pptx
MLG College of Learning, Inc
 
PPTX
PC LEESOON 6.pptx
MLG College of Learning, Inc
 
PPTX
PC 106 PPT-09.pptx
MLG College of Learning, Inc
 
PPTX
PC 106 PPT-07
MLG College of Learning, Inc
 
PPTX
PC 106 PPT-01
MLG College of Learning, Inc
 
PPTX
PC 106 Slide 04
MLG College of Learning, Inc
 
PPTX
PC 106 Slide no.02
MLG College of Learning, Inc
 
PPTX
pc-106-slide-3
MLG College of Learning, Inc
 
PPTX
PC 106 Slide 2
MLG College of Learning, Inc
 
PPTX
PC 106 Slide 1.pptx
MLG College of Learning, Inc
 
PDF
Db2 characteristics of db ms
MLG College of Learning, Inc
 
PDF
Db1 introduction
MLG College of Learning, Inc
 
Ad

Recently uploaded (20)

PDF
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
PPTX
Post Dated Cheque(PDC) Management in Odoo 18
Celine George
 
PDF
0725.WHITEPAPER-UNIQUEWAYSOFPROTOTYPINGANDUXNOW.pdf
Thomas GIRARD, MA, CDP
 
PDF
Horarios de distribución de agua en julio
pegazohn1978
 
PDF
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
PPTX
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
PPTX
MENINGITIS: NURSING MANAGEMENT, BACTERIAL MENINGITIS, VIRAL MENINGITIS.pptx
PRADEEP ABOTHU
 
PDF
The Different Types of Non-Experimental Research
Thelma Villaflores
 
PPTX
How to Create a PDF Report in Odoo 18 - Odoo Slides
Celine George
 
PPTX
PATIENT ASSIGNMENTS AND NURSING CARE RESPONSIBILITIES.pptx
PRADEEP ABOTHU
 
PDF
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
PPTX
PPT-Q1-WEEK-3-SCIENCE-ERevised Matatag Grade 3.pptx
reijhongidayawan02
 
PPT
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
PPTX
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
PDF
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
PDF
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
PPTX
HUMAN RESOURCE MANAGEMENT: RECRUITMENT, SELECTION, PLACEMENT, DEPLOYMENT, TRA...
PRADEEP ABOTHU
 
PPTX
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
PDF
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
PPTX
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
Post Dated Cheque(PDC) Management in Odoo 18
Celine George
 
0725.WHITEPAPER-UNIQUEWAYSOFPROTOTYPINGANDUXNOW.pdf
Thomas GIRARD, MA, CDP
 
Horarios de distribución de agua en julio
pegazohn1978
 
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
MENINGITIS: NURSING MANAGEMENT, BACTERIAL MENINGITIS, VIRAL MENINGITIS.pptx
PRADEEP ABOTHU
 
The Different Types of Non-Experimental Research
Thelma Villaflores
 
How to Create a PDF Report in Odoo 18 - Odoo Slides
Celine George
 
PATIENT ASSIGNMENTS AND NURSING CARE RESPONSIBILITIES.pptx
PRADEEP ABOTHU
 
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
PPT-Q1-WEEK-3-SCIENCE-ERevised Matatag Grade 3.pptx
reijhongidayawan02
 
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
HUMAN RESOURCE MANAGEMENT: RECRUITMENT, SELECTION, PLACEMENT, DEPLOYMENT, TRA...
PRADEEP ABOTHU
 
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 

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.