Chapter 5 Methods
Chapter 5 Methods
Methods
Table of Contents
1. What Is a Method?
2. Naming and Best Practices
3. Declaring and Invoking Methods
▪ Void and Return Type Methods
4. Methods with Parameters
5. Value vs. Reference Types
6. Overloading Methods
7. Program Execution Flow 7
What Is a Method
Table of Contents
A method in Java is a set of instructions that can be called for
execution using the method name. A Java method can take in
data or parameters and return a value - both parameters
and return values are optional.
7
Create
Table ofa Contents
Method
A method must be declared within a class. It is defined with the name of the
method, followed by parentheses ().
Java provides some pre-defined methods, such as System.out.println(),
but you can also create your own methods to perform certain actions:
7
Simple Methods
▪ Named block of code, that can be invoked later
▪ Sample method definition: Method named
printHello
public static void printHello () {
System.out.println("Hello!"); Method body
} always
surrounded
by { }
▪ Invoking (calling) the printHello();
method several times: printHello();
9
Why Use Methods?
▪ More manageable programming
▪ Splits large complex problems into small pieces
▪ Better organization of the program by breaking down into modules
▪ Improves code readability, reusability and maintainability
▪ Improves code understandability thus enhance collaboration with
other team members
▪ Avoiding repeating code
▪ Improves code maintainability
▪ Code reusability
▪ Using existing methods several times 10
Case study : Water billing system
Functional Requirements of the System
a) Method for Handling Database Connection
A method to establish and manage connections to the
database.
b) Method for Populating Data into JTable
A method that retrieves data from the database and
populates it into a JTable for display.
c) Method to Check Whether a Client Already Exists
A method that checks if a client record already exists to avoid
duplicates.
d) Method for Searching Records
A method that allows users to search for records based on
specific criteria.
Reasons:
1.If new record inserted DisplayRecord() must be called to updated grid view
DisplayRecord() 2.If record deleted DisplayRecord() must also be called to see the effect
3.If record is updated DisplayRecord() will be called to update data grid view
7
Void Type Method
▪ Executes the code between the brackets
▪ Does not return result
public static void printHello() { Prints "Hello"
System.out.println("Hello"); on the console
}
14
Methods – Best Practices
▪ Each method should perform a single, well-defined task such inserting
, updating ,and search data from the databases.
▪ A Method's name should describe that task in a clear and non-ambiguous
way it helps improve understandability of code
▪ Avoid methods longer than one screen, break down statements into several
lines
▪ Split them to several shorter methods
private static void printReceipt() {
printHeader();
printBody();
Self documenting
} printFooter(); and easy to test
15
Code Structure and Code Formatting
▪ Make sure to use correct indentation
static void main(args) { static void main(args)
// some code… {
// some more code… // some code…
} // some more code…
}
Requirements:
•The method should be called each time a verification code
is needed.
•It will randomly generate a 6-digit verification code.
•The generated code will be stored in the database.
Invoking a Method (2)
▪ A method can be invoked from:
▪ The main method – main()
public static void main(String[] args) {
printHeader();
}
23
Problem: Sign of Integer Number
▪ Create a method that prints the sign of an integer number n:
24
Solution: Sign of Integer Number
26
Solution: Grades
1
1 1 2
1 2 1 2 3
3 1 2 3 4 1 2 3 4
1 2 1 2 3
1 1 2
1
28
Solution: Printing Triangle (1)
▪ Create a method that prints a single line, consisting of numbers
from a given start to a given end:
public static void printLine(int start, int end) {
for (int i = start; i <= end; i++) {
System.out.print(i + " ");
}
System.out.println();
}
29
Solution: Printing Triangle (2)
▪ Create a method that prints the first half (1..n) and then the
second half (n-1…1) of the triangle: Method with
public static void printTriangle(int n) { parameter n
for (int line = 1; line <= n; line++)
printLine(1, line);
Lines 1...n
for (int line =n - 1; line >= 1; line--)
printLine(1,line);
} Lines n-1…1
30
Live Exercises
Returning Values From Methods
The Return Statement
▪ The return keyword immediately stops the method's
execution
▪ Returns the specified value
public static String readFullName(Scanner sc) {
String firstName = sc.nextLine();
String lastName = sc.nextLine();
return firstName+ " " + lastName;
}
Returns a String
▪ Void methods can be terminated by just using return
33
Using the Return Values
▪ Return value can be:
▪ Assigned to a variable
int max = getMax(5, 10);
▪ Used in expression
double total = getPrice() * quantity * 1.20;
▪ Passed to another method
34
Problem: Calculate Rectangle Area
▪ Create a method which returns rectangle area
with given width and height
3 6
12 48
4 8
5 50 7
56
10 8
35
Solution: Calculate Rectangle Area
String StringString
2
37
Solution: Repeat String
public static void main(String[] args) {
String inputStr = sc.nextLine();
int count = Integer.parseInt(sc.nextLine());
System.out.println(repeatString(inputStr, count));
}
private static String repeatString(String str, int count) {
String result = "";
for (int i = 0; i < count; i++) result += str;
return result;
}
Problem: Math Power
▪ Create a method that calculates and returns the value of a
number raised to a given power
28 256 5.53 166.375
42
Value Types
44
Value Types vs. Reference Types
STACK HEAP
i
42 (4 bytes)
int i = 42;
ch
char ch = 'A'; A (2 bytes)
bytes
byte[]@190d11 1 2 3 byte []
Example: Value Types
public staticvoid main(String[] args) {
int num = 5;
increment(num, 15); num == 5
System.out.println(num);
}
System.out.println(nums[0]);
}
51
Signature and Return Type
▪ Method's return type is not part of its signature
public static void print(String text) {
System.out.println(text); Compile-time
}
error!
public static String print(String text) {
return text;
}
52
Problem: Greater of Two Values
▪ Create a method getMax() that returns the greater of two
values (the values can be of type int, char or String)
int char
2 16 a z
16 z
String
aaa bbb
bbb
53
Live Exercises
Program Execution Flow
Program Execution
▪ The program continues, after a method execution completes:
public static void main(String[] args) {
System.out.println("before method executes");
printLogo();
System.out.println("after method executes");
}
return return
Problem: Multiply Evens by Odds
▪ Create a program that multiplies the sum of all even digits of a
number by the sum of all odd digits of the same number:
▪ Create a method called getMultipleOfEvensAndOdds()
▪ Create a method getSumOfEvenDigits()
▪ Create getSumOfOddDigits()
▪ You may need to use Math.abs() for negative numbers
https://softuni.org
▪ Access the Free Coding Lessons
▪ Get Help from the Mentors
▪ Meet the Other Learners