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

Cit 207 Module Final

b) Exception The correct way to handle potential errors or exceptions in a method is to: (3pts) a) Surround the code with try/catch blocks b) Surround the code with if/else blocks c) Return from the method immediately

Uploaded by

Mhir Re
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
50 views

Cit 207 Module Final

b) Exception The correct way to handle potential errors or exceptions in a method is to: (3pts) a) Surround the code with try/catch blocks b) Surround the code with if/else blocks c) Return from the method immediately

Uploaded by

Mhir Re
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 27

Unit 4: Object-Oriented Programming

a) Introduction
b) Object-Oriented Concept
c) Software Reusability
d) Classes and Objects
e) Calling Instance Method
f) Calling a Static Method
g) Passing Variable

Objectives:
At the end of the unit, the student must have:
a) defined object‐oriented programming and basic concepts
b) defined objects and classes
c) used instance variable and method
d) defined static method
e) used passing variables
How much do you know?

1. Use the correct method to print the length of the txt string.

String txt = "Hello";


System.out.println( . );

2. Use the correct method to return a random number between 0 (inclusive), and
1 (exclusive).

Math. ;

3. Fill in the missing parts to print the value

true: int x = 10;


int y = 9;
System.out.println( );

4. Print “Hello World” if x is greater than y

int x = 50;
int y = 10;
(x y) {
System.out.println( );
}

5. Print “1” if x is equal to y, print “2” if x is greater than y, otherwise print

“3”. int x = 50;


int y = 50;
(x y) {
System.out.println("1");
}
(x > y) {
System.out.println( );
}
{
System.out.println( );
}
Acquire new knowledge
Lesson Proper

Introduction
OOP stands for Object Oriented Programming.

Procedural Programming is about writing procedures or methods that can


perform operations on the data, while Object Oriented Programming is about
creating objects that contain both data and methods.

OOP has several advantages over procedural programming:


 OOP is faster and easier to execute
 OOP provides a clear structure for the programs
 OOP helps to keep the Java code DRY “Don’t Repeat Yourself”, and makes the
code easier to maintain, modify and debug
 OOP makes it possible to create full reusable applications with less code and
shorter development time

Tip: The “Don’t Repeat Yourself” (DRY) principle is about reducing the repetition of
code. You should extract out the codes that are common for the application, and
place them at a single place and reuse them instead of repeating it.

Object-Oriented Concept
Object means a real-world entity such as a pen, chair, table, computer, watch, etc.
Object-Oriented Programming is a methodology or paradigm to design a program
using classes and objects. It simplifies software development and maintenance by
providing some concepts:
 Object
 Class
 Inheritance
 Polymorphism
 Abstraction
 Encapsulation

Apart from these concepts, these are some other terms which are used in
Object-Oriented design:
 Coupling
 Cohesion
 Association
 Aggregation
 Composition

Object - any entity that has state and behavior is known as an object. For example,
a chair, pen, table, keyboard, bike, etc. It can be physical or logical. An object can be
defined as an instance of a class. An object contains an address and takes up some
space in memory. Objects can communicate without knowing the details of each
others data or code.
Class - a collection of objects is called class. It is a logical entity. A class can also be
defined as a blueprint from which you can create an individual object. Class doesn’t
consume any space.

The following illustrations shows the difference between class and objects:

Class Objects Class Objects

Apple Volvo
Fruit Car
Banana Audi

Mango Toyota

Inheritance - when one object acquires all the properties and behaviors of a
parent object, it is known as inheritance. It provides code reusability. It is used to
achieve run-time polymorphism.

Polymorphism - if one task is performed in different ways, it is known as


polymorphism. For example: to convince the customer, to draw something, for
example, to draw shapes like triangle, rectangle, etc. It is the same process or act of
drawing but it produces different output.

Polymorphic Methods
A same message can be sent to objects of different classes

aCircle.surface aRectangle.surface

Different objects can react differently to the same message.


Different classes can provide different implementation for methods with the
same name.

Abstraction - hiding internal details and showing functionality is known as abstracton.


For example, phone call, we don’t know the internal process of it.

Encapsulation - binding or wrapping code and data together into a single unit are
known as encapsulation.

Coupling - refers to the knowledge or information or dependency of another class. It


arises when classes are aware of each other. In java, we use private, protected, and
public modifiers to display the visibility level of a class, method, and field. You can
use interfaces for the weaker coupling because there is no concrete implementation.

Cohesion - refers to the level of a component which performs a single well-defined


task. A single well-defined task is done by a highly cohesive method. The weakly
cohesive method will split the task into separate parts. The java.io package is a
highly cohesive package because it has I/O related classes and interface. However,
the java.util package is a weakly cohesive package because it has unrelated classes
and interfaces.
Association - represents the relationship between the object. Here, one object can
be associated with one obejcts or many object. There can be four types of
association between the objects: One to One, One to Many, Many to One and Many
to Many.
For example, one school can have one School Administrator (One to One), but One
School can have many Teachers (One to Many), Many Teacher can have many
subjects (Many to Many).

Aggregation - is a way to achieve association. The composition represents the


relationship where one object contains other objects as a part of its state. There is a
strong relationship between the containing object and dependent object. It is the
state where containing objects do not have an independent existence. If you delete
the parent object, all the child objects will be deleted automatically.

Software Reusability
Reusability is a general engineering principle whose importance derives for the
desire to avoid duplication and to capture commonality in undertaking classes of
inherently similar tasks.

Software reusability is the degree to which a software module or other product


can be used in more than one software system.

Software reuse is the process of implementing new software systems using existing
software information.

Software reuse example


 Using functions available in some library.
 Reusing classes from another object-oriented program
 Adapting the modules of a software system with a very similar functionality
 Reusing the architecture or design of a software system when porting it to a
new language.

Benefits of Software Reuse:


 Software reuse increases the software productivity and decreases the time
required for the development of a software.
 By using the technique of software reuse, a company can improve software
system interoperability and needs less people for software development.
 This provides a competitive advantage for the company and helps to
produce better quality software and standardized software.
 Software reuse technique helps the company to reduce the costs involved in
software development and maintenance.
 By using it the software developers can be moved from one project to the
other project easily.
 Systems that incorporate a high level of reusable components are more
reliable and more easily constructed.
 Software reuse also reduces the risk involved in software development
process.

Although software reuse provides many benefits for the developers, there are some
disadvantages, like it increases the maintenance cost and occasionally there may be
lack of tool support.
Apply your knowledge. In this part, you will practice what you have
learned.

1. What is method overloading in Java? Give an example (10pts)

2. What is the output of the following code? (5pts)


Assess your knowledge. You will be tested here and you will be able to
know the gaps in your understanding in this lesson. If you are not
satisfied with the feedback, you may then go back to some point that you
may have missed.

1. What is the output of the following Java Program? (5pts)

2. What is the output of the following Java Program (5pts)


3. What will be the output of the following Java program? (5pts)
Unit 5: Exception Handling

a) What are exceptions


b) Catching Exceptions (try, catch, finally)
c) Throwing Exceptions (throw, throws)
d) Exception Categories (API, user defined)

Objectives:
At the end of the unit, the student must have:
a) defined Exceptions;
b) explained the catching exceptions;
c) explained the throwing exceptions;
d) discussed exceptions categories.
How much do you know?

Insert the missing part of the code below to output “Hello World”. (3pts)
public class MyClass {
public static void main(String[] args) {
. . ("Hello World");
}
}

An is also known as an error.


a) Option
b) Exception
c) Alternate code path
d) Identity

What does the expression int a = 12 / 0 return?


a) 0
b) Not a number
c) Infinity
d) Run Time Exception

What will happen when you compile and run the following program? (5pts)
Acquire new knowledge
Lesson Proper
What are exceptions
The Exception Handling in Java is one of the powerful mechanism to handle the
runtime errors so that normal flow of the application can be maintained.
In java, an exception is an event that disrupts the normal flow of the program. It
is an object which is thrown at runtime. (It could considered as an error)

Exception Handling is a mechanism to handle runtime errors such as


ClassNotFoundException, IOException, SQLException, RemoteException, etc.

Advantage of Exception Handling


