Computer Graphics
Lecture 4
Dr. Samah Adel
Methods
Defining and Using
Methods, Overloads
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 146
What Is a Method
Void Methods
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();
5
Why Use Methods?
More manageable programming
Splits large problems into small pieces
Better organization of the program
Improves code readability
Improves code understandability
Avoiding repeating code
Improves code maintainability
Code reusability
Using existing methods several times 6
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?
findStudent, loadReport, sine
If you cannot find a good name for a method, think
about whether it has a clear intent
Method1, DoSomething, HandleStuff, SampleMethod
9
Methods – Best Practices
Each method should perform a single, well-defined task
A Method's name should describe that task in a clear and
non-ambiguous way
Avoid methods longer than one screen
Split them to several shorter methods
private static void printReceipt()
{ printHeader();
printBody();
printFooter();
Self documenting
} and easy to test
10
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
Always use curly brackets for loops and if statements bodies
Avoid long lines and complex expressions
11
{…}
Declaring and Invoking Methods
Declaring Methods
Return Type Method Name Parameters
public static void printText(String text) {
System.out.println(text);
} Method Body
Methods are declared inside a class
main() is also a method
Variables inside a method are local
157
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
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
17
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);
}
18
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.
19
Solution: Sign of Integer Number
public static void main(String[] args) {
System.out.print("Enter element");
int n=Integer.parseInt(sc.nextLine());
printSign(n);
}
public static void 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);
}
20
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"
21
Solution: Grades
public static void main(String[] args) {
System.out.print("Enter grade");
printInWords(Double.parseDouble(sc.nextLine()));
}
public static void printInWords(double grade) {
String gradeInWords = "";
if (grade >= 2 && grade <= 2.99)
gradeInWords = "Fail";
if (grade >= 3 && grade <= 3.49)
gradeInWords = “poor";
22
Solution: Grades (Cont.)
if (grade >= 3.5 && grade <= 4.49)
gradeInWords = "Good";
elseif (grade >= 4.5 && grade <= 5.49)
gradeInWords = “Very Good";
elseif (grade >= 5.5 && grade <= 6)
gradeInWords = “Excellent";
else
gradeInWords = “Enter correct gade!";
System.out.println(gradeInWords);
} 23
Problem: Printing Triangle (Report)
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
24
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();
}
25
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
26
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
28
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());
29
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
30
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;
}
31
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
32
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;
}
177
Value vs. Reference Types
Memory Stack and Heap
Value vs. Reference Types
36
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)
37
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
38
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 static void 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 static void main(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
}
Overloading Methods
Method Signature
The combination of method's name and parameters
is called signature Method's
public static void print(String text) { signature
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"
43
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
}
44
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?
45
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
46
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("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 (Report)
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
Any Questions ?!