0% found this document useful (0 votes)
15 views

Method

Uploaded by

Hasanul Mahi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Method

Uploaded by

Hasanul Mahi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 21

Method

Introduction to Methods

➢ Reusable blocks of code


➢ Perform specific tasks
➢ Can be called from any part of the code
➢ Consists of input parameters and return values
➢ Enhances code reusability, modularity, and maintainability
➢ Also known as function in some other languages

2
Types of Methods
1. Pre-defined/ built-in method:
These methods are already defined in java libraries
e.g: .length(), .equals(), .compareTo(), .toLowerCase() etc.
2. User-defined method:
These are the methods written by the programmer.

In this lesson, we will learn how to write user-defined methods.

3
User-Defined Methods
There are mainly 2 parts of using a user-defined method:
1. Method declaration
2. Method calling
Method Declaration can be further broken down into more parts.

4
Static Method

● A static method belongs to the class and not to the instance of a class.
● As it belongs to the class, it can be called without creating any object.
● We use the keyword “static” to define a method as static.
● We can call a static method from inside any other static method.

5
Method Declaration

➢ A method in java is written outside the main() method but inside the class.
➢ The following convention is followed when declaring a method:

access_modifier static return_type method_name (parameter_type parameter_name) {


method body;
return return_value;
}

6
Method Declaration Cont.
Declaring a method that adds two numbers received as parameters.

Access modifier Method name


Return type Method Parameters

public static int add ( int a, int b){

int sum = a+b; Method Body

return sum; Return Value

7
Method Body
● Any set of code lines written inside the method.
● Any variable declared inside the scope of a method is not accessible from
outside including the parameter variables.
● No line is executed after the “return” statement.

8
Return Type

● To declare a method we need to define what type of variable the method is


returning.
● If we do not explicitly return any data or variable from the method it returns
Null and that is declared as “void” in the method declaration.

9
1 void return 2 int return 3 boolean return
static void print_sum( int a, int b) { static int sum( int a, int b) { static boolean check( int a) {

int sum = a+b; int sum = a+b; if(a>10){

System.out.println(sum); return sum; return true;


} //this method does not return any } //this method returns an integer type
}
value. value.
else{

4 String return 5 double return return false;

static String okay(int a, String str1) { static double point(int a) { }

return (a+2)+str1; double db = a/10.0; } //this method returns a boolean type


value.
} //this method returns a String type return db;
value.
} //this method returns a double type
variable.

10
Method Call

● To run a method we MUST call the method.


● Method call is done inside the main() method.
● The number of arguments passed must be equal to parameters received.
● The sequence of the parameters passed is important.
● The type of the arguments passed must be same as type of parameters
being received.
● After method call, a value is returned to the line of method call.

11
Method Call Cont.
Calling the previously written add method.

public static void main(String [] args){


Receiving the
value of sum int answer = add(4,5); Passing the same
type of arguments as
System.out.println(answer); declared (int)

Welcome to DrJava. Working directory is E:\Java

> run function1

>
12
Method Arguments & Parameters
The sequence of the arguments passed corresponds to the variables receiving
the parameters.

Method to subtract two numbers Calling subtract Output

static void subtract( int a, int b) { subtract(2, 3); Welcome to DrJava. Working directory is E:\
Java

int diff = a-b; subtract(3,2); > run function1

System.out.println(diff); -1

} //this method does not return any 1

value. >

Here in case 1: subtract(2,3), the values 2 and 3 will be received as int a = 2 and int b = 3. Therefore, the difference is (2-3) = -1.

In case 2: int a = 3 and int b = 2 and so difference is (3-2) = 1.


Method Signature
● A method is identified based on its name, parameter list it receives and return
type.
● Multiple methods can have same name but different sets of parameters.
● Multiple methods can have same name and same set of parameters but have
different return types.
● The number of parameters passed in method call must be equal to the
number of parameters received during method declaration.

14
Method Example 1
Writing a method that prints “Hello!”

public class func1{


public static void sayHello(){
Output

System.out.println(“Hello!”); Void return type Welcome to DrJava. Working directory is E:\


as no value is Java
}
being returned
public static void main(String []args){ from inside > run func1

sayHello(); Hello!
No arguments
} >
and no
} parameters
received

15
Method Example 2
Writing a method that checks if a number divisible by three or not.
public class func1{
public static String divThree(int num){
if(num%3==0){
Output
return “Divisible by 3”;
} Welcome to DrJava. Working directory is E:\
Java
else{
> run func1
return “Not divisible by 3”;
Not divisible by 3
} 13 will be received
This value will be >
by num. And num
} returned to the line of
= 13 will be
method call
public static void main(String []args){ accessible inside
the function.
String answer = divThree(13);
System.out.println(answer);
This line will invoke a
}
method call.
}
16
Method Example 3
Writing a method that prints the largest number out of two numbers.
public class func1{
public static void findLargest(int num1, int num2){
if(num1>num2){ Output
System.out.println(num1);
Welcome to DrJava. Working directory is E:\
} Java

else{ > run func1

System.out.println(num2); 13
} >
}
public static void main(String []args){
findLargest(13, -10);
num1 = 13 num2 = -10
void return
}
since no return
}
statement.

17
To do
Write a method named evenPositive to find even and positive
numbers from an array of numbers.

18
Calling a Method from another Method
● We can call a method from inside another public class Methods {
public static void main(String[] args) {
method. method1();
1. method1() called from the main() method. }
static void method1(){
2. method2() called from method1(). System.out.print("CSE");
method2();
}
static void method2(){
System.out.print("110");
}
}

Welcome to DrJava. Working directory is C:\Users\


Desktop
CSE110

19
To Do public class MethodCalling {
public static void main(String[] args) {
show_triangle(4);
Now, can you print a triangular palindrome like the System.out.println();
show_triangle(5);
following using a method called show_triangle()?
}
Note that you have to take the help of static void show_spaces(int a){
show_spaces() and show_palindrome() method. for (int i = 0; i<a; i++){
System.out.print(" ");
1 }
121 }
12321 static void show_palindrome(int b) {
1234321 for (int i = 1; i <= b; i++) {
123454321 System.out.print(i);
}
● show_spaces() method prints a number of for (int i = b - 1; i >= 1; i—-)
{
spaces passed to its parameter System.out.print(i);
● show_palindrome() prints a palindrome. }
}
These methods are already done for you. static void show_triangle(int a){
//To Do
}
} 20
Practice Problem
● Write a Java method to find the smallest number among three numbers.
● Write a Java method to count all vowels in a string.
● Write a Java method to count all the words in a string.
● Write a Java method that accepts three integers and checks whether they are consecutive or
not. Returns true or false.
● Write a Java method for extracting the first digit from a positive or negative integer.
● [Hard] A nonnegative integer is called a palindrome if it reads forward and backward in the
same way. For example, the numbers 5, 121, 3443, and 123454321 are palindromes. Write
a method that takes as input a nonnegative integer and returns true if the number is a
palindrome; otherwise, it returns false. Also write a program to test your method.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy