Lec4-Computer Graphics
Lec4-Computer Graphics
Lecture 4
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
}
18
Problem: Sign of Integer Number
Create a method that prints the sign of an integer number n:
19
Solution: Sign of Integer Number
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
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
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)
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);
}
System.out.println(nums[0]);
}
System.out.println(text);
}
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;
}
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");
}
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