Chapter 2 Methods and Exception
Chapter 2 Methods and Exception
Chapter 2 Methods and Exception
Chapter 2
num ++;
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.
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);
}
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:
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
}
} 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.
Enhanced
public static void main(String[] args) {
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