[go: up one dir, main page]

0% found this document useful (0 votes)
4 views60 pages

Chapter 5 Methods

Chapter 5 covers methods in Java, detailing their definition, declaration, invocation, and best practices. It explains the importance of methods for code reusability, organization, and maintainability, while also discussing parameters, return types, and method overloading. Additionally, it includes practical examples and case studies to illustrate the application of methods in programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views60 pages

Chapter 5 Methods

Chapter 5 covers methods in Java, detailing their definition, declaration, invocation, and best practices. It explains the importance of methods for code reusability, organization, and maintainability, while also discussing parameters, return types, and method overloading. Additionally, it includes practical examples and case studies to illustrate the application of methods in programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

Chapter 5

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.

A method is a block of code which only runs when it is called.


You can pass data, known as parameters, into a method.
Methods are used to perform certain actions, and they are also
known as functions.
Why use methods? To reuse code: define the code once, and
use it many times.

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
}

public static void main(String[] args) {


System.out.println("Hello");
} main() is also
a method
Naming and Best Practices
Naming Methods
▪ Methods naming guidelines
▪ Use meaningful method names
▪ Method names should answer the question:
▪ What does this method do?
DBconnection, SearchRecord,DisplayRecord

▪ If you c annot find a good name for a method, think


about whether it has a clear intent
Method1, DoSomething, HandleStuff, SampleMethod
13
Naming Method Parameters
▪ Method parameters names
▪ Preferred form: [Noun] or [Adjective] + [Noun]
▪ Should be in camelCase
▪ Should be meaningful
House_NO, previous_reading, current_reading,
UnitPrice, consumption, amountDue

▪ Unit of measure should be obvious


p, p1, p2, populate, LastName, last_name, convertImage

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…
}

▪ Leave a blank line between methods, after loops and after


if statements to make clear indentation and good arrangement
▪ Always use curly brackets for loops and if statements bodies
▪ Avoid long lines and complex expressions
16
{…}
Declaring and Invoking Methods
Declaring Methods

Return Type Method Name Parameters


public static void printText(String text) {
System.out.println(text);
} Method Body

▪ Method body can be a single or multiple statements it depends on the


operation it performed
▪ Methods are declared inside a class
▪ main() is also a method
▪ Variables inside a method are local and the can be accessible within the method
18
Invoking a Method
▪ Methods are first declared, then invoked (many times)
public static void printHeader() {
System.out.println("----------"); Method
} Declaration

▪ Methods can be invoked (called) by their name + ():


public static void main(String[] args) {
printHeader();
} Method
Invocation
Case Study:
Generating a Verification Code
Objective:
Create a method to generate a verification code for
password setting purposes.

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();
}

▪ Its own body – recursion ▪ Some other method


static void crash() { public static void printHeader() {
crash(); printHeaderTop();
} printHeaderBottom();
}
double
String
long

Methods with Parameters


Method Parameters
▪ Method parameters can be of any data type
static void printNumbers(int start, int end) {
for (int i = start; i <= end; i++) {
System.out.printf("%d ", i); Multiple parameters
} separated by comma
}

▪ Call the method with certain values (arguments)


public static void main(String[] args) {
printNumbers(5, 10);
} Passing arguments at invocation
22
Method Parameters (2)
▪ You can pass zero or several parameters
▪ You can pass parameters of different types
▪ Each parameter has name and type
Multiple parameters Parameter Parameter
of different types type name
public static void printStudent(String name, int age, double grade) {
System.out.printf("Student: %s; Age: %d, Grade: %.2f\n",
name, age, grade);
}

23
Problem: Sign of Integer Number
▪ Create a method that prints the sign of an integer number n:

2 The number 2 is positive.

-5 The number -5 is negative.

0 The number 0 is zero.

24
Solution: Sign of Integer Number

public static void main(String[] args) {


printSign(Integer.parseInt(sc.nextLine()));
}

public staticvoid printSign(int number) {


if (number >0)
System.out.printf("The number %d is positive.", number);
else if (number < 0)
System.out.printf("The number %d is negative.", number);
else
System.out.printf("The number %d is zero.", number);
}
25
Problem: Grades
▪ Write a method that receives a grade between 2.00 and 6.00
and prints the corresponding grade in words
▪ 2.00 - 2.99 - "Fail"
▪ 3.00 - 3.49 - "Poor" 3.33 Poor

