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

Compiled Module CPEPRO2

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)
19 views

Compiled Module CPEPRO2

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/ 163

SCHOOL OF INFORMATION TECHNOLOGY

CPEPRO2 OBJECT-ORIENTED
PROGRAMMING

Prepared by: A Self-regulated Learning Module


Meynard O. Soriano

prepared by: MOS A Self-regulated Learning Module 1


Table of Contents

Table of Contents .................................................................................................................................. 2


Introduction of the Course ................................................................................................................... 3
COURSE MODULES................................................................................................................................ 4
MODULE 1 ............................................................................................................................................. 4
Microcontroller vs Microprocessor ....................................................... Error! Bookmark not defined.
Advantage of Microcontroller.......................................................................................................... 5
Difference of a Microcontroller from a Microprocessor .................. Error! Bookmark not defined.

prepared by: MOS A Self-regulated Learning Module 2


Introduction of the Course

Course Code: CPEPRO2

Course Title: Object-Oriented Programming

Course Description:
This course is a continuation of the subject Programming Logic and Design or CPEPRO1. It
introduces methods and later progresses to the discussion of the different concepts in Object-oriented
Programming using Java Language.

Requirement of the Course:


• Assignments
• Quizzes
• Group works
• Group/Individual Reporting
• Major examinations

prepared by: MOS A Self-regulated Learning Module 3


COURSE MODULES

MODULE 1 Review of Arrays


Time: 1 hour
About this lesson: This lesson reviews single and two-dimensional arrays. It will
also introduce common errors when dealing with arrays.

Course Learning Outcomes:


At the end of this module, the students must have:
1. used single dimensional array in a program
2. used two-dimensional array in a program

Single array
• Arrays are used to store multiple values called elements in a single variable, instead of
declaring separate variables for each value. The values must be of the same type.

• Java array is an object.


• It is a data structure where we store similar elements. We can store only a fixed set of
elements in a Java array.
• Array in java is index-based, the first element of the array is stored at the index zero.

Advantages:
• Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
• Random access: We can get any data located at an index position.

Disadvantage
• Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at
runtime. To solve this problem, collection framework is used in Java which grows
automatically.

prepared by: MOS A Self-regulated Learning Module 4


Syntax to Declare an Array in Java
dataType[] arr; (or)
dataType []arr; (or)
dataType arr[];

Instantiation of an Array in Java


arrayRefVar=new datatype[size];

Declaration, Instantiation and Initialization of Java Array


int a[]={33,3,4,5};

Array Index Out Of Bounds Exception


• The Java Virtual Machine (JVM) throws an ArrayIndexOutOfBoundsException if length of the
array is negative, equal to the array size or greater than the array size while traversing the
array.

Example:

Multidimensional Array in Java


• In such case, data is stored in row and column based index (also known as matrix form).

Syntax to Declare Multidimensional Array in Java:


dataType[][] arrayRefVar; (or)
dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[];
Instantiation
int[][] arr=new int[3][3];//3 rows and 3 columns

Declaring and Initializing an array


int[][] boxes = { {5,9,12,7},
{5,7,2,8}};

prepared by: MOS A Self-regulated Learning Module 5


prepared by: MOS A Self-regulated Learning Module 6
ASSESSMENT:

Nature: Individual
General Code the following
Instruction:
Requirement: Submit a softcopy through Canvas labeled as Module 1 Assessment. This
should be an ATTACHMENT in MSWord format.
Duration: 4 hours

A program that lets the user enter a 4x4 matrix which accepts only 1 or 0.

Let the user select if row or column.

After which, select which row/col to complement (if 1 make it 0, if 0 make it 1)

Sample output:
Enter matrix:
1 1 0 1
1 0 1 0
1 1 0 1
0 0 0 1

[R]ow or [C]ol? R
Enter row/col: 2

Result:
1 1 0 1
0 1 0 1
1 1 0 1
0 0 0 1

prepared by: MOS A Self-regulated Learning Module 7


Intro to Object-oriented
Programming (OOP)
MOTIVATION:

Instructor will give you a “blank” trace of a shoe.


In a group of 4, design the shoe based on the
following:
1. Brand
2. Color
3. Size
OBJECTIVES:

At the end of the lesson, the students are expected to


have
1. defined OOP,
2. differentiated Class from Object,
3. defined what is a constructor, accessor and
mutator,
4. differentiated Static from Non-static Variable
using a table, and
5. created a class.
About OOP

Simula is considered the first object-oriented programming language.

Smalltalk is considered the first truly object-oriented programming


language.

Object-Oriented Programming is a paradigm that provides many concepts


such as inheritance, data binding, polymorphism, etc.

The popular object-oriented languages are Java, C#, PHP, Python, C++,
etc.
OOP SYSTEM

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 the software development and
maintenance by providing some concepts:

❖ Object

❖ Class

❖ Inheritance

❖ Polymorphism

❖ Abstraction

❖ Encapsulation
OBJECT

Any entity that has state and behavior is known as an


object.

❖For example a shoe, 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.
STATE: BEHAVIORs:

Objects can communicate without knowing the details brand: Samsung call
of each other's data or code. The only necessary thing color: BLACK turnOn
is the type of message accepted and the type of turnOff
RAM: 4 GB
response returned by the objects.
ROM: 64 GB sendMail

Example: A mobile phone is an object because it has


states like brand: Samsung, color: black, name: S21, etc.
as well as behaviors like call, turnOn, turnOff, etc.
OBJECT DEFINITIONS:

1. An object is a real-world entity.


2. An object is a runtime entity.
3. The object is an entity which has:
a.) state and

b.) behavior.
4. The object is an instance of a class.
CLASS

1.) Collection of objects is called


class. It is a logical entity.
2.) A class can also be defined as
a blueprint from which you can
create an individual object. Class STATE: BEHAVIORs:

doesn't consume any space. brand: call

color: turnOn

RAM: turnOff

ROM: sendMail
CLASS contains:

1. Fields
2. Methods
3. Constructors
4. Blocks
5. Nested class and interface
CLASS vs OBJECT, a view from the top
DIFFERENTIATE A CLASS FROM AN OBJECT USING
THE FOLLOWING TABLE:
CLASS OBJECT
Memory
consumption
Number (how many)
Has a current state
Behavior
Existence (logical/real
or real-time)
CODING:
“MIRROR ME” activity
Creating a class:

public class Hero


