Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Chapter 2 Methods and Exception

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 42

AACS2204 Object-Oriented Programming Techniques

Chapter 2

Methods & Exception Handling


Learning Outcomes
At the end of this chapter, you should be able to
■ Define methods, invoke methods and pass arguments to methods.
■ Use method overloading in programs.
■ Apply basic exception handling.
1. Methods
In Java, a function is known as a method.
Method Signature
Method signature is the combination of the method name and
the parameter list.
Formal Parameters
The variables defined in the method header are known as formal
parameters.
Actual Parameters
When a method is invoked, you pass a value to the parameter. This
value is referred to as actual parameter or argument.
Passing Parameters
The arguments (in the method call statement) must match
the formal parameters (in the method definition) in order,
number and compatibility type.

public static void nPrintln(String message, int n) {


for (int i = 0; i < n; i++)
System.out.println(message);
}

What is the output from these method calls:


⮚ nPrintln(“Welcome to Java”, 5);
⮚ nPrintln(“Computer Science”, 15);
Pass by Value
⮚ In Java, the value of the argument is passed to the
parameter.
⮚The variable used as an argument is not affected
regardless of the changes made to the parameters inside
the method.
Pass by Value
public class ByValueTest { Output:
public static void main(String[] args) {
int num = 1; Num : 1
Before : 1
System.out.println(“Num : ” + num ); After : 2
change(num1); Num : 1
System.out.println(“Num : ” + num );
}

public static void change (int num) {


System.out.println("Before : ” + num);

num ++;

System.out.println("After : " + num);


}
}
Return Value Type
⮚ A method may return a value. The return Value Type is the data type
of the value the method returns.
⮚ If the method does not return a value, the return Value Type is the
keyword void.
CAUTION
⮚ A return statement is required for a value-returning
method.
⮚ The method shown below in (a) is logically correct, but it
has a compilation error because the Java compiler thinks it
possible that this method does not return any value.

How can we fix this problem?

11
2. Modifiers
⮚ Modifiers are the reserved words that specify the properties
of the data, methods and classes and how they can be used.
⮚ Examples of modifiers are public, private, protected,
static, final and abstract.
⮚ A public datum, method or class can be accessed by other
programs.
⮚ A private datum or method cannot be accessed by other
programs.

[note : Modifiers are discussed in Chapter 4, “Objects and Classes.”]


2. Modifiers
■ Default: When no access modifier is specified for a class ,
method or data member – It is said to be having
the default access modifier by default.
■ having default access modifier are accessible only within the
same package.

13
14
Static Keyword
■ Used a lot in java programming
■ Apply java static keyword with
■ Variables
■ Methods
■ Nested class
■ Block

15
Static Variable
▪ Are shared by all the instances of the class.
▪ May be accessed using the object name or the class name
▪ The static variable can be used to refer the common
property of all objects(that is not unique for each objects)
e.g collage name of students, company name of employees
etc.

16
Static methods
■ belongs to the class rather than the object of a class.
■  can be invoked without the need for creating an instance of
a class.
■ can be accessed directly in static and non-static methods.
■ For example, the main() method that is the entry point of a
java program itself is a static method.

17
3. Reuse Methods from Other Classes
public class TestMax {
public static void main(String[] args) {
int i = 5, j = 2;
int k = max(i, j);
System.out.println("The maximum between " + i + " and " + j + " is " + k);
}

/* Return the max between two numbers */


public static int max(int num1, int num2) {
int result;

if (num1 > num2)


result = num1; The max method can be invoked from any class
else besides TestMax.
result = num2;
If you create a new class Test, you can invoke
return result; the max method using TestMax.max (ie
} ClassName.methodName)
}
Example:
import java.util.Scanner;

public class AnotherClass {


public static void main(String[] args) {
int num1, num2, maxNum;
Scanner input = new Scanner(System.in);

System.out.print("Enter the first number: ");


num1 = input.nextInt();

System.out.print("Enter the first number: ");


num2 = input.nextInt();

// call method max from class TestMax


maxNum = TestMax.max(num1, num2);
System.out.println("The maximum between the two numbers is " + maxNum);
}
}
4. Method Overloading
Method overloading : 2 or more methods with the same name
but different parameter lists ie different type or number of
parameters.

⮚ The max method work with int-typed arguments.


⮚ What if we need to find the maximum value of two real
numbers?
⮚ Solution - use method overloading
Method Overloading
public class FindMax{
public static int max(int num1, int num2) {
if (num1 > num2)
return num1;
else
return num2;
}

public static double max(double num1, double num2) {


if (num1 > num2)
return num1;
else Question :
return num2;
What if we need to find the maximum
}
} value of three real numbers?
Method Overloading
⮚ Different versions of method max will be called depending
on the argument types in the method call:
⮚If you call max with int arguments, the max method
with int parameters will be invoked.
⮚If you call max with 2 double arguments, the max
method with 2 double parameters will be invoked.
⮚ The Java compiler determines which version of the method
is used based on the method signature.
Ambiguous Invocation
⮚ Sometimes there may be two or more possible matches for an
invocation of a method, but the compiler cannot determine
the most specific match: ambiguous invocation.
⮚ Ambiguous invocation is a compilation error.
  public static double max(int num1, double num2) {
if (num1 > num2)
return num1;
else
return num2;
}
public static double max(double num1, int num2) {
if (num1 > num2)
return num1;
else
return num2;
x = max (1, 2);
} Which method will be involved?
5. Scope of Local Variables
⮚ The scope of a local variable public class TestMax {
public static void main(String[] args) {
starts from its declaration and int i = 5;
continues to the end of the int j = 2;
block that contains the variable. int k = max(i, j);
….
⮚ A parameter is actually a local }
variable and its scope covers public static int max(int num1, int
the entire method. num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
}
Scope of Local Variables
A variable declared in the initial action part of a for loop header
has its scope in the entire loop. But a variable declared inside a
for loop body has its scope limited in the loop body from its
declaration and to the end of the block that contains the variable.
Scope of Local Variables
You can declare a local variable with the same name multiple times in
different non-nesting blocks in a method, but you cannot declare a
local variable twice in nested blocks.
6. Method Abstraction
⮚ You can think of the method body as a black box that
contains the detailed implementation for the method.
⮚ The detail implementation are hidden.
Benefits of Methods
⮚ Write a method once and reuse it anywhere.
⮚ Information hiding. Hide the implementation from the
user.
⮚ Reduce complexity.
⮚ Ease of maintenance
7. The Math Class
⮚ The Math class contains mathematical constants and
methods which perform basic mathematical functions.
⮚ Class constants:
■ PI
■E
⮚ Class methods:
■ Trigonometric Methods
■ Exponent Methods
■ Rounding Methods
■ min, max, abs, and random Methods
Trigonometric Methods
Examples:
■ sin(double a)
■ cos(double a) Math.sin(0) returns 0.0
Math.sin(Math.PI / 6) returns 0.5
■ tan(double a)
Math.sin(Math.PI / 2) returns 1.0
■ acos(double a) Math.cos(0) returns 1.0
■ asin(double a) Math.cos(Math.PI / 6) returns 0.866
■ atan(double a) Math.cos(Math.PI / 2) returns 0
Math.cos(Math.toRadians(270)) returns -1.0

Radians
pow, sqrt Methods
⮚ pow(double a, double b)
Returns a raised to the power of b.
⮚ sqrt(double a)
Returns the square root of a.
Examples:
Math.pow(2, 3) returns 8.0
Math.pow(3, 2) returns 9.0
Math.pow(3.5, 2.5) returns 22.91765
Math.sqrt(4) returns 2.0
Math.sqrt(10.5) returns 3.24
min and max Method
⮚ max(a, b)
⮚ min(a, b)
Returns the maximum or minimum of two parameters.

Examples:

Math.max(2, 3) returns 3
Math.max(2.5, 3) returns 3.0
Math.min(2.5, 3.6) returns 2.5
The random Method
Generates a random double value greater than or equal to 0.0 and
less than 1.0 (0 <= Math.random() < 1.0).
Examples:

(char)(‘A’ + Math.random() * (‘F’ – ‘A’ + 1)); Return a random character


between A and F

In general,
For more information about the methods on Math class, please
refer to Oracle Help Center at
https://docs.oracle.com/javase/10/docs/api/java/lang/Math.html

34
Generate random character
public class RandomCharacter {
/** Generate a random character between ch1 and ch2 */
public static char getRandomCharacter(char ch1, char ch2) {
return (char)(ch1 + Math.random() * (ch2 - ch1 + 1));
}
  /** Generate a random lowercase letter */
public static char getRandomLowerCaseLetter() {
return getRandomCharacter ('a', 'z');
}
  /** Generate a random digit character */ RandomCharacter
public static char getRandomDigitCharacter() {
return getRandomCharacter ('0', '9'); TestRandomCharacter
}
 }
8. Exception Handling
Exception : An error that occurs at run time.
import java.util.Scanner; ExceptionDemo.java

public class ExceptionDemo {


public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);


System.out.print("Enter an integer: "); Read integer
int number = scanner.nextInt();
System.out.println("The number entered is " + number);

}
} Question : What will happen when input other than integer ?
Exception Handling
⮚ Streamlines error handling by allowing your program to define a
block of code called an exception handler.
⮚ The exception handler is automatically executed when an error
occurs.
⮚ In Java, exception handling is managed using 5 keywords: try,
catch, throws, throw and finally.