▪ 3.50 - 4.49 - "Good" 4.50 Very good


▪ 4.50 - 5.49 - "Very good"
2.99 Fail
▪ 5.50 - 6.00 - "Excellent"

26
Solution: Grades

public static void main(String[] args) {


printInWords(Double.parseDouble(sc.nextLine()));
}
public static void printInWords(double grade) {
String gradeInWords = "";
if (grade >= 2 && grade <= 2.99)
gradeInWords = "Fail";
//TODO: make the rest
System.out.println(gradeInWords);
}
27
Problem: Printing Triangle
▪ Create a method for printing triangles as shown below:

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

int age = Integer.parseInt(sc.nextLine());

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

public static void main(String[] args) {


double width =Double.parseDouble(sc.nextLine());
double height=Double.parseDouble(sc.nextLine());
double area =calcRectangleArea(width, height);
System.out.printf("%.0f%n",area);
}

public static double calcRectangleArea(


double width, double height) {
return width * height;
}
36
Problem: Repeat String
▪ Write a method that receives a string and a repeat count n
▪ The method should return a new string
abc
abcabcabc
3

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

public static double mathPower(double number, int power) {


double result = 1;
for (int i = 0; i < power; i++)
result *= number;
return result;
}
39
Live Exercises
Value vs. Reference Types
Memory Stack and Heap
Value vs. Reference Types

42
Value Types

▪ Value type variables hold directly their value


▪ int, float, double,
Stack
boolean, char, …
i
▪ Each variable has its
42 (4 bytes)
own copy of the value
ch
int i = 42; A (2 bytes)
char ch = 'A'; result
boolean result = true; true (1 byte)
43
Reference Types
▪ Reference type variables hold а reference
(pointer / memory address) of the value itself
▪ String, int[], char[], String[]
▪ Two reference type variables can reference the
same object
▪ Operations on both variables access / modify
the same data

44
Value Types vs. Reference Types

STACK HEAP
i
42 (4 bytes)
int i = 42;
ch
char ch = 'A'; A (2 bytes)

boolean result = true; result


true (1 byte)
Object obj = 42;
obj
String str = "Hello"; int32@9ae764 42 4 bytes
str
byte[] bytes ={ 1, 2, 3 }; String@7cdaf2 Hello String

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);
}

public static void increment(int num, int value) {


num += value;
num == 20
}
Example: Reference Types
public staticvoidmain(String[] args) {
int[]nums = { 5 };
increment(nums, 15); nums[0] == 20

System.out.println(nums[0]);
}

public static void increment(int[] nums, int value) {


nums[0] += value;
nums[0] == 20
}
Live Exercises
Overloading Methods
Method Signature
▪ The combination of method's name and parameters
is called signature Method's
signature
public static void print(String text) {
System.out.println(text);
}

▪ Signature differentiates between methods with same names


▪ When methods with the same name have different signature,
this is called method "overloading"
50
Overloading Methods
▪ Using the same name for multiple methods with different
signatures (method name and parameters)
static void print(int number) { static void print(String text) {
System.out.println(number); System.out.println(text);
} }

static void print(String text, int number) { Different method


System.out.println(text + ' ' + number); signatures
}

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;
}

▪ How would the compiler know which method to call?

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");
}

public static void printLogo() {


System.out.println("Company Logo");
System.out.println("http://www.companywebsite.com");
}
Program Execution – Call Stack
▪ "The stack" stores information about the active subroutines
(methods) of a computer program
▪ Keeps track of the point to which each active subroutine should
return control when it finishes executing
Call Stack
call call

Start Main Method A Method B

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

Evens: 2 4 Even sum: 6


-12345 54
Odds: 1 3 5 Odd sum: 9
Live Exercises
Summary

▪ Break large programs into simple


methods that solve small sub-problems
▪ Methods consist of declaration and body
▪ Methods are invoked by their name + ()
▪ Methods can accept parameters
▪ Methods can return a value or nothing
(void)
Next Steps

▪ Join the SoftUni "Learn To Code" Community

https://softuni.org
▪ Access the Free Coding Lessons
▪ Get Help from the Mentors
▪ Meet the Other Learners

You might also like