The core advantage of exception handling is to maintain the normal flow of the
application. An exception normally disrupts the normal flow of the application that is
why we use exception handling.
Let’s take a scenario:

Supposed there are 10 statements in your program and


there occurs an exception at statement 5, the rest of
the code will not be executed i.e. statement 6 to 10 will
not be executed. If we perform exception handling, the
rest of the statement will be executed. That is why we
use exception handling in Java.

Hierarchy of Java Exception


Classes
The java.lang.Throwable class is
the root class of Java Exception
hierarchy which is inherited by two
subclasses: Exception and Error. A
hierarchy of Java Exception classes are
given below:
Types of Java Exceptions
There are mainly two types of exceptions: checked and unchecked. Here, an
error is considered as the unchecked exception. According to Oracle, there are three
types of exceptions:
1. Checked Exception - the classes which directly inherit Throwable class except
RuntimeException and Error are known as checked exceptions e.g. IOException,
SQLException etc. Checked exceptions are checked at compile-time.

2. Unchecked Exception - the classes which inherit RuntimeException are known


as unchecked exceptions e.g. ArithmeticException, NullPointedException,
ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at
compile-time, but they are checked at runtime.

3. Error - is irrecoverable e.g. OutOfMemoryError, VirtualMachineError,


AssertionError, etc.

Java Exception Keywords


There are 5 keywords which are used in handling exceptions in Java.

Java Exception Handling Example


Let’s see an example of Java Exception Handling where we use a try-catch
statement to handle the exception.
Output:

In the above example, 100/0 raises an ArithmeticException which is handled by


try-catch block.

Common Scenarios of Java Exceptions

There are given some scenarios where unchecked exception may occur. They are as
follows:

1) A scenario where ArithmeticException occurs


If we divide any number by zero, there occurs an ArithmeticException.

int a=50/0; //ArithmeticException

2) A scenario where NullPointerException occurs


If we have a null value in any variable, performing any operation on the variable
throws a NullPointerException.

String s = null;
System.out.println(s.length()); // NullPointerException

3) A scenario where NumberFormatException occurs


The wrong formatting of any value may occur NumberFormatException. Suppose
I have a string variable that has characters, converting this variable into digit will
occur NumberFormatException.

String s = “abc”;
int i = Integer.parseInt(s); // NumberFormatException

4) A scenario where ArrayIndexOutOfBoundsException occurs


If you are inserting any value in the wrong index, it would result in
ArrayIndexOutOfBoundsException as shown below:

int a[] = new int[5];


a[10] = 50 // ArrayIndexOutOfBoundsException

Java try-catch block

Java try block


Java try block is used to enclose the code that might throw an exception. It must
be used within the method.
If an exception occurs at the particular statement of try block, the rest of the
block code will not execute.
Java try block must be followed by either catch or finally block.
Syntax of Java try-catch

try{
// code that may throw an exception
} catch(Exception_class_name ref){}

Syntax of try-finally block

try{
//code that may throw an exception
}finally {}

Java catch block

Java catch block is used to handle the Exception by declaring the type of exception
within the parameter. The declared exception must be the parent class exception
(i.e., Exception) or the generated exception type. However, the good approach is to
declare the generated type of exception.

The catch block must be used after the try block only. You can use multiple catch
block with a single try block.

Problem without exception handling

Let’s try to understand the problem if we don’t use a try-catch block.

Example 1

Output:

As displayed in the above example, the rest of the code is not executed (in
such case, the rest of the code statement is not printed).

There can be 100 lines of code after exception. So all the code after exception will
not be executed.
Solution by exception handling
Let’s see the solution of the above problem by a java try-catch block.

Example 2

Output:

Now, as displayed in the above example, the rest of the code is executed, i.e., the
rest of the code statement is printed.

Example 3

Output:

Here, we can see that if an exception occurs in the try block, the rest of the block code
will not execute.
Example 4

Here, we handle the exception using the parent class exception.

Output:

Example 5

Let’s see an example to print a custom message on exception

Output:
Example 6

Let’s see an example to resolve the exception in a catch block.

Output:

25

Example 7

In this example, along with try block, we also enclose exception code in a catch block.

Output:

Here, we can see that the catch block didn’t contain the exception code. So, enclose
exception code within a try block and use catch block only yo handle the exceptions.
Example 8

In this example, we handle the generated exception (Arithmetic Exception) with a


different type of exception calss (ArrayIndexOutOfBoundsException).

Output:

Example 9

Let’s see an example to handle another unchecked exception

Output:
Java Multi-catch block
A try block can be followed by one or more catch blocks. Each catch block must
contain a different exception handler. So, if you have to perform different tasks at the
occurrence of different exceptions, use java multi-catch block.

Points to remember
 At a time only one exception occurs and at a time only one catch block is
executed.
 All catch blocks must be ordered from most specific to most general, i.e.
catch for ArithmeticException must come before catch for Exception.

Example 1

Output:

Java Nested try block


The try block within a try block is known as nested try block in java.

Why use nested try block


Sometimes a situation may arise where a part of a block may cause one error and the
entire block itself may cause another error. In such cases, exception handlers have to
be nested.
Syntax

try{
statement 1;
statement 2;

try{
statement 1;
statement 2;
}

catch(Exception e){

}
}

catch(Exception e){

Java nested try example

Let’s see a simple example of java nested try block.


Java finally block

Java finally block is a block that is used to execute important code suchs as closing
connection, stream, etc.

Java finally block is always executed whether exception is handled or not.

Java finally block follows or catch block.

Note: if you don’t handle exception before terminating the program, JVM executes
finally block (if any)

Why use finally block

Finally block in java can be used to put “cleanup” code such as closing a file, closing
connection, etc.
Example 1

Let’s see the java finally example where exception doesn’t occur.

Output:

Example 2

Let’s see the java finally example where exception occurs and not handled.

Output:
Example 3

Let’s see the java finally example where exception occurs and handled.

Output:

Notice that the only difference with the codes on example 2 and 3 is the catch block.
Example 2 used NollPointerException, but example 3 handled the exception by using
ArithmeticException.

Rule: for each try block there can be zero or more catch blocks, but only one finally
block.

Note: the finally block will not be executed if program exits (either by calling
System.exit() or by causing a fatal error that causes the process to abort).
Apply your knowledge. In this part, you will practice what you have
learned.

Inset the missing keyword to handle the error in the code below. (4pts)

{
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
}
(Exception e) {
System.out.println("Something went wrong.");
}

What is the output of the code above? (3pts)

Insert the missing keyword to execute code, after try.. catch, regardless of the result.
(2pts)

try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} catch (Exception e) {
System.out.println("Something went wrong.");
} {
System.out.println("The 'try catch' is finished.");
}

What is the output of the code above? (6pts)


Assess your knowledge. You will be tested here and you will be able to
know the gaps in your understanding in this lesson. If you are not
satisfied with the feedback, you may then go back to some point that you
may have missed.

1. What is the use of try & catch?


a) It allows us to manually handle the exception
b) It allows to fix errors
c) It prevents automatic terminating of the program in cases when an exception
occurs
d) All of the mentioned

2. Which of these keywords are used for the block to be examined for exceptions?
a) try
b) catch
c) throw
d) check

3. Which of these keywords are used for the block to handle the exceptions
generated by try block?
a) try
b) catch
c) throw
d) check

4. If an error occurs when code inside a try block runs, what will happen next?
a) Nothing will ever happen. The program will always crash.
b) The next line of code in the try block runs.
c) The code starts running again from the beginning of the try block.
d) The code in the catch block runs.

5. Which of these statements is incorrect?


a) try block need not to be followed by catch block
b) try block can be followed by finally block instead of catch block
c) try can be followed by both catch and finally block
d) try need not to be followed by anything

6. What will be the output of the following java code?

a) Hello
b) World
c) HelloWorld
d) Compilation Error
7. What will be the output of the following Java code?

a) Hello
b) World
c) HelloWorld
d) Compilation Error

8. What will be the output of the following Java code?

a) Hello
b) World
c) HelloWorld
d) Compilation Error
9. What will be the output of the following code?

a) Hello
b) World
c) HelloWorld
d) Compilation Error

10. What will be the output of the following code?

a) Hello
b) WorldWorld
c) HelloWorld
d) Compilation Error

You might also like