{

public – access modifier which means the class is accessible to all


objects
class – keyword to denote it is a class
identifier – any valid Java identifier starting with an uppercase.
Instance variable

public class Hero


{
private int life;
}

data field – is part of the class’s state in this case, life. A “non-static”
variable in a class is called instance variable which means all instantiated
objects will have their own life variable.
private – access modifier which means it is only accessible to the class
Instance variables

public class Hero


{
private int life;
private int mana;
private String[] skills;
}
Instance method

Accessor and Mutator

public class Hero


instance method – a “non-
{
static” method within a class
private int life;
mutator – is a setter method or
public void setLife(int _life) method that changes the value
{ of an instance variable
life = _life; accessor – is a getter method or
} method that retrieves the value
public int getLife() of an instance variable
{
return life;
}
}
Instance methods

public class Hero public void getLife()


{
{ return life;
private int life; }
private int mana; public void setMana(int _mana)
{
private String[] skills;
mana = _mana;
}
public void setLife(int _life) public void getMana()
{ {
life = _life; return mana;
}
}
...
}
Constructor

public class Hero public class Hero


{ {
public Hero()
{
life=3;
mana=1;
}
} }

constructor – a special method that has the same name as the class. Its function
is to initialize an instantiated object
If not explicitly defines, java creates one for you.
Numeric field are set to 0, character fields are set to Unicode ‘\u0000’, Boolean
fields to false and object fields such as String to null.
DIFFERENTIATE STATIC
FROM NON-STATIC
Static Non-static
static is a keyword No keyword used
class variables / static variables instance variable / non-static variable

Class methods / static methods Instance methods/ non-static methods

No need for objects Must use an object


instantiate 10 objects, only one copy of instantiate 10 objects, 10 copies of
that field exists in memory that field exist in memory

instantiate 10 objects, only one copy of the Instantiate 10 objects, only one copy of the
method exist and method does not receive method exist but the method receives
a this reference a this reference that contains the address
of the object currently using it
every instance of a class shares separate memory location for
the same copy of any class variables each non-static field in each instance
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 runtime polymorphism.
•The class from which the subclass is derived is called
a superclass (also a base class or a parent class). Except
Object , which has no superclass, every class has one
and only one direct superclass(single inheritance).
•A subclass inherits all the members (fields, methods, and
nested classes) from its superclass.
Polymorphism

If one task is performed by different ways, it is


known as polymorphism.
For example: draw shape: triangle, rectangle, etc.
In Java, we use method overloading and method
overriding to achieve polymorphism.
Another example can be to speak something; for
example, a cat speaks “meow”, dog barks “woof”,
etc.
Call via Call via
Messages Dialer

Call via
Contacts

Call via
Browser
ENCAPSULATION

Encapsulation is one of the four fundamental OOP concepts.

Encapsulation in Java is a mechanism for wrapping the data (variables)


and code acting on the data (methods) together as a single unit.

In encapsulation, the variables of a class will be hidden from other


classes and can be accessed only through the methods of their current
class. Therefore, it is also known as data hiding.

To achieve encapsulation in Java −


● Declare the variables of a class as private.
● Provide public setter and getter methods to modify and view the
variables values. The setter and getter methods are intended for
variables.
getOS
osVersion Version()

change
Version()
ABSTRACTION

Abstraction is the quality of dealing with ideas rather than events.

For example, when you consider the case of e-mail, complex details such as
what happens as soon as you send an e-mail, the protocol your e-mail server
uses are hidden from the user. Therefore, to send an e-mail you just need to
type the content, mention the address of the receiver, and click send.

Likewise in Object-oriented programming, abstraction is a process of hiding the


implementation details from the user, only the functionality will be provided to
the user (IDEA!). In other words, the user will have the information on what the
object does instead of how it does it.

In Java, abstraction is achieved using Abstract classes and interfaces.

“encapsulation is a realization of your desired abstraction” - Lokesh Gupta,


https://howtodoinjava.com/oops/encapsulation-in-java-and-its-relation-with-
abstraction/
A mobilePhone object
has OS version
can change OS version
can tell you what its version
Sources:

https://www.javatpoint.com/
https://www.tutorialspoint.com/
Farrell, Java Programming
METHOD
OVERLOADING
Prepared by: Meynard Soriano, CpE, MIT
Description
• This module will review you on static methods which you have
taken in your course Java 1. It progresses to method overloading
which is an important principle in OOP.
Objectives:
At the end of this module, the students must have:
1. defined what is method overloading, and
2. applied method overloading on static methods, mutators and
accessors.
•Let us review methods. We have
been using methods in the
previous modules. To strengthen
your knowledge in methods, the
succeeding slides will help you
recall what was discussed.
WHAT IS A METHOD?
• A method is a program module or block that
contains a series of statements that can be
carried out when called.

• Example:
➢main
➢constructors
➢mutators
➢accessors
WHO IS THE CALLER?
WHO WAS CALLED?
• To execute a method, you invoke or call it in
your program
• The act of calling a method makes a “method
call”.
• The method call invokes(to be executed by the
computer) the called method.
• The calling method is also known as a client
method. This is because a called method
provides a service for its client.
Illustration

Called
Client Method Method
Ex: Ex:
main(){ addAll(){
addAll(); …
} }
Guide questions in making a method:

•Who can access it?


•What information should I supply
my method?
•What will my method do?
•What will my method give back?
Example: This is a method
– the main
method.
public class ThisIsAClass{
public static void main(String [] args){
System.out.println(“#30 Brgy ABC");
System.out.println(“Baguio City");
System.out.println(“Philippines");
}
}

The main method prints a 3-liner house address


Example:
What if you want to print the address again?
public class ThisIsAClass{
public static void main(String [] args){
System.out.println(“#30 Brgy ABC");
System.out.println(“Baguio City");
System.out.println(“Philippines");

System.out.println(“#30 Brgy ABC");


System.out.println(“Baguio City");
System.out.println(“Philippines");
}
}
Effect:
Longer code and harder to maintain. What if you
want to change the number of the house? Or the
name of the barangay? Then you have to go
through all the lines of code that does that.
As a solution, we introduce
STATIC METHODS
public class ThisIsAClass{
public static void main(String [] args){

public static void printAddress(){


System.out.println(“#30 Brgy ABC");
System.out.println(“Baguio City");
System.out.println(“Philippines");
}

}
Now, let us call the method inside
the main method.
public class ThisIsAClass{
public static void main(String [] args){
printAddress();
}

public static void printAddress(){


System.out.println(“#30 Brgy ABC");
System.out.println(“Baguio City");
System.out.println(“Philippines");
}

}
To print the address twice:
public class ThisIsAClass{
public static void main(String [] args){
printAddress();
printAddress();
}

public static void printAddress(){


System.out.println(“#30 Brgy ABC");
System.out.println(“Baguio City");
System.out.println(“Philippines");
}

}
Effect:
• The code is shorter because it promotes
software or code reuse. The code is also easier
to maintain. Editing the number of the house
will require you to edit one line of code only.
Parts of a method
Return type
Method header
Method name

public static void printAddress(){


System.out.println(“#30 Brgy ABC");
System.out.println(“Baguio City");
System.out.println(“Philippines");
}

modifier Method body

Access specifier
Method Header
• A method header—A method’s header provides
information about how other methods can interact with
it. A method header is also called a declaration.

• It includes :
• The syntax (format = how to use)
• The parameter list
• The return type
• The method name
Method Body
• A method body between a pair of curly braces—The
method body contains the statements that carry out the
work of the method.
• A method’s body is called its implementation.
Technically, a method is not required to contain any
statements in its body, but you usually would have no
reason to create an empty method in a class.
• Sometimes, while developing a program, the
programmer creates an empty method as a placeholder
and fills in the implementation later. An empty method
is called a stub.
Access Specifier
• The access specifier for a Java method can be any of the
following modifiers: public, private, protected, or, if left
unspecified, package by default.
• public – if you want other methods and classes inside or
outside the package to use it
• private – if you want the method to be accessible inside
the class only
• package – if you want the method to be accessible
within the package( or the current project) only.
• protected – if you want the method or field to be
accessible not only to parent class but also child classes
static – a modifier keyword
• Aside from making the method in the example public, it
is also static.
• Making it static will not require you to instantiate an
object.

• If non-static (needs an object):


ThisIsAClass thisIsAnObject = new ThisIsAClass(); //instantatiation
thisIsAnObject.printAddress();
• If static:
printAddress();
or
ThisIsAClass.printAddress(); //same as System.out.println()
Return type
• A return type describes the type of data the method
sends back to its calling method.
• Not all methods return a value to their calling methods;
a method that returns no data has a return type of void.
• If it is not void, you should have a last statement return
inside your method
Arguments vs Parameters
Arguments:
(in calling a method, you provide an argument)

Parameters
(in the method header)
Example Method with one
parameter:
public class First
{
public static void main(String[] args)
{ argument
displayMessage(1);
System.out.println("First Java application");
parameter
}
public static void displayMessage(int x)
{
if(x==1) System.out.println(“You passed the value 1”);
else if(x==2) System.out.println(“You passed the value 2”);
}
}
Overloading a Method

•Overloading a method allows you to


use one identifier to execute diverse
tasks.
Overloading a Method

•In Java, it more specifically means


writing multiple methods in the same
scope that have the same name but
different parameter lists.
Overloading a Method
• In overloaded methods, the parameter
identifiers do not have to be different, but the
parameter lists must satisfy one or both of
these conditions:
• The lists must have different numbers of parameters.
For example, one list could have one double, another
list could have two doubles, and a third list could have
10 doubles.
• The lists must have parameter data types in different
orders. For example, one list could have two doubles,
another could have an int and a double, and a third
could have a double and an int. (caution with this)
Example overloaded method
public static void printAddress(){
System.out.println(“#30 Brgy ABC");
System.out.println(“Baguio City");
System.out.println(“Philippines");
}

public static void printAddress(int number){


System.out.println(“#” + number + “ Brgy ABC");
System.out.println(“Baguio City");
System.out.println(“Philippines");
}

public static void printAddress(int number, String brgy){


System.out.println(“#” + number + “ “+ brgy);
System.out.println(“Baguio City");
System.out.println(“Philippines");
}
Type conversion in methods
• The parameters are converted automatically whenever
possible. No syntax error is prompted.
• Example:
int integerNum = 5;
printDouble(integerNum);

public static void printDouble (double doubleNum){


….
}
Answer the following:

•Who can access it?


•What information should I supply
my method?
•What will my method do?
•What will my method give back?
Constructor
Overloading
prepared by M. Soriano
Rules on Overloading Methods

 write multiple methods in the same scope that have the same
name but different parameter lists
Example:
public static void overload(int a)
public static void overload(int a, double b)
public static void overload(String a)
Rules on Overloading Methods

 the parameter identifiers do not have to be different, but the parameter


lists must satisfy one or both of these conditions:
1. must have different numbers of parameters
Example:
public static void calculateInterest(int bal)
public static void calculateInterest(int bal, double rate)

2. must have parameter data types in different orders


Example:
public static void calculateInterest(char loanType, int bal)
public static void calculateInterest(int bal, char loanType)
Constructor Overloading

 The same rules in method overloading applies since


constructor is also a method.
Common errors and Ambiguity:
ERROR:
public static void computeBalance(double deposit)
public static void computeBalance(double withdrawal)
***overloaded but the same header

AMBIGOUS:
public static void calculateInterest(int bal, double rate)
public static void calculateInterest(double rate, int bal)
***overloaded, different order but computer will be
confused what to use in case there is parameter type
casting.
Example: calculateInterest(5,6); What will the
computer use? Method 1 or 2?
this vs this()
“this” reference

 used to access the instance variables shadowed by the


parameters
 You can ONLY use the this reference for instance
variables and NOT on static or class variables.

public void setAge( int age ){


this.age = age;
}
Constructor with Parameters

NO PARAMETER:
public class Employee{
private int empNum; Employee partTimeWorker =
new Employee();
Employee(){
empNum = 999;}
}

WITH PARAMATER:
public class Employee{
private int empNum; Employee partTimeWorker =
new Employee(881);
Employee(int num){
empNum = num;}
}
OVERLOADING CONSTRUCTORS

public class Employee{


private int empNum;

public Employee(int num){


empNum = num;}

public Employee(){
empNum = 999;}
}
“this()” constructor call
 Constructor calls can be chained, meaning, you can
call another constructor from inside another
constructor.
 Use the this() call for this type of chaining
 There are a few things to remember when using the
this constructor call:
 When using the this constructor call, IT MUST OCCUR AS THE
FIRST STATEMENT in a constructor
 It can ONLY BE USED IN A CONSTRUCTOR DEFINITION. The
this call can then be followed by any other relevant
statements.
Challenge: Try this first (30 mins).

 A constructor that accepts an int and a double


and assigns them the student number and
grade point average, respectively
 A constructor that accepts a double and
assigns it to the grade point average, but
initializes every student number to 999
 A constructor that accepts an int and assigns it
to the student number, but initializes every
grade point average to 0.0
 A default constructor that assigns 999 to every
student number and 0.0 to every grade point
average
Solution:
public class Student{
public class Student{
private int stuNum;
private int stuNum;
private double gpa; private double gpa;
Student (int num, double avg){
stuNum = num; Student (int num, double avg){
gpa = avg;} stuNum = num;
Student (double avg){ gpa = avg;}
stuNum = 999; Student (double avg){
gpa = avg;} this(999, avg);}

Student (int num){ Student (int num){


this(num, 0.0);}
stuNum = num;
Student(){
gpa = 0.0;}
this(999,0.0)}
Student(){
}
stuNum = 999;
gpa = 0.0}
}
}
static and final fields
 Fields declared to be static are not always final.
Conversely, final fields are not always static. In
summary:
 If you want to create a field that all instantiations of the
class can access, but the field value can change, then it
is static but not final.
public static int canBeUpdated;
 If you want each object created from a class to contain
its own final value, you would declare the field to be
final but not static, may be initialized it in the
constructor.
public final int canNotBeUpdated;
 If you want all objects to share a single non-changing
value, then the field is static and final.
public static final int b=5;
INHERITANCE
DESCRIPTION

• This module introduces inheritance. You will learn how to implement


polymorphism and software re-use through inheritance. It discusses
how to inherit a class, how constructors affect the inheriting subclass
and the use of the keyword super.
OBJECTIVES:

• At the end of this module, the students are expected to have


1. defined inheritance,
2. enumerated benefits of inheritance, and
3. used inheritance in a program.
INHERITANCE

• the ability to create classes that share the attributes and methods of
existing classes but with more specific features
• enables one class to acquire all the behaviors and attributes of
another class
• Superclass/ base class/ parent
– Any class above a specific class in the class hierarchy.
– Common attributes
• Subclass/ derived class/ child
– Any class below a specific class in the class hierarchy.
– Class that inherits from a base class.
– Unique attributes
INHERITANCE DEMO:

• We are tasked to design 4 phones. The base phone or the phone that
will be the flagship will be called S22. S22FE is the cheapest. S22+ is
bigger in screen and has more colors to choose from. S22Ultra is as
big as S22+ but has more powerful camera, more Ram and more
colors to choose from.

• Program with the instructor and decide the features of the phone.
The instructor will point out the purpose of inheritance.
BENEFITS OF INHERITANCE

• Once a behavior (method) is defined in a superclass, that behaviour is


automatically inherited by all subclasses.
• Thus, you can encode a method only once and they can be used by all
subclasses.
• A subclass only needs to implement the differences between itself and
the parent.
EXTENDING CLASSES
• To derive a class, use the extends keyword.

public class Person{



}

public class Student extends Person{



}
OVERRIDING SUPERCLASS
METHODS
• To override a field or method in a child class means to use the child’s
version instead of the parent’s version.
• Polymorphism - using the same method name to indicate different
implementations
– meaning “many forms”—many different forms of action take place, even
though you use the same word to describe the action.
public class Person{
public void display(){
System.out.println(“Person Display Method”);
}
}
public class Student extends Person{
@Override
public void display(){
System.out.println(“Student Display Method”);
}
}

public class DemoOvveriding {


public static void main(String[] args){
Student child = new Student();
child.display();
}
}
Note: This is just a demonstration
Output:
Student Display Method
CALLING CONSTRUCTORS
DURING INHERITANCE
• When you create any object, as in the following statement, you are
calling a constructor:
– SomeClass anObject = new SomeClass();
• When you instantiate an object that is a member of a subclass, you are
actually calling at least two constructors:
– the constructor for the base class and the constructor for the extended,
derived class.
• When you create any subclass object, the superclass constructor must
execute first, and then the subclass constructor executes.
public class ASuperClass{
public ASuperClass(){
System.out.println("In superclass constructor");
}
}

public class ASubClass extends ASuperClass{


public ASubClass(){
System.out.println("In subclass constructor");}
}

public class DemoConstructors{


public static void main(String[] args){
ASubClass child = new ASubClass();}
}

Output:
In superclass constructor
In subclass constructor
THE “SUPER” KEYWORD

• A subclass can also explicitly call a constructor of its immediate superclass.


• This is done by using the super constructor call.
• A super constructor call in the constructor of a subclass will result in the
execution of relevant constructor from the superclass, based on the
arguments passed.
• Ex:
public Student(){
super( "SomeName", "SomeAddress" );
System.out.println("Inside Student:Constructor");
}
• The super() call MUST OCCUR AS THE FIRST STATEMENT IN A
CONSTRUCTOR.
• The super() call can only be used in a constructor definition.
• This implies that the this() construct and the super() calls CANNOT
BOTH OCCUR IN THE SAME CONSTRUCTOR.
• Another use of super is to refer to members of the superclass (just like
the this reference ).
Ex:
public Student() {
super.name = “somename”;
super.address = “some address”;}
METHODS YOU CANNOT
OVERRIDE
1. Static methods
– A subclass cannot override methods that are declared static in the
superclass
2. Final methods
– A subclass cannot override methods that are declared final in the
superclass
3. Methods within final classes
– Cannot extend a final class
Exceptions

Prepared by: M. O. Soriano


Description

▪ In this module, the student will learn how to handle common errors during
runtime. It will define exceptions and errors then give some tips to handle the
different types of exceptions.

Prepared by: M. O. Soriano


Objectives

At the end of this lesson, the student must have


▪ defined exceptions
▪ differentiated exceptions from errors
▪ enumerated the different types of exceptions
▪ implemented exceptions in a program

Prepared by: M. O. Soriano


Exception

▪ An exception is an unexpected or error condition. The programs you write can


generate many types of potential exceptions:
▪ A program might issue a command to read a file from a disk, but the file does
not exist there.
▪ A program might attempt to write data to a disk, but the disk is full or
unformatted.
▪ A program might ask for user input, but the user enters an invalid data type.
▪ A program might attempt to divide a value by 0.
▪ A program might try to access an array with a subscript that is too large or too
small.

Prepared by: M. O. Soriano


▪ Exception handling is the name for the object-oriented
techniques that manage or resolve such errors.

▪ Runtime exceptions are unplanned exceptions that occur


during a program’s execution in contrast with syntax errors
that are discovered during program compilation.

▪ Java includes two basic classes of errors: Error and Exception.


Both of these classes descend from the Throwable class

Prepared by: M. O. Soriano


Exception vs Error

▪ The Error class represents more serious errors from which your program
usually cannot recover.
▪ For example, there might be insufficient memory to execute a program.
▪ Usually, you do not use or implement Error objects in your programs.
▪ A program cannot recover from Error conditions on its own.

▪ The Exception class comprises less serious errors that represent unusual
conditions that arise while a program is running and from which the program
can recover.
▪ For example, one type of Exception class error occurs if a program uses an
invalid array subscript value, and the program could recover by assigning a
valid value to the subscript variable.

Prepared by: M. O. Soriano


Exception Tree

Prepared by: M. O. Soriano


Error Tree

Prepared by: M. O. Soriano


import java.util.Scanner;
public class Division
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int numerator, denominator, result;
System.out.print("Enter numerator >> ");
numerator = input.nextInt();
System.out.print("Enter denominator >> ");
denominator = input.nextInt();
result = numerator / denominator;
System.out.println(numerator + " / " +
denominator + " = " + result);
}
}
Prepared by: M. O. Soriano
Normal Execution

Prepared by: M. O. Soriano


ArithmeticException: / by zero

Prepared by: M. O. Soriano


InputMismatchException

Prepared by: M. O. Soriano


Prepared by: M. O. Soriano
▪ The list of error messages after each attempted
execution is called a stack trace history list, or
more simply, a stack trace. (You might also hear the
terms stack backtrace or stack traceback.)
▪ The list shows each method that was called as the
program ran.

Prepared by: M. O. Soriano


Classic way of handling it:

if(denominator == 0)
System.out.println("Cannot divide by 0");
else {
result = numerator / denominator;
System.out.println(numerator + " / " +
denominator + " = " + result);
}

Prepared by: M. O. Soriano


Why Exceptions?

▪ Programs that can handle exceptions appropriately are said to be more fault
tolerant and robust.
▪ Fault-tolerant applications are designed so that they continue to operate,
possibly at a reduced level, when some part of the system fails.
▪ Robustness represents the degree to which a system is resilient to stress and
able to continue functioning.
▪ Even if you choose never to use object-oriented exception-handling techniques
in your own programs, you must understand them because built-in Java
methods will throw exceptions.

Prepared by: M. O. Soriano


Try-catch Block

▪In object-oriented terminology, you “try” a


procedure that might cause an error.
▪A method that detects an error condition
“throws an exception,” and
▪if you write a block of code that processes
the error, that block is said to “catch the
exception.”

Prepared by: M. O. Soriano


try

▪ A try block consists of the following elements:


1. The keyword try followed by a pair of curly braces
2. Executable statements lie between the curly braces, including
some statements that might cause exceptions

Prepared by: M. O. Soriano


▪ To handle a thrown exception, you can code one or more catch blocks
immediately following a try block.
▪ A catch block is a segment of code that can handle an exception that
might be thrown by the try block that precedes it.
▪ The exception might be one that is thrown automatically, or you might
explicitly write a throw statement.
▪ A throw statement is one that sends an Exception object out of a
block or a method so that it can be handled elsewhere.
▪ A thrown Exception can be caught by a catch block.
▪ Each catch block can “catch” one type of exception—that is, one
object of type Exception or one of its child classes.

Prepared by: M. O. Soriano


▪ You create a catch block by typing the following elements:
1. The keyword catch followed by a pair of parentheses
2. Between the parentheses, an Exception type and an identifier
for an instance
3. A pair of curly braces that contain statements that take the
actions you want to use to handle the error condition

Prepared by: M. O. Soriano


try
{
result = numerator / denominator;
System.out.println(numerator + " / " + denominator +
" = " + result);
}
catch(ArithmeticException mistake)
{
System.out.println("Arithmetic exception was thrown and
caught");
}
System.out.println("End of program");

Prepared by: M. O. Soriano


Prepared by: M. O. Soriano
Get the exception message

catch(ArithmeticException mistake)
{
System.out.println(mistake.getMessage());
}
System.out.println("End of program");

Prepared by: M. O. Soriano


finally

▪ When you have actions you must perform at the end of a try…catch sequence,
you can use a finally block.
▪ The code within a finally block executes regardless of whether the preceding
try block identifies an exception.
▪ Usually, you use a finally block to perform cleanup tasks that must happen
regardless of whether any exceptions occurred and whether any exceptions
that occurred were caught.

Prepared by: M. O. Soriano


A try catch WITHOUT runtime error

Prepared by: M. O. Soriano


A try catch WITH runtime error

Prepared by: M. O. Soriano


A try catch WITH uncatched runtime error

Prepared by: M. O. Soriano


A try catch WITH uncatched runtime error

with finally block

Prepared by: M. O. Soriano


Practice Exercises

▪ https://www.geeksforgeeks.org/types-of-exception-in-java-with-examples/

Practice the listed example. UNDERSTAND them. Then screenshot all


programs+output and place them all in a PDF file. Turn in your PDF.

Prepared by: M. O. Soriano


SCHOOL OF INFORMATION TECHNOLOGY

CPEPRO2 OBJECT-ORIENTED
PROGRAMMING

Prepared by: A Self-regulated Learning Module


Meynard O. Soriano

prepared by: MOS A Self-regulated Learning Module 1


MODULE 8 Java Swing
Time: 3 hours
About this lesson: This lesson introduces the use of Java Swing Class to create
Graphical User Interface (GUI).

Course Learning Outcomes:


At the end of this module, the students must have:
1. defined Java Swing,
2. enumerated Java Swing Subclasses or components, and
3. used Java Swing in a program

Computer programs usually are more user friendly and more fun to use when they contain
graphical user interface (GUI) components. GUI components are buttons, text fields, and other
components with which the user can interact. Java contains two sets of prewritten GUI components—
the Abstract Windows Toolkit (AWT) and Swing. AWT components are older, not as portable as
Swing components, and do not have a consistent appearance when used with different operating
systems.

Java Swing
• Java Swing is a part of Java Foundation Classes (JFC) that is used to create window-based
applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and entirely written
in java.
• Unlike AWT, Java Swing provides platform-independent and lightweight components.
• The javax.swing package provides classes or java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc. (javatpoint.com, 2018).

AWT
• The Abstract Window Toolkit (AWT) is Java's original platform-dependent windowing, graphics,
and user-interface widget toolkit, preceding Swing. The AWT is part of the Java Foundation
Classes (JFC)

Difference between AWT and Java Swing


Java AWT Java Swing
AWT components are platform-dependent. Java swing components are platform-independent.
AWT components are heavyweight. Swing components are lightweight.
AWT doesn't support pluggable look and Swing supports pluggable look and feel.
feel.
AWT provides less components than Swing. Swing provides more powerful components such as
tables, lists, scroll panes, color chooser, tabbed panes
etc.
AWT doesn't follows MVC(Model View Swing follows MVC.
Controller) where model represents data, view

prepared by: MOS A Self-regulated Learning Module 2


represents presentation and controller acts as
an interface between model and view.

Hierarchy of Java Swing classes

Commonly used Methods of Component class


The methods of Component class are widely used in java swing that are given below.
Method Description
public void add(Component c) add a component on another component.
public void setSize(int width,int height) sets size of the component.
public void setLayout(LayoutManager m) sets the layout manager for the
component.
public void setVisible(boolean b) sets the visibility of the component. It is by
default false.

JFrame
JFrame class is a type of container which inherits the java.awt.Frame class. JFrame works like the
main window where components like labels, buttons, textfields are added to create a GUI.There are
two ways to create a frame:
1. by creating the object of Frame class (association)
2. by extending Frame class (inheritance)
We can write the code of swing inside the main(), constructor or any other method.

prepared by: MOS A Self-regulated Learning Module 3


Creating the object of Frame class (association)
Create a class and name it DisplayAllComponents. Inside it, create the main method like the
sample code below. Make sure to import classes or packages the program requires as highlighted by
your IDE.

The JFrame is an object you instantiated inside your main method. The DisplayAllComponent is not
a JFrame subclass. Now try it in your IDE and describe the output. Screenshot the output and save it
in a Word document.

By extending Frame class (inheritance)


Create another class and name it InheritedJFrame. Let the InheritedJFrame class extend JFrame
(recall Inheritance topic). Make a constructor of the class which has one parameter called title which
is a String type then set-up the JFrame. Inside the constructor, type the following:

Now make a main method inside InheritedJFrame class. The main should look like this:

What you did is a class that inherited JFrame. You instantiated an object of type InheritedJFrame
inside your main method. This is the difference of association and inheritance. Now try it in your
IDE and describe the output. Screenshot the output and save it in a Word document.

Java JLabel
The object of JLabel class is a component for placing text in a container. It is used to display a
single line of read only text. The text can be changed by an application but a user cannot edit it
directly. It inherits JComponent class.

Commonly used Constructors:


Constructor Description
JLabel() Creates a JLabel instance with no image and with an empty string for
the title.
JLabel(String s) Creates a JLabel instance with the specified text.

prepared by: MOS A Self-regulated Learning Module 4


JLabel(Icon i) Creates a JLabel instance with the specified image.
JLabel(String s, Icon i, int Creates a JLabel instance with the specified text, image, and
horizontalAlignment) horizontal alignment.

Commonly used Methods:


Methods Description
String getText() It returns the text string that a label displays.
void setText(String text) It defines the single line of text this component
will display.
void setHorizontalAlignment(int alignment) It sets the alignment of the label's contents along
the X axis.
Icon getIcon() It returns the graphic image that the label displays.
int getHorizontalAlignment() It returns the alignment of the label's contents
along the X axis.

To try JLabel, encode the main method below inside your DisplayAllComponents class.

Now try it in your IDE and describe the output. Screenshot the output and save it in a Word
document.

JButton
The JButton class is used to create a labeled button that has platform independent
implementation. The application result in some action when the button is pushed. It inherits
AbstractButton class. To try JButton, edit the code above by including these lines of code after
f.add(l2).

prepared by: MOS A Self-regulated Learning Module 5


Now try it in your IDE and describe the output. Screenshot the output and save it in a Word
document.

FlowLayout
Rerun DisplayAllComponent’s main method. Now position the cursor to the rightmost edge of
the JFrame output and resize the frame going to the left. Describe what happened to the JButtons
and JLabels inside the JFrame. Screenshot the output and save it in a Word document. This layout is
called absolute and this is done by setting the layout to null.
Let us compare it with a layout controlled by the Layout Manager of Java. We will use the
layout FlowLayout. This is useful when placing components like JButtons and JLabels inside a
panel which is a container used to group components. To use the FlowLayout, change the line where
you set the layout to null (that is f.setLayout(null)) into f.setLayout(FlowLayout). The
practice is to group your components inside a JPanel (read on Jpanel vs JFrame) then use a
FlowLayout to out lay the components.

Now try it in your IDE and describe the output before and after resizing the JFrame. Screenshot the
output and save it in a Word document.

Handling Events – Button Click


Changing the state of an object is known as an event.
Example:
• clicks on button,
• dragging mouse
• closing a frame
• etc.

There must be a mechanism in your program to handle such events. They are called event handlers.

To handle an event:
1. Register the component with a listener.
Button
public void addActionListener(ActionListener a){}
MenuItem
public void addActionListener(ActionListener a){}
TextField
public void addActionListener(ActionListener a){}
public void addTextListener(TextListener a){}

prepared by: MOS A Self-regulated Learning Module 6


TextArea
public void addTextListener(TextListener a){}
Checkbox
public void addItemListener(ItemListener a){}
Choice
public void addItemListener(ItemListener a){}
List
public void addActionListener(ActionListener a){}
public void addItemListener(ItemListener a){}

2. Put the event handler in any of the following:


1. Within class

2. Other class

3. Anonymous class

Using Anonymous class: Insert the code below after f.add(b1);

b1.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
l1.setText("Button Clicked!");
}
});

Now try it in your IDE and describe the output. Screenshot the output and save it in a Word
document.

ASSIGNMENT:
Read on 1 and 2 of putting the event handler (Within Class and Other Class) then demonstrate.

prepared by: MOS A Self-regulated Learning Module 7


REFERENCES:

JavaTpoint.com. (2018). Java Swing Tutorial. https://www.javatpoint.com/java-swing.

prepared by: MOS A Self-regulated Learning Module 8


Prepared by: Meynard Soriano, MIT
▪ This Module introduces Threads. It defines what is a thread and
discusses the life cycle of a Java Thread. It also gives details on
what happens when a thread or multiple threads run. Lastly, it
gives example of programs implementing threads.
At the end of the module, the students must have”
1. differentiated multi-processing from multi-threading,
2. enumerated the life cycle of a thread,
3. differentiated threads via inheritance from threads via
interface, and
4. used threads in a program.
▪ Multitasking is a process of executing
multiple tasks simultaneously.
▪ We use multitasking to utilize the CPU.
▪ Multitasking can be achieved in two ways:
1. Process-based Multitasking (Multiprocessing)
2. Thread-based Multitasking (Multithreading)
▪ Multithreading in java is a process
of executing multiple threads
simultaneously.
▪ A thread is a lightweight sub-
process, the smallest unit of
processing.
▪ Java Multithreading is mostly used
in games, animation, etc.

https://www.javatpoint.com/images/java-multithreading.png
▪ Process-based Multitasking (Multiprocessing)
1. Each process has an address in memory. In other words, each
process allocates a separate memory area.
2. A process is heavyweight.
3. Cost of communication between the process is high.
4. Switching from one process to another requires some time
for saving and loading registers, memory maps, updating
lists, etc.
▪ Thread-based Multitasking (Multithreading)
1. Threads share the same address space.
2. A thread is lightweight.
3. Cost of communication between the thread is low.
▪ A thread can be in one of the five states. According to sun, there
is only 4 states in thread life cycle in java new, runnable, non-
runnable and terminated. There is no running state.
▪ New
▪ Runnable
▪ Running
▪ Non-Runnable (Blocked)
▪ Terminated
A thread can be in one of the following states:
▪ NEW – a thread that has not yet started is in this state.
▪ RUNNABLE – a thread executing in the Java virtual
machine is in this state.
▪ BLOCKED – a thread that is blocked waiting for a
monitor lock is in this state.
▪ WAITING – a thread that is waiting indefinitely for
another thread to perform a particular action is in this
state.
▪ TIMED_WAITING – a thread that is waiting for another
thread to perform an action for up to a specified
waiting time is in this state.
▪ TERMINATED- a thread that has exited is in this state.

A thread can be in only one state at a given point


in time. These states are virtual machine states
which do not reflect any operating system thread
states.
▪ There are two ways to create a thread:
1. By extending Thread class
2. By implementing Runnable interface.
▪ Thread class provides constructors and
methods to create and perform operations on
a thread. Thread class extends Object class
and implements Runnable interface.
▪ Commonly used Constructors of Thread
class:
1. Thread()
2. Thread(String name)
3. Thread(Runnable r)
4. Thread(Runnable r, String name)
▪ public void run(): is used to perform action for a thread.
▪ public void start(): starts the execution of the thread. JVM calls the
run() method on the thread.
▪ public void sleep(long miliseconds): Causes the currently executing
thread to sleep (temporarily cease execution) for the specified number
of milliseconds.
▪ public void join(): waits for a thread to die.
▪ public void join(long miliseconds): waits for a thread to die for the
specified miliseconds.
▪ public int getPriority(): returns the priority of the thread.
▪ public int setPriority(int priority): changes the priority of the thread.
▪ public String getName(): returns the name of the thread.
▪ public void setName(String name): changes the name of the thread.
▪ public Thread currentThread(): returns the reference of currently
executing thread.
▪ public int getId(): returns the id of the thread.
▪ public Thread.State getState(): returns the state of the thread.
▪ public boolean isAlive(): tests if the thread is alive.
▪ public void yield(): causes the currently executing thread object to
temporarily pause and allow other threads to execute.
▪ public void suspend(): is used to suspend the thread(deprecated).
▪ public void resume(): is used to resume the suspended
thread(deprecated).
▪ public void stop(): is used to stop the thread(deprecated).
▪ public boolean isDaemon(): tests if the thread is a daemon thread.
▪ public void setDaemon(boolean b): marks the thread as daemon
or user thread.
▪ public void interrupt(): interrupts the thread.
▪ public boolean isInterrupted(): tests if the thread has been
interrupted.
▪ public static boolean interrupted(): tests if the current thread has
been interrupted.
▪ An interface is an abstract "class" that is used to group related methods
with "empty" bodies:
▪ To access the interface methods, the interface must be "implemented"
by another class with the implements keyword (instead of extends). The
body of the interface method is provided by the "implement" class.
(W3Schools, 2022)

// interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void sleep(); // interface method (does not have a body)
}
▪ The Runnable interface should be implemented by any class
whose instances are intended to be executed by a thread.
Runnable interface have only one method named run().

public void run(): is used to perform action for a thread.


▪ start() method of Thread class is used to start
a newly created thread. It performs following
tasks:
1. A new thread starts(with new callstack).
2. The thread moves from New state to the
Runnable state.
3. When the thread gets a chance to execute, its
target run() method will run.
class Sample extends Thread{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Sample t1=new Sample();
t1.start();
}
}
class Sample implements Runnable{
public void run(){
System.out.println("thread is running...");
}

public static void main(String args[]){


Sample m1 = new Sample();
Thread t1 = new Thread(m1);
t1.start();
}
}
▪ Thread scheduler in java is the part of the JVM that decides
which thread should run.
▪ There is no guarantee that which runnable thread will be
chosen to run by the thread scheduler.
▪ Only one thread at a time can run in a single process.
▪ The thread scheduler mainly uses preemptive or time slicing
scheduling to schedule the threads.
▪ Under preemptive scheduling,
▪ the highest priority task executes until it enters the waiting or dead
states
▪ or a higher priority task comes into existence.

▪ Under time slicing,


▪ a task executes for a predefined slice of time and then reenters the
pool of ready tasks.
▪ the scheduler then determines which task should execute next,
based on priority and other factors.
▪ The sleep() method of Thread class is used to sleep a thread for
the specified amount of time.
▪ The Thread class provides two methods for sleeping a thread:
▪ public static void sleep(long miliseconds)throws InterruptedException
▪ public static void sleep(long miliseconds, int nanos)throws InterruptedException
class TestSleep extends Thread{
public void run(){
for(int i=1;i<5;i++){
try{Thread.sleep(500);}
catch(InterruptedException e){System.out.println(e);}
System.out.println(i);
}
}
public static void main(String args[]){
TestSleep t1=new TestSleep();
TestSleep t2=new TestSleep();
t1.start();
t2.start();
}
}
▪ Each thread starts in a separate call stack.
▪ Invoking the run() method from main thread, the run() method
goes onto the current call stack rather than at the beginning of
a new call stack.
▪ Stopping a Java Thread requires some preparation of your thread
implementation code.
▪ The Java Thread class contains a stop() method, but it is
deprecated.
▪ The original stop() method would not provide any guarantees
about in what state the thread was stopped. That means, that all
Java objects the thread had access to during execution would be
left in an unknown state. If other threads in your application also
has access to the same objects, your application could fail
unexpectedly and unpredictably.

▪ Instead of calling the stop() method you will have to implement


your thread code so it can be stopped.
▪ Here is an example of a class that implements Runnable which contains
an extra method called doStop() which signals to the Runnable to stop.
The Runnable will check this signal and stop when it is ready to do so.

public class MyRunnable implements Runnable {


private boolean doStop = false;
public synchronized void doStop() {
this.doStop = true;
}
private synchronized boolean keepRunning() {
return this.doStop == false;
}
@Override
public void run() {
while(keepRunning()) {
// keep doing what this thread should do.
System.out.println("Running");
try {Thread.sleep(3L * 1000L);}
catch (InterruptedException e){}
}
}
}
public class MyRunnableMain {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();

try {Thread.sleep(10L * 1000L);}


catch (InterruptedException e) {}

myRunnable.doStop();
}
}
https://www.javatpoint.com/multithreading-in-java
https://www.tutorialspoint.com/java/java_multithreading.htm
https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.Stat
e.html
https://www.w3schools.com/java/ref_keyword_implements.asp
SCHOOL OF INFORMATION TECHNOLOGY

CPEPRO2 OBJECT-ORIENTED
PROGRAMMING

Prepared by: A Self-regulated Learning Module


Meynard O. Soriano

prepared by: MOS A Self-regulated Learning Module 1


MODULE 9 File Input/Output
Time: 3 hours
About this lesson: This module discusses java.io package we need to perform input
from and output to (I/O) in Java. It also describes streams
representing an input source and an output destination.

Course Learning Outcomes:


At the end of this module, the students must have:
1. defined a stream,
2. enumerated Java I/O packages, and
3. used Java I/O in a program

The java.io package contains nearly every class we might ever need to perform input and
output (I/O) in Java. All these streams represent an input source and an output destination. The
stream in the java.io package supports many data such as primitives, object, localized characters,
etc. (Java - Files and I/O - Tutorialspoint, n.d.).
Stream
A stream is a series of data. There are two types of stream – the InPutStream amd the
OutPutStream and they provide a good support such as methods, classes and pre-defined constants
which a programmer can readily use.
1. InPutStream – this is used to read data from a source
2. OutPutStream – this is used for writing data into a destination

Some Java Stream:


1. Byte Streams – for 8-bits bytes. Example classes are FileInputStream and FileOutputStream.
2. Character Streams – Java Character streams are used to perform input and output for 16-bit
unicode. Though there are many classes related to character streams but the most frequently
used classes are FileReader and FileWriter.
3. Standard Streams – All the programming languages provide support for standard I/O where
the user's program can take input from a keyboard and then produce an output on the
computer screen. Java provides the following three standard streams −
a. Standard Input − This is used to feed the data to user's program and usually a keyboard
is used as standard input stream and represented as System.in.
b. Standard Output − This is used to output the data produced by the user's program and
usually a computer screen is used for standard output stream and represented as
System.out.
c. Standard Error − This is used to output the error data produced by the user's program
and usually a computer screen is used for standard error stream and represented as
System.err.

prepared by: MOS A Self-regulated Learning Module 2


4. FileInputStream – this stream is used for reading data from the files. Objects can be created
using the keyword new and there are several types of constructors available.
5. FileOutputStream – this is used to create a file and write data into it. The stream would
create a file, if it doesn't already exist, before opening it for output.
FileInputStream
The following are sample of constructors we can use:

InputStream f = new FileInputStream("C:/java/cpepro2File1")


or
File f = new File("C:/java/ cpepro2File1");
InputStream f = new FileInputStream(f);

Helper Methods:

Sr.No. Method & Description

1 public void close() throws IOException{}


This method closes the file output stream. Releases any system
resources associated with the file. Throws an IOException.

2 protected void finalize()throws IOException {}


This method cleans up the connection to the file. Ensures that the close
method of this file output stream is called when there are no more
references to this stream. Throws an IOException.

3 public int read(int r)throws IOException{}


This method reads the specified byte of data from the InputStream.
Returns an int. Returns the next byte of data and -1 will be returned if it's
the end of the file.

4 public int read(byte[] r) throws IOException{}


This method reads r.length bytes from the input stream into an array.
Returns the total number of bytes read. If it is the end of the file, -1 will be
returned.

5 public int available() throws IOException{}


Gives the number of bytes that can be read from this file input stream.
Returns an int.

FileOutputStream
Here are two constructors which can be used to create a FileOutputStream object.

prepared by: MOS A Self-regulated Learning Module 3


Following constructor takes a file name as a string to create an input stream object to write the file −
OutputStream f = new FileOutputStream("C:/java/cpepro2File1")
or
File f = new File("C:/java/cpepro2File1");
OutputStream f = new FileOutputStream(f);

Helper Methods:

Sr.No. Method & Description

1 public void close() throws IOException{}


This method closes the file output stream. Releases any system
resources associated with the file. Throws an IOException.

2 protected void finalize()throws IOException {}


This method cleans up the connection to the file. Ensures that the close
method of this file output stream is called when there are no more
references to this stream. Throws an IOException.

3 public void write(int w)throws IOException{}


This methods writes the specified byte to the output stream.

4 public void write(byte[] w)


Writes w.length bytes from the mentioned byte array to the OutputStream.

Example:
import java.io.*;

public class Module9Sample {


public static void main(String args[]) {
try {
int[] data= {11,21,3,40,65};
OutputStream outputStream = new FileOutputStream("cpepro2.txt");
for(int x = 0; x < data.length ; x++) {
outputStream.write( data[x] );
}
outputStream.close();

InputStream inputStream = new FileInputStream("cpepro2.txt");


int size = inputStream.available();
for(int i = 0; i < size; i++) {
System.out.print((char)inputStream.read() + " ");
}
inputStream.close();
} catch (IOException e) {

prepared by: MOS A Self-regulated Learning Module 4


System.out.print("Exception occurred");
}
}
}

Java File Handling


The File class from the java.io package, allows us to work with files. To use the File class, create an
object of the class, and specify the filename or directory name:

Example
import java.io.File; // Import the File class

File myObj = new File("filename.txt"); // Specify the filename

The File class has many useful methods for creating and getting information about files. For example:

Method Type Description

canRead() Boolean Tests whether the file is readable or not

canWrite() Boolean Tests whether the file is writable or not

createNewFile() Boolean Creates an empty file

delete() Boolean Deletes a file

exists() Boolean Tests whether the file exists

getName() String Returns the name of the file

getAbsolutePath() String Returns the absolute pathname of the file

length() Long Returns the size of the file in bytes

list() String[] Returns an array of the files in the directory

mkdir() Boolean Creates a directory

prepared by: MOS A Self-regulated Learning Module 5


REFERENCES

Java - Files and I/O - Tutorialspoint. (n.d.). www.tutorialspoint.com.


https://www.tutorialspoint.com/java/java_files_io.htm

prepared by: MOS A Self-regulated Learning Module 6

You might also like