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

PPTX
Java method
PPTX
Classes, Objects and Method - Object Oriented Programming with Java
PPTX
11. java methods
PPTX
Java Method, Static Block
PPTX
Main method in java
PPTX
Java method present by showrov ahamed
PPTX
Method of java
PPTX
Java Foundations: Methods
Java method
Classes, Objects and Method - Object Oriented Programming with Java
11. java methods
Java Method, Static Block
Main method in java
Java method present by showrov ahamed
Method of java
Java Foundations: Methods

What's hot (20)

PPTX
Basic concept of class, method , command line-argument
PPTX
java Method Overloading
PDF
Methods in Java
PPTX
Advanced Python : Static and Class Methods
PPTX
Std 12 computer chapter 8 classes and object in java (part 2)
PPT
Java ppt
PPTX
Inheritance and Polymorphism in java simple and clear
PPTX
Types of methods in python
PPTX
Java Foundations: Strings and Text Processing
PPTX
05. Java Loops Methods and Classes
PPTX
Java Programs
PPTX
02. Data Types and variables
PPTX
Java Foundations: Basic Syntax, Conditions, Loops
PPTX
Hemajava
PPT
Java căn bản - Chapter2
PPTX
Interface in java
PPTX
Java Foundations: Objects and Classes
PPT
Chap08
PPTX
19. Data Structures and Algorithm Complexity
Basic concept of class, method , command line-argument
java Method Overloading
Methods in Java
Advanced Python : Static and Class Methods
Std 12 computer chapter 8 classes and object in java (part 2)
Java ppt
Inheritance and Polymorphism in java simple and clear
Types of methods in python
Java Foundations: Strings and Text Processing
05. Java Loops Methods and Classes
Java Programs
02. Data Types and variables
Java Foundations: Basic Syntax, Conditions, Loops
Hemajava
Java căn bản - Chapter2
Interface in java
Java Foundations: Objects and Classes
Chap08
19. Data Structures and Algorithm Complexity
Ad

Similar to Computer programming 2 Lesson 15 (20)

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

More from MLG College of Learning, Inc (20)

PPTX
PPTX
PC111-lesson1.pptx
PPTX
PC LEESOON 6.pptx
PPTX
PC 106 PPT-09.pptx
PPTX
PPTX
PPTX
PPTX
PC 106 Slide no.02
PPTX
PPTX
PPTX
PC 106 Slide 1.pptx
PDF
Db2 characteristics of db ms
PDF

Recently uploaded (20)

PDF
Anesthesia in Laparoscopic Surgery in India
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PPTX
master seminar digital applications in india
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
TR - Agricultural Crops Production NC III.pdf
PDF
Complications of Minimal Access Surgery at WLH
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PDF
Sports Quiz easy sports quiz sports quiz
PPTX
Cell Types and Its function , kingdom of life
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PPTX
Pharma ospi slides which help in ospi learning
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PPTX
GDM (1) (1).pptx small presentation for students
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PPTX
Cell Structure & Organelles in detailed.
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Anesthesia in Laparoscopic Surgery in India
2.FourierTransform-ShortQuestionswithAnswers.pdf
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
Microbial diseases, their pathogenesis and prophylaxis
master seminar digital applications in india
STATICS OF THE RIGID BODIES Hibbelers.pdf
TR - Agricultural Crops Production NC III.pdf
Complications of Minimal Access Surgery at WLH
FourierSeries-QuestionsWithAnswers(Part-A).pdf
Sports Quiz easy sports quiz sports quiz
Cell Types and Its function , kingdom of life
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Microbial disease of the cardiovascular and lymphatic systems
O5-L3 Freight Transport Ops (International) V1.pdf
Pharma ospi slides which help in ospi learning
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
GDM (1) (1).pptx small presentation for students
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
Cell Structure & Organelles in detailed.
Chapter 2 Heredity, Prenatal Development, and Birth.pdf

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.