[Note: we will only cover try and catch.]


Using try and catch
Steps:
1. Put the code that you want to monitor for errors within a try block.
2. When an exception occurs, the exception is thrown out of the try block
and caught by the catch statement. At this point, control passes to the
catch, and the try block is terminated.
3. After the catch statement executes, program control continues with the
statement following the catch. Thus, it is the job of the exception
handler to remedy the problem that caused the exception.
public class HandleExceptionDemo {

Enhanced
public static void main(String[] args) {

version Scanner scanner = new Scanner(System.in);


boolean continueInput = true;

do {
try {
System.out.print("\nEnter an integer: ");
int number = scanner.nextInt();
System.out.println("\nThe number entered is " + number);
continueInput = false;
}
catch (Exception ex) {
System.out.println("Incorrect input: an integer is required");
scanner.nextLine();
}
} while (continueInput);
}
}
HandleExceptionDemo.java
The finally Clause
Used when there are statements that are always to be
executed, whether the try block exits normally or not.
try {
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}
Review of learning outcomes
You should now be able to
■ Define methods, invoke methods and pass arguments to methods.
■ Use method overloading in programs.
■ Write a try-catch block to handle exceptions.

41 41
To Do
■ Review the slides and source code for this chapter.
■ Read up the relevant portions of the recommended text .
■ Complete the remaining practical questions for this chapter.
■ We shall selectively discuss them during class.

42 42

You might also like