0% found this document useful (0 votes)
18 views

CPE207 Object Oriented Programming (Week 4)

Uploaded by

sinemturkyilmaz8
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)
18 views

CPE207 Object Oriented Programming (Week 4)

Uploaded by

sinemturkyilmaz8
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/ 22

Week 4

Working with classes: Exception


handling, static keyword

Dr. Nehad Ramaha,


Computer Engineering Department
Karabük Universities These Slides mainly adopted from Assist. Prof. Dr. Ozacar Kasim lecture notes
1
The class notes are a compilation and edition from many sources. The instructor does not claim intellectual property or ownership of the lecture notes.
 Why do we create methods to
access variables, if we can access
Class Foo {
them directly? private String name;
◦ Answer: security issue.
 'private' variables can only be public void setName(String name){
//put any condition
accessed in the class. It's as if this.name = name;
they were invisible out of the }
scope of the class / object.
 Using set() and get() methods, A public String getName(){
class can have total control over //put any condition
what is stored in its attributes return name;
}
}

2
 A class can have total control over what is
stored in its attributes.
 Attributes of a class can be made read-only or write-only.
 The users of a class do not know how the class stores its
data.
◦ A class can change the data type of a attributes and users of the
class do not need to change any of their code.

CME225 OOP- Week 4 2/10/2023 3


errors

Compile Time
Errors Run Time Errors
-Syntax error Exceptions
in a; -exceptions are events that disrupt
-Type mismatch, wrong the normal flow of the program's
casting instructions during the execution of
- int x = “asdsad”; a program.
- …

We must handle the Exception,


otherwise the program will crash!!
4
What if value2 is zero? This is an exception

Value1/value2 is undefined

This is an exception that disrupts the


normal flow of the program's
instructions
5
6
 Exception handling is a mechanism that allows The general form of try-
you to take appropriate action to avoid run-time catch block in Java.
errors.
 Java provides five keywords to support
exception handling.
◦ Try : The try block contain statements which may
generate exceptions.
◦ Catch :The catch block defines the action to be taken,
when an exception occur.
◦ Throw : When an exception occur in try block, it is
thrown to the catch block using throw keyword.
Finally block can be used
◦ Throws : Throws keyword is used in situation, when
we need a method to throw an exception. to put "cleanup" code
◦ Finally : If exception occur or not, finally block will such as closing a file,
always execute. closing connection etc.

7
try{
//statements that may cause an exception
}
catch (Exception(type) e(object)){
//error handling code
//System.out.println(e.getMessage());
}

public String getMessage()


-Returns a detailed message about the exception that has occurred. This
message is initialized in the Throwable constructor.

9
• Class Time1 represents the time
of day. Time1
-hour:int
• private int instance variables
-minute:int
hour, minute and second
represent the time in universal- -second:int
time format (24-hour clock <<constructor>>Time1(hour:int, minute: int,
format in which hours are in the second:int)
range 0–23, and minutes and +setHour(h: int)
seconds are each in the range 0– +setMinute(m: int)
59). +setSecond(s: int)
• public methods setHour(), +toString():String
setMinute(), setSecond(), +toUniversalString():Sting
toUniversalString() and
toString().

10
11
12
class TestClass{
void m(){
int data=50/0;
}
void n(){
m();
}
void p(){
try{
n();
}catch(Exception e){
System.out.println("exception handled");}
}
public static void main(String args[]){
TestClass obj=new TestClass();
obj.p();
System.out.println("normal flow...");
}

https://simplesnippets.tech/throw-throws-in-java-exception-handling-part-3/
13
Scanner scanner = new Scanner(System.in);
If there is no error in input, then try{
no exception is thrown, and the int num = scanner.nextInt();
output will be if (num > 100) {
DONE throw new Exception("Out of bound");
If there is an error in input, one }
of the two exceptions is thrown,
} catch (InputMismatchException e) {
and the output will be
Not an integer
System.out.println("Not an
DONE integer");
or } catch (Exception e) {
Error: Out of bound System.out.println("Error: "+
DONE e.getMessage());
} finally {
System.out.println("DONE");
}

14
 The static keyword is a non-access modifiers and used in java
mainly for memory management. It is used with variables,
methods, blocks and nested classes.
 It is a keyword that are used for share the same variable or
method of a given class.
 This is used for a constant variable or a method that is the same
for every instance of a class.

15
16
 If any variable, we declared as static is known as static variable.

 Static variable is used for fulfill the common requirement. For


Example, college name of students etc.
Name of the college is common for all students.

 The static variable allocate memory only once in class area at the
time of class loading.

 Using static variable we make our program memory efficient (i.e it


saves memory).

17
 Suppose we want to store record of all employee of
any company, in this case employee id is unique for
every employee but company name is common for
all. So, use static variable to store the company name.
 When we create a static variable as a company name
then only once memory is allocated otherwise it
allocate a memory space each time for every
employee object.

18
19
 static keyword always fixed the memory that means that will be
located only once in the program
 final keyword always fixes the value that means it makes
variable values constant
 Note: As for as real time statement there concern every final
variable should be declared the static but there is no obligation
that every static variable declared as final.

20
21
 You need to read an integer value from
keyboard. However, let's say a user typed a
string value.
 This will cause an input mismatch exception.
 Handle this exception.
(Hint: use InputMismatchException
exception.)

22
• Create a Worker class which contains name salary attributes
• Create setName and setSalary methods.
• Your program should throw an exception when salary value is less than zero. (When
you enter an illegal argument)
• The exception message is “salary amount must be greater than zero”
• In main method handle the exception and display the exception message.

 Add another attribute (counter) which must be shared by all the


instances of Worker class.
 Create three workers and display number of total workers using
counter variable.

23

You might also like