You are on page 1of 83

Debre Markos University Burie Campus

Department of Computer Science

Object Oriented Programming Teaching Material


(CoSc 2051)

Prepared By: Robel Mamo (MSc)

February 2022
Preface

This teaching material is prepared in support of the Object Oriented Programming Curriculum.
The course emphasizes the methodology of programming from an object-oriented perspective
and software engineering principles. The objectives of the course are: to explain the basic object
oriented concepts, to successfully code, debug and run programs with appropriate development
environment, to work on more advanced programs, and to have clear differentiation between
structural and object oriented programming paradigms.

Dear students, in chapter one you have been studied about Types of programming paradigms
Overview of OO principles, and Editing, Compiling and Interpreting.

In chapter two, Defining a class, Creating an Object, Instantiating and using objects, Printing to
the Console, Methods and Messages, Parameter Passing, Comparing and Identifying Objects,
Destroying Objects, Enumerated Types, Instance fields, Constructors and Methods, Access
Modifiers, and Encapsulation.

In chapter three, you have been studied about Inheritance Casting, Method Overriding and
Overloading, Polymorphism, Super, The Object Class, Abstract Classes, Interfaces, and Using
Interfaces.

In chapter four, Exceptions Overview, Catching Exceptions, The finally Block, Exception
Methods, Declaring Exceptions, Defining and Throwing Exceptions, Errors and Runtime
Exceptions.

Chapter five is about Packages, The import Statement, Static Imports, CLASSPATH and Import,
Defining Packages, and Package Scope.

Chapter six is about The Set, Set Implementation Classes, The List, List Implementation Classes,
The Queue, Queue Implementation Classes, and Map/ dictionary.

i
Table of Contents
Chapter One: Introduction to Object-Oriented Programming ...................................................................... 1
1.1. Types of Programming Paradigm ................................................................................................. 1
1.2. Overview of OO Principles ........................................................................................................... 2
1.3. Editing, Compiling and Interpreting ............................................................................................. 6
Chapter One Review Questions ................................................................................................................ 8
Chapter Two: Objects and Classes................................................................................................................ 9
2.1. Defining a Class ............................................................................................................................ 9
2.2. Creating an Object ...................................................................................................................... 10
2.3. Instantiating and Using Objects .................................................................................................. 10
2.3.1. Printing to the Console ........................................................................................................ 10
2.3.2. Methods and Messages ....................................................................................................... 10
2.3.3. Parameter Passing ............................................................................................................... 11
2.3.4. Comparing and Identifying Objects .................................................................................... 11
2.3.5. Destroying Objects .............................................................................................................. 12
2.3.6. Enumerated Types............................................................................................................... 13
2.4. Instance Fields ............................................................................................................................ 14
2.5. Constructors and Methods .......................................................................................................... 15
2.6. Access Modifiers ........................................................................................................................ 18
2.7. Encapsulation .............................................................................................................................. 18
Chapter Two Review Questions ............................................................................................................. 21
Chapter Three: Inheritance and Polymorphism .......................................................................................... 22
3.1. Inheritance................................................................................................................................... 22
3.2. Casting ........................................................................................................................................ 25
3.3. Method Overriding and Overloading .......................................................................................... 26
3.4. Polymorphism ............................................................................................................................. 30
3.5. Super ........................................................................................................................................... 31
3.6. The Object class .......................................................................................................................... 33
3.7. Abstract class .............................................................................................................................. 34
3.8. Interfaces ..................................................................................................................................... 34
3.9. Using Interfaces .......................................................................................................................... 35
Chapter Three Review Questions ........................................................................................................... 37

ii
Chapter Four: Exception Handling ............................................................................................................. 38
4.1. Exceptions Overview .................................................................................................................. 38
4.2. Catching Exceptions ................................................................................................................... 40
4.3. The finally Block ........................................................................................................................ 41
4.4. Exception Methods ..................................................................................................................... 42
4.5. Declaring Exceptions .................................................................................................................. 43
4.6. Defining and Throwing Exceptions ............................................................................................ 43
4.7. Errors and Runtime Exceptions .................................................................................................. 45
Chapter Four Review Questions ............................................................................................................. 48
Chapter Five: Packages ............................................................................................................................... 49
5.1. Packages ...................................................................................................................................... 49
5.2. The Import Statement.................................................................................................................. 50
5.3. Static Imports .............................................................................................................................. 51
5.4. CLASSPATH.............................................................................................................................. 52
5.5. Defining Packages ...................................................................................................................... 52
5.6. Package Scope ............................................................................................................................ 53
Chapter Five Review Questions.............................................................................................................. 54
Chapter Six: Data Structures ....................................................................................................................... 55
6.1. The set ......................................................................................................................................... 55
6.2. Set Implementation Classes ........................................................................................................ 55
6.3. The List ....................................................................................................................................... 65
6.4. List Implementation Classes ....................................................................................................... 66
6.5. The stack ..................................................................................................................................... 70
6.6. Stack Implementation Classes .................................................................................................... 71
6.7. The Queue ................................................................................................................................... 75
6.8. Queue Implementation Classes ................................................................................................... 75
6.9. Map/Dictionary ........................................................................................................................... 77
Chapter Six Review Questions ............................................................................................................... 79

iii
Chapter One: Introduction to Object-Oriented Programming

Software development is dynamic and always undergoing major change. The methods we will
use in the future no doubt will differ significantly from those currently in practice. System
development refers to all activities that go into producing an information system solution.
System development activities consist of system analysis, design, implementation, testing and
maintenance. Software process describes how the work is to be carried out to achieve the original
goal based on the system requirements.

1.1. Types of Programming Paradigm

Object-oriented system development methods differ from traditional development techniques in


that the traditional techniques view software as a collection of programs (or functions) and
isolated data. The traditional approach focuses on the functions of the system while object-
oriented system development centers on the object, which combines data and functionality. In
structured approach, applications are developed in which data is separate from function. The
main concept behind object-oriented paradigm is that instead of defining systems as two separate
parts, define systems as a collection of interacting objects. Objects do things (that is, they have
functionality) and they know things (they have data).

During the 1970s and into the 80s, the primary software engineering methodology was structured
programming. It was based on the following advice: To solve a large problem, break the problem
into several pieces and work on each piece separately; To solve each piece, treat it as a new
problem which can itself be broken down into smaller problems; eventually, you will work your
way down to problems that can be solved directly, without further decomposition. This approach
is called top-down programming. There is nothing wrong with top-down programming. It is a
valuable and often-used approach to problem-solving. However, it is incomplete. Top-down
programming doesn’t give adequate consideration to the data that the program manipulates.
Another problem with strict top-down programming is that it makes it difficult to reuse work
done for other projects. Producing high-quality programs is difficult and expensive.

In bottom-up design, the approach is to start “at the bottom,” with problems that you already
know how to solve. From there, you can work upwards towards a solution to the overall

1
problem. It uses reusable components in a modular way. A module is a component of a larger
system that interacts with the rest of the system in a simple, well-defined, straightforward
manner. One common format for software modules is to contain some data, along with some
sub-routines for manipulating that data. Data can only be manipulated in known, well-defined
ways that leads to the concept of data or information hiding. This latest approach is called object-
oriented programming, often abbreviated as OOP. The central concept of object-oriented
programming is the object, which is a kind of module containing data and subroutines. The
point-of-view in OOP is that an object is a kind of self-sufficient entity that has an internal state
(the data it contains) and that can respond to messages (calls to its subroutines).

Activity 1.1

 Explain the types of programming paradigm?


 Explain the central concept of object-oriented programming?

1.2. Overview of OO Principles

The object-oriented system development is a software development strategy based on the idea of
building systems from reusable components called objects. Objects are instances of classes and
can be easily replaced, modified, and reused. A class is a generic representation of similar objects
that interact with each other. Each object has attributes (data) and methods (functions). Object-
oriented approach first proposed in the late 1960s. Throughout 1990s it becomes the paradigm
choice. In OO approach a running program can be seen as a collection of objects collaborating to
perform a given task. Consider an example of a real world object chair. It is a member (instance)
of furniture. Generic attributes can be associated with every object in the class furniture. Among
the many possible attributes furniture has cost, dimension, weight, location, and color. These can
be applied also for table, sofa, etc. and the attributes can be reused. The same is true also for the
operations.

The fundamental difference between the object-oriented systems and the traditional is the way in
which you approach problems. The traditional approach is either algorithm centric or data

2
centric. In an algorithm centric, you think of an algorithm that can accomplish the task, then
build data structures for that algorithm to use. In a data centric, you think how to construct the
data, then build the algorithm around structure. In an object-oriented system, however, the
algorithm and the data structures are packaged together as an object, which has a set of attributes
and methods. For example, a car has certain attributes, such as color, year, model, and price, and
can perform a number of operations, such as go, stop, turn left, and turn right.

Why an object-orientation

Object-oriented methods enable us to create sets of objects that work together to produce
software that better model their problem domains than similar systems produced by traditional
techniques. The systems are easier to adapt to changing requirements, easier to maintain, more
robust, and promote greater reuse.

Higher level of abstraction: the OO approach supports abstraction at the object level. Abstraction
is a view of a problem that extracts the essential information relevant to a particular purpose and
ignores the remaining of the information. Abstraction reduces complexity and increase
efficiency.

Seamless transition among different phases of software development: reduce the level of
complexity and redundancy and makes for clearer, more robust system development.

Encouragement of good programming techniques: a class in an object-oriented system carefully


delineates between its interface and the implementation of that interface. The object-oriented
method tends to promote clearer designs, which are easier to implement.

Improved software development productivity: object-oriented programming is modular, as it


provides separation of duties in object-based program development. It is also extensible, as
objects can be extended to include new attributes and functions. Objects can also be reused
within an across applications. Because of these three factors; modularity, extensibility, and
reusability object-oriented provides improved software development productivity over the
traditional techniques.

Faster development: reuse enables faster development

3
Lower cost of development: reuse also lowers the cost of development.

The principles of encapsulation and data hiding help the developer to develop systems that
cannot be tempered by other parts of the system.

It allows effective management of software complexity by the virtue of modularity.

With the concept of high cohesiveness we can implement systems which can be easily
maintained

Overview of Java Programming and Types of Java Program

Java is the world’s most widely used computer programming language. Java programming
language was originally developed by Sun Microsystems which was initiated by James Gosling
and released in 1995 as core component of Sun Microsystems' Java platform (Java1.0). Java is
the preferred language for meeting many organizations’ enterprise programming needs. Java has
also become the language of choice for implementing Internet-based applications and software
for devices that communicate over a network. In use today are more than a billion general-
purpose computers and billions more Java-enabled cell phones, smartphones and handheld
devices (such as tablet computers). Java is guaranteed to be Write Once, Run Anywhere.

Properties of Java

Object Oriented: In Java, everything is an Object. Java can be easily extended since it is based on
the Object model.

Platform Independent: Unlike many other programming languages including C and C++, when
Java is compiled, it is not compiled into platform specific machine, rather into platform
independent byte code. This byte code is distributed over the web and interpreted by the Virtual
Machine (JVM) on whichever platform it is being run on.

Simple: Java is designed to be easy to learn. If you understand the basic concept of OOP Java, it
would be easy to master.

Secure: With Java's secure feature it enables to develop virus-free, tamper-free systems.
Authentication techniques are based on public-key encryption.

4
Architecture-neutral: Java compiler generates an architecture-neutral object file format, which
makes the compiled code executable on many processors, with the presence of Java runtime
system.

Portable: Being architecture-neutral and having no implementation dependent aspects of the


specification makes Java portable.

Robust: Java makes an effort to eliminate error prone situations by emphasizing mainly on
compile time error checking and runtime checking.

Multithreaded: With Java's multithreaded feature it is possible to write programs that can
perform many tasks simultaneously. This design feature allows the developers to construct
interactive applications that can run smoothly.

Interpreted: Java byte code is translated on the fly to native machine instructions and is not
stored anywhere. The development process is more rapid and analytical since the linking is an
incremental and light-weight process.

High Performance: With the use of Just-In-Time compilers, Java enables high performance.

Distributed: Java is designed for the distributed environment of the internet.

Dynamic: Java is considered to be more dynamic than C or C++ since it is designed to adapt to
an evolving environment. Java programs can carry extensive amount of run-time information
that can be used to verify and resolve accesses to objects on run-time.

Definition of Java Application and Java Applets

Java is used to develop java applications and java applets. Java application is a program that runs
using Java interpreter. An applet is a Java program that runs in a Web browser. An applet can be a
fully functional Java application because it has the entire Java API at its disposal.

Java is used in such a broad spectrum of applications that it has two other editions. The Java
Enterprise Edition (Java EE) is geared toward developing large-scale, distributed networking
applications and web-based applications. Today’s applications can be written with the aim of
communicating among the world’s computers via the Internet and the web. The Java Micro

5
Edition (Java ME) is geared toward developing applications for small, memory-constrained
devices, such as BlackBerry smartphones. Google’s Android operating system used on numerous
smartphones, tablets (small, lightweight mobile computers with touch screens), e-readers and
other devices—uses a customized version of Java not based on Java ME.

Activity 1.2

 Explain objects and classes?


 Explain why object-orientation?
 Explain properties of Java programming?

1.3. Editing, Compiling and Interpreting

Java programs normally go through five phases: edit, compile, load, verify and execute in the
context of the Java SE Development Kit (JDK). You can download the most up-to-date JDK and
its documentation from www.oracle.com. You type a Java program (typically referred to as
source code) using the editor, make any necessary corrections and save the program on a
secondary storage device, such as your hard drive. A file name ending with the .java extension
indicates that the file contains Java source code.

Popular Java Editors

To write your Java programs, you will need a text editor. There are even more sophisticated IDEs
available in the market. But for now, you can consider one of the following:
Notepad: On Windows machine, you can use any simple text editor like Notepad.
Netbeans: A Java IDE that is open-source and free which can be downloaded from
https://htmlhttps://www.netbeans.org/index.html
Eclipse: A Java IDE developed by the eclipse open-source community and can be downloaded
from https://www.eclipse.org/

Compiling a Java Program into Bytecodes: you use the command javac (the Java compiler) to
compile a program. For example, to compile a program called Welcome.java, type javac

6
Welcome.java then the Java compiler translates Java source code into bytecodes that represent
the tasks to execute in the execution phase. Bytecodes are executed by the Java Virtual Machine.
(JVM). JVM is a part of the JDK and the foundation of the Java platform. A virtual machine
(VM) is a software application that simulates a computer but hides the underlying operating
system and hardware from the programs that interact with it. If the same VM is implemented on
many computer platforms, applications that it executes can be used on all those platforms. The
JVM is one of the most widely used virtual machines. Bytecodes are platform independent. They
do not depend on a particular hardware platform. So, Java’s bytecodes are portable i.e. without
recompiling the source code, the same bytecodes can execute on any platform containing a JVM
that understands the version of Java in which the bytecodes were compiled. The JVM is invoked
by the java command. For example, to execute a Java application called Welcome, type the
command java Welcome

Loading a Program into Memory: The JVM places the program in memory to execute it and this
is known as loading.

Bytecode Verification: In Phase 4, as the classes are loaded, the bytecode verifier examines their
bytecodes to ensure that they’re valid and do not violate Java’s security restrictions. Java
enforces strong security to make sure that Java programs arriving over the network do not
damage your files or your system (as computer viruses and worms might).

Execution: the JVM executes the program’s bytecodes, thus performing the actions specified by
the program . In early Java versions, the JVM was simply an interpreter for Java bytecodes. This
caused most Java programs to execute slowly, because the JVM would interpret and execute one
bytecode at a time. Today’s JVMs typically execute bytecodes using a combination of
interpretation and so-called just-in-time (JIT) compilation. In this process, the JVM analyzes the
bytecodes as they’re interpreted, searching for hot spots i.e. parts of the bytecodes that execute
frequently. For these parts, a just-in-time (JIT) compiler known as the Java HotSpot compiler
translates the bytecodes into the underlying computer’s machine language.

7
Chapter One Review Questions

1. What is the difference between top-down and bottom-up programming approaches?


2. Discuss the characteristics of object-oriented paradigm?
3. Java is platform independent. What does it mean?
4. Explain the types of Java program?
5. Discuss the phases of Java programming?

8
Chapter Two: Objects and Classes

Java is an Object-Oriented Language. As a language that has the Object-Oriented feature, Java
supports the following fundamental concepts:
 Polymorphism
 Inheritance
 Encapsulation
 Abstraction
 Classes
 Objects
 Instance
 Method
 Message Passing

The term object means a combination of data and function that represents some real-world entity.
Classes are used to distinguish one type of object from another. A class is a set of objects that
share a common structure and a common behavior; a single object is simply an instance of a
class. The chief role of a class is to define the properties and procedures of its instances.
Attributes (object state and properties) properties represent the state of an object. They are often
referred as class data. Object behavior is described in methods or procedures. A method
implements the behavior of an object. Basically, a method is a function or procedure that is
defined for a class and typically can access the internal state of an object of that class to perform
some operation. Each procedure defines and describes a particular behavior of an object. For
example getColor extract the color stored in the color attribute. Messages are the means by
which objects interact. Sending a message to an object means asking the object to execute or
invoke one of its methods. This is only possible, if the method is actually known to the object.
Different objects can respond to the same message in different ways. For example, cars,
motorcycles, and bicycles will all respond to a stop message, but the actual operations performed
are object specific.

2.1. Defining a Class

To define a class the class keyword is followed by the name of the new type. For example:

9
class ClassTypeName {
/*class body goes here*/
}
This introduces a new class type, although the class body consists only of a comment (the stars
and slashes and what is inside, which will be discussed later in this chapter)

2.2. Creating an Object

To create an object of that class type use the new keyword as follows:
ClassTypeName obj = new ClassTypeName();
But you cannot tell it to do much of anything (that is, you cannot send it any interesting
messages) until you define some methods for it.

Activity 2.1

 Define a class called Mammal?


 Create an object from the class you define above?

2.3. Instantiating and Using Objects


2.3.1. Printing to the Console

Printing to the console refers to writing the output of a Java program to the console. The methods
used for streaming output are defined in the PrintStream class. The methods used for writing
console output are print(), println() and write(). The print() and println() methods are widely used
to direct the output to the console. Both these methods are used with the help of the System.out
stream.

2.3.2. Methods and Messages

In many languages (like C and C++), the term function is used to describe a named subroutine.
The term that is more commonly used in Java is method, as in “a way to do something.” Methods
in Java determine the messages an object can receive. Messages are the means by which objects
interact. Sending a message to an object means asking the object to execute or invoke one of its
10
methods. This is only possible, if the method is actually known to the object. The fundamental
parts of a method are the name, the arguments, the return type, and the body. Here is the basic
form:

ReturnType methodName( /* Argument list */ ) {


/* Method body */
}

2.3.3. Parameter Passing

The return type describes the value that comes back from the method after you call it. The
argument list gives the types and names for the information that you want to pass into the
method. The method name and argument list (which is called the signature of the method)
uniquely identify that method.

A method can be called only for an object, and that object must be able to perform that method
call. If you try to call the wrong method for an object, you’ll get an error message at compile
time. You call a method for an object by naming the object followed by a period (dot), followed
by the name of the method and its argument list, like this:
objectName.methodName(arg1, arg2, arg3);

For example, suppose you have a method display( ) that takes no arguments and returns a value
of type int. Then, if you have an object called obj for which display( ) can be called, you can say
this: int x = obj.display();

The type of the return value must be compatible with the type of x. This act of calling a method
is commonly referred to as sending a message to an object. In the preceding example, the
message is display() and the object is obj. Object-oriented programming is often summarized as
simply “sending messages to objects.”

2.3.4. Comparing and Identifying Objects

Comparing objects is an essential feature of object-oriented programming languages. Let's begin


with the == and != operators that can tell if two Java objects are the same or not, respectively.

11
For primitive types, being the same means having equal values. If two integers have different
values, the == operator would return false, while the != operator would return true.

Integer a = new Integer(1);

Integer b = new Integer(1);

a == b is false because by comparing two objects, the value of those objects is not 1. Rather it is
their memory addresses in the stack that are different since both objects were created using
the new operator. If we had assigned a to b, then we would've had a different result:

Integer a = new Integer(1);

Integer b = a;

a == b is true

Now, let's see what happens when we're using the Integer valueOf method:

Integer a = Integer.valueOf(1);
Integer b = Integer.valueOf(1);
a == b is true
In this case, they are considered the same. This is because the valueOf() method stores
the Integer in a cache to avoid creating too many wrapper objects with the same value.
Therefore, the method returns the same Integer instance for both calls. This method is defined in
the Object class so that every Java object inherits it.

Comparing using equals() method:


Integer a = new Integer(1);
Integer b = new Integer(1);
a.equals(b) is true

2.3.5. Destroying Objects

One critical issue when working with objects is the way they are created and destroyed. Each
object requires resources, most notably memory, in order to exist. When an object is no longer
needed it must be cleaned up or destroyed so that these resources are released for reuse. Java
uses dynamic memory allocation, exclusively. Every time you want to create an object, you use

12
the new operator to build a dynamic instance of that object. Java provides a feature called a
garbage collector that automatically discovers when an object is no longer in use and destroys it.
The garbage collector “knows” when an object is no longer in use, and it then automatically
releases the memory for that object.

2.3.6. Enumerated Types

Enumerated types are a common enough need that C, C++, and a number of other languages
have always had them. Java has enum, too, and it’s much more full-featured than what you find
in C/C++. Here’s a simple example:
public enum Spiciness {
NOT, MILD, MEDIUM, HOT, FLAMING
}
This creates an enumerated type called Spiciness with five named values. Because the instances
of enumerated types are constants, they are in all capital letters by convention (if there are
multiple words in a name, they are separated by underscores). To use an enum, you create a
reference of that type and assign it to an instance:
public class SimpleEnumUse {
public static void main(String[] args) {
Spiciness howHot = Spiciness.MEDIUM;
System.out.println(howHot);
}
}
The compiler automatically adds useful features when you create an enum. For example, it
creates a toString() so that you can easily display the name of an enum instance, which is how
the print statement above produced its output.
The compiler also creates an ordinal() method to indicate the declaration order of a particular
enum constant, and a static values() method that produces an array of values of the enum
constants in the order that they were declared:
public class EnumOrder {
public static void main(String[] args) {
for(Spiciness s : Spiciness.values())

13
System.out.println(s + ", ordinal " + s.ordinal());
}
}

2.4. Instance Fields

When you define a class, you can put two types of elements in your class: fields (sometimes
called data members), and methods (sometimes called member functions). Here is an example of
a class with some fields:
class DataOnly {
int i;
double d;
boolean b;
}
You can create an object like this:
DataOnly data = new DataOnly();

You can assign values to the fields, but you must first know how to refer to a member of an
object. This is accomplished by stating the name of the object reference, followed by a period
(dot), followed by the name of the member inside the object: objectReference.member
For example:
data.i = 47;
data.d = 1.1;
data.b = false;

It is also possible that your object might contain other objects that contain data you’d like to
modify. For this, you just keep “connecting the dots.” For example:
myPlane.leftTank.capacity = 100;
When a primitive data type is a member of a class, it is guaranteed to get a default value if you
do not initialize it: for example the default value of int is 0. It’s best to always explicitly initialize
your variables. The DataOnly class cannot do much of anything except hold data, because it has
no methods. To understand how those work, you must first understand arguments and return
values. A class can contain any of the following variable types:

14
Local variables: Variables defined inside methods, constructors or blocks are called local
variables. The variable will be declared and initialized within the method and the variable will be
destroyed when the method has completed.

Instance variables: Instance variables are variables within a class but outside any method. These
variables are initialized when the class is instantiated. Instance variables can be accessed from
inside any method, constructor or blocks of that particular class.

Class variables: Class variables are variables declared within a class, outside any method, with
the static keyword.

Activity 2.2

 What are the methods used to print result to console?


 What are messages?
 How to destroy objects?

2.5. Constructors and Methods

A constructor initializes an object when it is created. It has the same name as its class and is
syntactically similar to a method. However, constructors have no explicit return type. Typically,
you will use a constructor to give initial values to the instance variables defined by the class, or
to perform any other start-up procedures required to create a fully formed object. All classes
have constructors, whether you define one or not, because Java automatically provides a default
constructor that initializes all member variables to zero. However, once you define your own
constructor, the default constructor is no longer used. A class can have more than one
constructor.
Java allows two types of constructors namely:
 No argument Constructors
 Parameterized Constructors

15
No argument Constructors
As the name specifies the no argument constructors of Java does not accept any parameters
instead, using these constructors the instance variables of a method will be initialized with fixed
values for all objects. Example:
public class MyClass {
Int num ;
MyClass() {
num =100;
}
}

Parameterized Constructors
Most often, you will need a constructor that accepts one or more parameters. Parameters are
added to a constructor in the same way that they are added to a method, just declare them inside
the parentheses after the constructor's name. Example:
public class MyClass {
int x ;
MyClass(int i ){
x=i;
}
}

The static keyword

If you want to have only a single piece of storage for a particular field or if you need a method
that isn’t associated with any particular object of this class. You can achieve both of these effects
with the static keyword. When you say something is static, it means that particular field or
method is not tied to any particular object instance of that class. To make a field or method static,
you simply place the keyword before the definition. For example, the following produces a static
field and initializes it:
class StaticTest {
static int i = 47;
}

16
At this point, any objects have the same value of 47 since they refer to the same piece of
memory. You define a static method in a similar way:
class Incrementable {
static void increment() {
StaticTest.i++;
}
}

There are two ways to refer to a static variable or method. You can refer using the object of that
class. You can also refer to it directly through its class name, something you cannot do with a
non-static member. Using the class name is the preferred way to refer to a static variable. Not
only does it emphasize that variable’s static nature, but in some cases it gives the compiler better
opportunities for optimization.

final Instance Variables

You can use the keyword final to specify that a variable is not modifiable (i.e., it’s a constant)
and that any attempt to modify it is an error. For example:
private final int INCREMENT;
declares a final (constant) instance variable INCREMENT of type int. Such variables can be
initialized when they’re declared. If they are not, they must be initialized in every constructor of
the class. Initializing constants in constructors enables each object of the class to have a different
value for the constant. If a final variable is not initialized in its declaration or in every
constructor, a compilation error occurs.

this keyword

Every object can access a reference to itself with keyword this (sometimes called the this
reference). When a non-static method is called for a particular object, the method’s body
implicitly uses keyword this to refer to the object’s instance variables and other methods. For
example:
class SimpleTime {
private int hour;
private int minute;

17
private int second;
public SimpleTime( int hour, int minute, int second ){
this.hour = hour;
this.minute = minute;
this.second = second;
}

2.6. Access Modifiers

The Java access modifiers public, protected, and private are placed in front of each definition for
each member in your class, whether it’s a field or a method. If you don’t provide an access
modifier, it means “package access.” So one way or another, everything has some kind of access
control.
Package access: all the other classes in the current package have access to that member, but to all
the classes outside of this package, the member appears to be private. Package access allows you
to group related classes together in a package so that they can easily interact with each other.

Public access: members are available to everyone. Everybody, everywhere, can access them.

Private access: no one can access that member except the class that contains that member, inside
methods of that class. Other classes in the same package cannot access private members.

Protected access: deals with a concept called inheritance (the mechanism that permits new class
to be created out of existing classes by extending and refining its capabilities). An inherited class
can access a protected member as well as a public member (but not private members). It can
access package-access members only if the two classes are in the same package.

2.7. Encapsulation

Encapsulation: the process of binding both attributes and methods together within a class.
Through encapsulation, the internal details of a class can be hidden from outside.

Data hiding: typically, a class is designed such that its data can be accessed only by its class
methods and insulated from direct outside access. This process of insulating an object’s data is
called data hiding.

18
To achieve encapsulation in Java declare the variables of a class as private and Provide public
setter and getter methods to modify and view the variables values. Following is an example that
demonstrates how to achieve Encapsulation in Java:
public class EncapTest {
private String name;
private String idNum;
private int age;
public int getAge (){
return age;
}
public String getName (){
return name ;
}
public String getIdNum (){
return idNum;
}
public void setAge(int newAge ){
Age = newAge;
}
public void setName(String newName){
Name = newName ;
}
public void setIdNum (String newId) {
idNum = newId;
}
}
The public setXXX() and getXXX() methods are the access points of the instance variables of
the EncapTest class. Normally, these methods are referred as getters and setters. Therefore, any
class that wants to access the variables should access them through these getters and setters. The
variables of the EncapTest class can be accessed using the following program:
public class RunEncap{

19
public static void main(String args []){
EncapTest encap = new EncapTest();
encap.setName(“Abebe");
encap.setAge(20);
encap.setIdNum(“01x");
System.outout.println(("Name : " + encap.getName()+ “Age : " +encap .getAge();)
}
}

Activity 2.3

 Explain the types of Java constructors?


 Explain the types of Java access modifiers?
 Explain the concept of encapsulation?

20
Chapter Two Review Questions

1. Define a sample class with its member data and methods?


2. Show the three types of variable in the defined class?
3. Create a constructor in the defined class?
4. Which Java access modifier is related to inheritance and how it works?
5. What mean by data hiding?

21
Chapter Three: Inheritance and Polymorphism

3.1. Inheritance

Inheritance is the mechanism that permits new class to be created out of existing classes by
extending and refining its capabilities. The existing classes are called the base classes /parent
classes/ super-classes, and the new classes are called the derived classes /child classes/ sub-
classes. The sub-class can inherit or derive the attributes and methods of the super-class(es)
provided that the super-class allows so. Besides, the subclass may add its own attributes and
methods.

Inheritance defines an “is-a” relationship. Example from a class mammal, a number of classes
can be derived such as Human, Cat, Dog, Cow, etc. Humans, Cats, Dogs, and Cows all have the
distinct characteristics of mammals. In addition, each has its own particular characteristics. It can
be said that a cat “is-a” mammal. With inheritance, you can save time during program
development by basing new classes on existing proven and debugged high-quality software. This
also increases the likelihood that a system will be implemented and maintained effectively.
Syntax
public class (subclass-name) extends (existing-class-name) {
// Changes and additions.
}
extends is the keyword used to inherit the properties of a class. With the use of the extends
keyword, the subclasses will be able to inherit all the properties of the superclass except for the
private properties of the superclass. Following is an example demonstrating Java inheritance. In
this example, you can observe two classes namely Calculation and My_Calculation. Using
extends keyword, the My_Calculation inherits the methods addition() and Subtraction() of
Calculation class.

class Calculation {
int z;
public void addition (int x ,int y ){
z=x+y;
System.out.println("The sum of the given numbers:"+z);

22
}
public void Subtraction(int x ,int y ){
z=x-y;
System.out.println("The difference between the given numbers:"+z);
}
}
public class My_Calculation extends Calculation {
public void multiplication (int x , int y ){
z=x*y;
System.out.println("The product of the given numbers:"+z);
}
public static void main (String args []){
int a =20, b =10;
My_Calculation demo =new My_Calculation();
demo .addition(a,b);
demo .Subtraction(a, b);
demo .multiplication(a, b);
}
}

In the given program, when an object to My_Calculation class is created, a copy of the contents
of the superclass is made within it. That is why, using the object of the subclass you can access
the members of a superclass. A subclass inherits all the members from its superclass.
Constructors are not members, so they are not inherited by subclasses, but the constructor of the
superclass can be invoked from the subclass. The Superclass reference variable can hold the
subclass object, but using that variable you can access only the members of the superclass, so to
access the members of both classes it is recommended to always create reference variable to the
subclass. Example:
Calculation demo = new My_Calculation();
demo.addition(a,b);
demo.Subtraction(a,b);

23
Types of Inheritance

Single Inheritance: a subclass derives from a single super-class.

Multiple Inheritance: a subclass derives from more than one super-class.

Multilevel Inheritance: a subclass derives from a super-class which in turn is derived from
another class and so on.

Hierarchical Inheritance: a class has a number of subclasses each of which may have subsequent
subclasses, continuing for a number of levels, so as to form a tree structure.

24
A very important fact to remember is that Java does not support multiple inheritance. Therefore
following example is illegal:
public class extends Animal,Mammal{}
However, a class can implement one or more interfaces, which has helped Java get rid of the
impossibility of multiple inheritance.

Activity 3.1

 What mean by inheritance in programming?


 What are the advantages of inheritance?
 Explain the types of inheritance?

3.2. Casting

In Java, type casting is a method or process that converts a data type into another data type in
both ways Narrowing Casting (manually) and Widening Casting (automatically). The automatic
conversion is done by the compiler and manual conversion performed by the programmer.
Widening Casting (automatically): converting a smaller type to a larger type size. Widening
casting is done automatically when passing a smaller size type to a larger size type. Example:
public class Main {
public static void main(String[] args) {
int intType = 4;
double doubleType = intType; // Automatic casting: int to double
System.out.println(intType); // Outputs 4
System.out.println(doubleType); // Outputs 4.0
}

25
}
Narrowing Casting (manually): converting a larger type to a smaller size type. Narrowing casting
must be done manually by placing the type in parentheses in front of the value. Example:
public class Main {
public static void main(String[] args) {
double doubleType = 4.23d;
int intType = (int) doubleType; // Manual casting: double to int
System.out.println(doubleType); // Outputs 4.23
System.out.println(intType); // Outputs 4
}
}

3.3. Method Overriding and Overloading

Overriding: In object-oriented terms, overriding means to override the functionality of an


existing method. The benefit of overriding is: ability to define a behavior that's specific to the
subclass type, which means a subclass can implement a parent class method based on its
requirement. Example:
class Animal {
public void move () {
System.outout.println("Animals can move");
}
}
class Dog extends Animal{
public void move (){
System.outout.println("Dogs can walk and run");
}
}
public class TestDog{
public static void main (String args []) {
Animal a = new Animal(); //Animal reference and object Animal
Animal b = new Dog(); //Animal reference but Dog object

26
a.move(); //runs the method in Animal class
b.move(); //runs the method in Dog class
}
}
The above program works successfully
Consider the next example
class Animal {
public void move (){
System.outout.println("Animals can move“);
}
}
class Dog extends Animal{
public void move (){
System.outout.println(("Dogs can walk and run");
}
}
public void bark (){
System.outout.println("Dogs can bark");
}
}
public class TestDog {
public static void main (String args []) {
Animal a = new Animal();// Animal reference and object Animal
Animal b = new Dog(); // Animal reference but Dog object
a.move(); // runs the method in Animal class
b.move();// runs the method in Dog class
b.bark();
}
}

27
This program will throw a compile time error since b's reference type Animal doesn't have a
method by the name of bark. When invoking a superclass version of an overridden method the
super keyword is used. Example:
class Animal{
public void move () {
System.outout.println("Animals can move“);
}
}
class Dog extends Animal {
public void move (){
super.move(); // invokes the super class method
System.outout.println("Dogs can walk and run");
}
}
public class TestDog {
public static void main (String args []) {
Animal b = new Dog(); // Animal reference but Dog object
b.move(); // runs the method in Dog class
}
}

Rules for Method Overriding

 The argument list should be exactly the same as that of the overridden method.
 The return type should be the same as the return type declared in the original overridden
method in the superclass.
 The access level cannot be more restrictive than the overridden method's access level. For
example: If the superclass method is declared public then the overridding method in the
sub class cannot be either private or protected.
 Instance methods can be overridden only if they are inherited by the subclass.
 A method declared final cannot be overridden.
 Constructors cannot be overridden.

28
Overloading: Circle and Square have similar calculateArea() method in their class definition.
Although both methods have the same method name, they have different method
implementation, since the formula for calculating area of each is not the same. The ability to use
the same name for two or more methods in a class is known as operation overloading in object-
oriented terms. Methods having the same method signature may pose problems in the
compilation process depending on where they are used in the program.

Two methods are said to have the same method signature if the name of the methods are the
same; and the number and type of formal parameters are the same.

In the code fragment below, method A() is overloaded by A(int x), A(int x, int y), and A(String
s). These four methods are distinguished in the compilation process by the number and type of
parameters present in the method call.
class A {
...
A() { ... }
A(int x) { ... }
A(int x, int y) { ... }
A(String x) { ... }
...
}
The return type of a method does not distinguish overloaded methods from one another.
However, declaring methods of the same signature in different classes are considered as valid in
object-oriented programming.

Activity 3.2

 Show an example casting?


 What mean by overriding?
 Explain method overloading?

29
3.4. Polymorphism

Polymorphism is a Greek word that means the ability to take multiple forms. In object-oriented
paradigm, polymorphism implies using operation in different ways, depending upon the
instances they are operating upon. Polymorphism enables you to “program in the general” rather
than “program in the specific.” In particular, polymorphism enables you to write programs that
process objects that share the same superclass. The most common use polymorphism in OOP
occurs when a parent class reference is used to refer to a child class object. Any Java object that
can pass more than one IS-A test is considered to be polymorphic.
Example 1
public interface Vegetarian{}
public class Animal{}
public class Deer extends Animal implements Vegetarian{}
Now, the Deer class is considered to be polymorphic since this has multiple inheritance.
Following are true for the above example:
A Deer IS-A Animal
A Deer IS-A Vegetarian
A Deer IS-A Deer
A Deer IS-A Object
When we apply the reference variable facts to a Deer object reference, the following declarations
are legal:
Deer d = new Deer();
Animal a = d;
Vegetarian v =d;
Object o =d;
All the reference variables d, a, v, o refer to the same Deer object

Example 2
If class Rectangle is derived from class Quadrilateral, then a Rectangle object is a more specific
version of a Quadrilateral. Any operation (e.g., calculating the perimeter or the area) that can be
performed on a Quadrilateral can also be performed on a Rectangle. These operations can also be
performed on other Quadrilaterals, such as Squares, Parallelograms and Trapezoids. The

30
polymorphism occurs when a program invokes a method through a superclass Quadrilateral
variable at execution time, the correct subclass version of the method is called, based on the type
of the reference stored in the superclass variable.

Polymorphism enables you to deal in generalities and let the execution-time environment handle
the specifics.

Polymorphism promotes extensibility: Software that invokes polymorphic behavior is


independent of the object types to which messages are sent. New object types that can respond to
existing method calls can be incorporated into a system without modifying the base system.

Polymorphism also increases code readability since the same message is used to call different
objects to perform the appropriate behavior.

3.5. Super

The super keyword is similar to this keyword. Following are the scenarios where the super
keyword is used.
 It is used to differentiate the members of superclass from the members of subclass, if they
have same names.
 It is used to invoke the superclass constructor from subclass.
If a class is inheriting the properties of another class. And if the members of the superclass have
the names same as the sub class, to differentiate these variables we use super keyword as shown
below.
super.variable;
super.method();

In the given program, you have two classes namely Sub_class and Super_class, both have a
method named display() with different implementations, and a variable named num with
different values. We are invoking display() method of both classes and printing the value of the
variable num of both classes. Here you can observe that we have used super keyword to
differentiate the members of superclass from subclass.
class Super_class {
int num = 20;

31
//display method of superclass
public void display () {
System.outout.println("This is the display method of superclass");
}
}
public class Sub_class extends Super_class{
int num =10;
//display method of sub class
public void display (){
System.outout.println("This is the display method of subclass");
}
public void my_method (){
//Instantiating subclass
Sub_class sub= new Sub_class();
//Invoking the display() method of sub class
sub.display();
//Invoking the display() method of superclass
super.display();
//printing the value of variable num of subclass
System.outout.println("value of the variable named num in sub class:”+ subsub.num);
//printing the value of variable num of superclass
System.outout.println("value of the variable named num in super class:”+ super.num)
}
public static void main (String args []) {
Sub_class obj = new Sub_class();
obj.my_method();
}
}

Invoking Superclass Constructor

32
If a class is inheriting the properties of another class, the subclass automatically acquires the
default constructor of the superclass. But if you want to call a parameterized constructor of the
superclass, you need to use the super keyword as shown below.
super(values);

The following program contains a superclass and a subclass, where the superclass contains a
parameterized constructor which accepts an integer value, and we used the super keyword to
invoke the parameterized constructor of the superclass.
class Superclass {
int age ;
Superclass(int age ){
this.age = age;
}
public void getAge() {
System.outout.println("The value of the variable named age in super class is: " +age)
}
}
public class Subclass extends Superclass {
Subclass(int age ){
Super(age);
}
public static void main (String args []) {
Subclass s = new Subclass(24);
s.getAge();
}
}

3.6. The Object class

A class that is not explicitly declared to be a subclass of some other class is automatically made a
subclass of the standard class Object.
public class myClass { . . . }
is exactly equivalent to

33
public class myClass extends Object { . . .}
Since every class is a subclass of Object, a variable of type Object can refer to any object
whatsoever, of any type. Java has several standard data structures that are designed to hold
Objects, but since every object is an instance of class Object, these data structures can actually
hold any object whatsoever.

3.7. Abstract class

You create an abstract class when you want to manipulate a set of classes through its common
interface. A class containing abstract methods is called an abstract class. If a class contains one or
more abstract methods, the class itself must be qualified as abstract. An abstract class is one that
is not used to construct objects, but only as a basis for making subclasses. An abstract class exists
only to express the common properties of all its subclasses. Abstract method is a method that is
incomplete; it has only a declaration and no method body. The body is in subclass of the abstract
class.
Syntax
abstract void add( );

3.8. Interfaces

The interface keyword takes the concept of abstractness one step further. The abstract
keyword allows you to create one or more undefined methods in a class. You provide part of
the interface without providing a corresponding implementation. The implementation is
provided by inheritors. The interface keyword produces a completely abstract class, one
that provides no implementation at all. It allows the creator to determine method names,
argument lists, and return types, but no method bodies. An interface provides only a form,
but no implementation.

An interface says, "All classes that implement this particular interface will look like this."
Thus, any code that uses a particular interface knows what methods might be called for that
interface, and that’s all. So the interface is used to establish a "protocol" between classes.
However, an interface is more than just an abstract class taken to the extreme, since it allows
you to perform a variation of "multiple inheritance" by creating a class that can be upcast to
more than one base type.

34
3.9. Using Interfaces

To create an interface, use the interface keyword instead of the class keyword. As with a
class, you can add the public keyword before the interface keyword (but only if that
interface is defined in a file of the same name). If you leave off the public keyword, you get
package access, so the interface is only usable within the same package. An interface can also
contain fields, but these are implicitly static and final.

To make a class that conforms to a particular interface, use the


implements keyword, which says, "The interface is what it looks like, but now I’m going to
say how it works." Other than that, it looks like inheritance. Once you have implemented an
interface, that implementation becomes an ordinary class that can be extended in the regular
way. You can choose to explicitly declare the methods in an interface as public, but they are
public even if you don’t say it. So when you implement an interface, the methods from the
interface must be defined as public. Otherwise, they would default to package access, and
you are reducing the accessibility of a method during inheritance, which is not allowed by
the Java compiler. Note that every method in the interface is strictly a declaration, which is the
only thing the compiler allows.

public interface Furniture {


// Compile-time constant:
int QUANTITY = 5; // static & final
// Cannot have method definitions:
void setColor(); // Automatically public
}
public class Sofa implements Furniture {
@Override
public void setColor() {
System.out.println("Blue");
}
public void getColor() {
this.setColor();
}
35
}
public class Table extends Sofa implements Furniture {
@Override
public void setColor() {
System.out.println("Brown");
}
}
In the above example the class Sofa implements the interface Furniture and the class Table
extends the class Sofa and implements the interface Furniture. Here there is multiple inheritance
in the class Table.
Sofa obj=new Sofa();
Table obj2=new Table();
obj.getColor(); //returns Blue
obj2.getColor(); //returns Brown

Activity 3.3

 Explain polymorphism?
 What are abstract classes?
 Explain interface and its uses?

36
Chapter Three Review Questions

1. Discuss inheritance with real world example?


2. Discuss polymorphism with real world example?
3. Explain the use of super keyword?
4. Explain what Object class is?
5. How multiple inheritance achieved in Java show with example

37
Chapter Four: Exception Handling

4.1. Exceptions Overview

An exception is a problem that arises during the execution of a program. When an Exception
occurs the normal flow of the program is disrupted and the program terminates abnormally,
which is not recommended, therefore, these exceptions are to be handled. An exception can
occur for many different reasons. Following are some scenarios where an exception occurs.
 A user has entered an invalid data.
 A file that needs to be opened cannot be found.
 A network connection has been lost in the middle of communications or the JVM has run
out of memory.
Some of these exceptions are caused by user error, others by programmer error, and others by
physical resources that have failed in some manner. The goals for exception handling in Java are
to simplify the creation of large, reliable programs, and to do so with more confidence that your
application doesn’t have an unhandled error.

Categories of Exceptions

Checked exceptions: A checked exception is an exception that is checked (notified) by the


compiler at compilation-time, these are also called as compile time exceptions. These exceptions
cannot simply be ignored, the programmer should take care of (handle) these exceptions.
Compile-time errors occur when there are syntactical issues present in application code, for
example, missing semicolons or parentheses, misspelled keywords or usage of undeclared
variables. These syntax errors are detected by the Java compiler at compile-time and an error
message is displayed on the screen. The compiler prevents the code from being executed until
the error is fixed. Therefore, these errors must be addressed by debugging before the program
can be successfully run. For example: if you use FileReader file class in your program to read
data from a file, if the file specified in its constructor doesn't exist, then a
FileNotFoundException occurs, and the compiler prompts the programmer to handle the
exception.
Example:
import java .io.File;

38
import java.io.FileReader;
Public class FilenotFound_Demo {
public static void main (String args []){
File file = new File("E://file.txt");
FileReader fr =new FileReader(file);
}
}
In the above program if the file specified is not found then it will generate
FileNotFoundException.

Unchecked exceptions: An unchecked exception is an exception that occurs at the time of


execution. These are also called as Runtime Exceptions. These include programming bugs, such
as logic errors or improper use of an API. Runtime exceptions are ignored at the time of
compilation. For example: if you have declared an array of size 5 in your program, and trying to
call the 6 element of the array then an ArrayIndexOutOfBoundsException exception occurs.
Example:
public class Unchecked_Demo {
public static void main (String args []) {
int num [] = {1,2,3, 4};
System.out.println(num[5]);
}
}
If you compile and execute the above program, you will get ArrayIndexOutOfBoundsException

Activity 4.1

 What mean by exception in programming?


 What are checked and unchecked exceptions explain their difference?

39
4.2. Catching Exceptions

All exception classes are subtypes of the java.lang.Exception class. The Exception class is a
subclass of the Throwable class. Other than the Exception class there is another subclass called
Error which is derived from the Throwable class. The Exception class has two main subclasses:
IOException class and RuntimeException Class. A method catches an exception using a
combination of the try and catch keywords. A try/catch block is placed around the code that
might generate an exception. Code within a try/catch block is referred to as protected code, and
the syntax for using try/catch looks like the following:
Syntax
try {
// Protected code
}
catch (ExceptionName e1) {
// Catch block
}
The code which is prone to exceptions is placed in the try block. When an exception occurs, that
exception occurred is handled by catch block associated with it. Every try block should be
immediately followed either by a catch block or finally block. A catch statement involves
declaring the type of exception you are trying to catch. If an exception occurs in protected code,
the catch block (or blocks) that follows the try is checked. If the type of exception that occurred
is listed in a catch block, the exception is passed to the catch block.
Example:
The following is an array declared with 2 elements. Then the code tries to access the 3 of element
of the the array which throws an exception.
import java .io.*;
public class ExcepTest {
public static void main (String args []) {
try {
int a [] = new int[2];
System.outout.println(“Access element three :" + a [3]);
} catch(ArrayIndexOutOfBoundsException e ){

40
System.outout.println("Exception thrown :" + e );
}
System.outout.println("Out of the block");
}
}
This will produce the following output
Exception thrown: java.lang.ArrayIndexOutOfBoundsException: 3 Out of the block

A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks
like the following:
Syntax
try {
// Protected code
} catch (ExceptionType1 e1) {
// Catch block
} catch (ExceptionType2 e2) {
// Catch block
} catch (ExceptionType3 e3) {
// Catch block
}
You can have any number of catch blocks after a single try. If an exception occurs in the
protected code, the exception is thrown to the first catch block in the list. If the data type of the
exception thrown matches ExceptionType1, it gets caught there. If not, the exception passes
down to the second catch statement. This continues until the exception either is caught or falls
through all catches.

4.3. The finally Block

The finally block follows a try block or a catch block. A finally block of code always executes,
irrespective of occurrence of an Exception. Using a finally block allows you to run any cleanup-
type statements that you want to execute, no matter what happens in the protected code. A finally
block appears at the end of the catch blocks and has the following syntax:
Syntax

41
try {
// Protected code
} catch (ExceptionType1 e1) {
// Catch block
} catch (ExceptionType2 e2) {
// Catch block
} catch (ExceptionType3 e3) {
// Catch block
}finally {
// The finally block always executes.
}

Note the following:

 A catch clause cannot exist without a try statement.


 It is not compulsory to have finally clauses whenever a try/catch block is present.
 The try block cannot be present without either catch clause or finally clause.
 Any code cannot be present in between the try, catch, finally blocks.

4.4. Exception Methods

public String getMessage(): Returns a detailed message about the exception that has occurred.
public Throwable getCause(): Returns the cause of the exception.
public String toString(): Returns the name of the class concatenated with the result of
getMessage().
public void printStackTrace(): Prints the result of toString().
public StackTraceElement [] getStackTrace(): Returns an array containing each element on the
stack trace.
public Throwable fillInStackTrace(): Fills the stack trace of this Throwable object with the
current stack trace.

42
Activity 4.2

 Discuss how to catch an exception?


 Explain the use of finally block in caching exception?

4.5. Declaring Exceptions

Java’s built-in exceptions don’t always provide the information we need. So, we sometimes need
to supplement these exceptions with our own. A custom exception gives you more control to
provide extra data about the problem and to handle the exception in your code. You can create
your own exceptions in Java which are called User-defined Exceptions. Apart from the built in
exceptions Java provides, exception classes can be written by the programmer. These can then be
thrown like the built-in Java exceptions. Keep the following points in mind when writing your
own exception classes:
 All exceptions must be a child of Throwable.
 If you want to write a checked exception that is automatically enforced by the Handle or
Declare Rule, you need to extend the Exception class.
 If you want to write a runtime exception, you need to extend the RuntimeException class.
We can define our own Exception class as below:
class MyException extends Exception { //for checked exceptions
}
modifier MyException extends RuntimeException { //for runtime exceptions
}

4.6. Defining and Throwing Exceptions

It is important to understand how to throw exceptions in Java. This will allow you to create
higher quality code where errors are checked at compile time instead of runtime, and create
custom exceptions that make debugging and recovery easier. Throwing an exception is as simple
as using the "throw" statement. You then specify the Exception object you wish to throw. Every
Exception includes a message which is a human-readable error description. It can often be

43
related to problems with user input, server, backend, etc. Here is an example that shows how to
throw an exception:
throw new Exception("Exception message");

The Throws keyword

If a method does not handle a checked exception, the method must declare it using the throws
keyword. The throws keyword appears at the end of a method's signature. A method can declare
that it throws more than one exception, in which case the exceptions are declared in a list
separated by commas. The throws keyword allows the compiler to help you write code that
handles this type of error, but it does not prevent the abnormal termination of the program. With
the help of the throws keyword, we can provide information to the caller of the method about the
types of exceptions the method might throw. The caller has to handle the exception using a try-
catch block or propagate the exception.

Example
import java.io.*;
public class className {
public void withdraw (double amount ) throws RemoteException, InsufficientFundsException {
// Method implementation
}
// Remainder of class definition
}

In the example below, we have created a test method to demonstrate throwing an exception.
The toString() method returns a textual representation of an object, but in this case the variable is
null. Calling a method on a null reference or trying to access a field of a null reference will
trigger a NullPointerException.
public void testMethod() throws Exception {
String test = null;
test.toString();
}
This must be handled with a try/catch block:

44
public class Example {
public static void main(String[] arg) {
try {
testMethod();
} catch (Exception e) {
e.printStackTrace();
}
}
}

Activity 4.3

 What mean by user-defined exception?


 What is the purpose of Throws keyword?

4.7. Errors and Runtime Exceptions

Errors: These are not exceptions at all, but problems that arise beyond the control of the user or
the programmer. Errors are typically ignored in your code because you can rarely do anything
about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored
at the time of compilation. Errors are abnormal conditions that happen in case of severe failures,
these are not handled by the Java programs. Errors are generated to indicate errors generated by
the runtime environment. Example: JVM is out of memory.

A logical error is always the symptom of a bug in application code leading to incorrect output
e.g. subtracting two variables instead of adding them. In case of a logical error, the program
operates incorrectly but does not terminate abnormally. Each statement may need to be checked
to identify a logical error, which makes it generally harder to debug than a runtime error.

A runtime error in Java is an application error that occurs during the execution of a program. A
runtime error occurs when a program is syntactically correct but contains an issue that is only
detected during program execution. These issues cannot be caught at compile-time by the Java
compiler and are only detected by the Java Virtual Machine (JVM) when the application is

45
running. Runtime errors are a category of exception that contains several more specific error
types. Some of the most common types of runtime errors are:
 IO errors
 Division by zero errors
 Out of range errors
 Undefined object errors, etc.
Runtime errors occur during program execution (the interpretation phase), after compilation has
taken place. Any code that throws a runtime error is therefore syntactically correct. A runtime
error could potentially be a legitimate issue in code, for example, incorrectly formatted input data
or lack of resources (e.g. insufficient memory or disk space). When a runtime error occurs in
Java, the compiler specifies the lines of code where the error is encountered. This information
can be used to trace back where the problem originated.

It is useful to catch runtime exceptions and continue program execution. To handle a runtime
error, the code can be placed within a try-catch block and the error can be caught inside the catch
block.

Runtime Exceptions Example: Division by zero error

Here is an example of a java.lang.ArithmeticException, a type of runtime exception, thrown due


to division by zero:

public class ArithmeticExceptionExample {


public static void main(String[] args) {
int a = 10, b = 0;
System.out.println("Result: "+ a/b);
}
}
In this example, an integer a is attempted to be divided by another integer b, whose value is zero,
leading to a java.lang.ArithmeticException:
Here is an example of a java.lang.ArrayIndexOutOfBoundsExceptionthrown due to an attempt to
access an element in an array that is out of bounds:

46
public class ValueOutOfRangeErrorExample {
public static void main(String[] args) {
int arr[] = new int[5];
System.out.println("5th element in array: " + arr[5]);
}
}
In this example, an array is initialized with 5 elements. An element at position 5 is later
attempted to be accessed in the array, which does not exist, leading to
a java.lang.ArrayIndexOutOfBoundsException runtime error:

How to handle Runtime Exceptions

To illustrate this, the code in the earlier ArithmeticException example can be updated as follows:
public class ArithmeticExceptionExample {
public static void main(String[] args) {
try {
int a = 10, b = 0;
System.out.println("Result: " + a/b);
} catch (ArithmeticException ae) {
System.out.println("Arithmetic Exception: cannot divide by 0");
}
}
}
Surrounding the code in try-catch blocks like the above allows the program to continue execution
after the exception is encountered. Runtime errors can be avoided where possible by paying
attention to detail and making sure all statements in code are mathematically and logically
correct.

Activity 4.4

 Explain errors by comparing with exceptions?


 Explain runtime exceptions with exampe?

47
Chapter Four Review Questions

1. Explain what try-with-resources with example?


2. Define your own exception to accept a positive number only. i.e. catch negative numbers
as exception.
3. Explain the different types of exceptions in java? Example: A NumberFormatException
can occur when an attempt is made to convert a string into a number. Such conversions
are done by the functions Integer.parseInt and Integer.parseDouble. Consider the function
call Integer.parseInt(str) where str is a variable of type String. If the value of str is the
string "42", then the function call will correctly convert the string into the int 42.
However, if the value of str is, say, "Abebe", the function call will fail because "Abebe" is
not a legal string representation of an int value. In this case, an exception of type
NumberFormatException occurs. If nothing is done to handle the exception, the program
will crash.

48
Chapter Five: Packages

5.1. Packages

A Package can be defined as a grouping of related types (classes, interfaces, enumerations and
annotations) providing access protection and namespace management. Packages are used in Java
in order to prevent naming conflicts, to control access, to make searching/locating and usage of
classes, interfaces, enumerations and annotations easier, etc. Package names and directory
structure are closely related. For example if a package name is college.staff.cs, then there are
three directories, college, staff and cs such that cs is present in staff and staff is present college.

Types of Packages: there are two types of packages; User-defined and Built-in packages.

Built-in Packages

These packages consist of a large number of classes which are a part of Java API. Some of the
commonly used built-in packages are:

java.lang: Contains language support classes(e.g classed which defines primitive data types,
math operations). This package is automatically imported.
java.io: Contains classed for supporting input / output operations.
java.util: Contains utility classes which implement data structures like Linked List, Dictionary
and support ; for Date / Time operations.
java.applet: Contains classes for creating Applets.
java.awt: Contain classes for implementing the components for graphical user interfaces (like
button , menus etc).
java.net: Contain classes for supporting networking operations.

User-defined packages

These are the packages that are defined by the user. First we create a
directory myPackage (name should be same as the name of the package). Then create
the MyClass inside the directory with the first statement being the package names.

// Name of the package must be same as the directory under which this file is saved
package myPackage;

49
public class MyClass
{
public void getName(String name)
{
System.out.println(name);
}
}

Packages are Java’s way of doing large-scale design and organization. They are used both to
categorize and group classes.

5.2. The Import Statement

If a class wants to use another class in the same package, the package name need not be used.
Classes in the same package find each other without any special syntax.
Example:
A class named Boss is added to the payroll package that already contains Employee. The Boss
can then refer to the Employee class without using the payroll prefix, as demonstrated by the
following Boss class.
package payroll;
public class Boss {
public void payEmployee (Employee e ){
e.mailCheck();
}
}

What happens if the Employee class is not in the payroll package? The Boss class must then use
one of the following techniques for referring to a class in a different package. The fully qualified
name of the class can be used. For example:
payroll.Employee
The package can be imported using the import keyword and the wild card (*). For example:
import payroll .*;
The class itself can be imported using the import keyword. For example:

50
import payroll.Employee;

A class file can contain any number of import statements. The import statements must appear
after the package statement and before the class declaration.

5.3. Static Imports

The static import declaration is analogous to the normal import declaration. Where the normal
import declaration imports classes from packages, allowing them to be used without package
qualification, the static import declaration imports static members from classes, allowing them to
be used without class qualification.

The import provides accessibility to classes and interface whereas static import provides
accessibility to static members of the class.
Exampe:
import static java.lang.System.*;
class StaticImportExample{
public static void main(String args[]){
out.println(“Hello Static Import”);//no need of System.out
}
}

Activity 5.1

 Explain package and its purpose?


 Explain the use of import statement?

51
5.4. CLASSPATH

The full path to the classes directory, <path-two>\classes, is called the class path, and is set with
the CLASSPATH system variable. Both the compiler and the JVM construct the path to your
.class files by adding the package name to the class path. A class path set via the operating
system, and sometimes by the installation program that installs Java.

CLASSPATH contains one or more directories that are used as roots in a search for .class files.
Starting at that root, the interpreter will take the package name and replace each dot with a slash
to generate a path name off of the CLASSPATH root (so package foo.bar.baz becomes
foo\bar\baz. Say <path-two>\classes is the class path, and the package name is
com.apple.computers, then the compiler and JVM will look for .class files in <path-
two>\classes\com\apple\computers. A class path may include several paths. Multiple paths
should be separated by a semicolon (Windows) or colon (Unix). By default, the compiler and the
JVM search the current directory and the JAR file containing the Java platform classes so that
these directories are automatically in the class path.

5.5. Defining Packages

Programmers can define their own packages to bundle group of classes/interfaces, etc. It is a
good practice to group related classes implemented by you so that a programmer can easily
determine that the classes, interfaces, enumerations, and annotations are related. Since the
package creates a new namespace there won't be any name conflicts with names in other
packages. Using packages, it is easier to provide access control and it is also easier to locate the
related classes.

While creating a package, you should choose a name for the package and include a package
statement along with that name at the top of every source file that contains the classes, interfaces,
enumerations, and annotation types that you want to include in the package. The package
statement should be the first line in the source file (except for comments and white space, of
course). There can be only one package statement in each source file, and it applies to all types in
the file. If a package statement is not used then the class, interfaces, enumerations, and
annotation types will be placed in the current default package. It is a good practice to use names

52
of packages with lower case letters to avoid any conflicts with the names of classes and
interfaces. Following package example contains interface named animals:
package animals;
interface Animal{
public void eat ();
public void travel ();
}
Now a package/folder with the name animals will be created in the current directory and the
class files will be placed in it.

5.6. Package Scope

The default access has no keyword, but it is commonly referred to as package access. It means
that all the other classes in the current package have access to that member, but to all the classes
outside of this package, the member appears to be private.

Package access allows you to group related classes together in a package so that they can easily
interact with each other. When you put classes together in a package, thus granting mutual access
to their package-access members, you “own” the code in that package.

Give the member package access by leaving off any access modifier, and put the other classes in
the same package. Then the other classes in that package can access the member.

Activity 5.2

 Explain package and its purpose?


 Explain the use of import statement?

53
Chapter Five Review Questions

1. Explain the types of packages?


2. What is the difference between import and static import statements?
3. What mean by a CLASSPATH?
4. Define a package and show how the import statement works?
5. Explain the scope of a package?

54
Chapter Six: Data Structures
6.1. The set

The set is an interface available in the java.util package. The set interface extends the Collection
interface. An unordered collection or list in which duplicates are not allowed is referred to as a
collection interface. The set interface is used to create the mathematical set. The set interface use
collection interface's methods to avoid the insertion of the same elements. More formally, sets
contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. As
implied by its name, this interface models the mathematical set abstraction.

Example: LinkedHashSet using the Set


package set;
import java.util.*;
public class setExample {
public static void main(String[] args) {
// creating LinkedHashSet using the Set
Set<String> data = new LinkedHashSet<String>();
data.add("JavaTpoint");
data.add("Set");
data.add("Example");
data.add("Set");
System.out.println(data);
}
}
Output: [JavaTpoint, Set, Example]

6.2. Set Implementation Classes

The Java platform contains three general-purpose Set implementations: HashSet, TreeSet,
and LinkedHashSet. HashSet, which stores its elements in a hash table, is the best-performing
implementation; however it makes no guarantees concerning the order of iteration. TreeSet,
which stores its elements in a red-black tree, orders its elements based on their values; it is
substantially slower than HashSet. LinkedHashSet, which is implemented as a hash table with a

55
linked list running through it, orders its elements based on the order in which they were inserted
into the set (insertion-order).

Operations on the Set Interface

On the Set, we can perform all the basic mathematical operations like intersection, union and
difference. Suppose, we have two sets, i.e., set1 = [22, 45, 33, 66, 55, 34, 77] and set2 = [33, 2,
83, 45, 3, 12, 55].We can perform the following operation on the Set:

Intersection: The intersection operation returns all those elements which are present in both the
set. The intersection of set1 and set2 will be [33, 45, 55].

Union: The union operation returns all the elements of set1 and set2 in a single set, and that set
can either be set1 or set2. The union of set1 and set2 will be [2, 3, 12, 22, 33, 34, 45, 55, 66,77,
83].

Difference: The difference operation deletes the values from the set which are present in another
set. The difference of the set1 and set2 will be [66, 34, 22, 77].

In set, addAll() method is used to perform the union, retainAll() method is used to perform the
intersection and removeAll() method is used to perform difference. Let's take an example to
understand how these methods are used to perform the intersection, union, and difference
operations.
Example:
package set;
import java.util.*;
public class SetOperations {
public static void main(String[] args) {
Integer[] A = {22,45,33,66,55,34,77};
Integer[] B = {33,2,83,45,3,12,55};
Set<Integer> set1 =new HashSet<Integer>();
set1.addAll(Arrays.asList(A));
Set<Integer> set2 = new HashSet<Integer>();
set2.addAll(Arrays.asList(B));

56
// Finding Union of set1 and set2
Set<Integer> union_data = new HashSet<Integer>(set1);
union_data.addAll(set2);
System.out.print("Union of set1 and set2 is:");
System.out.println(union_data);
// Finding Intersection of set1 and set2
Set<Integer> intersection_data = new HashSet<Integer>(set1);
intersection_data.retainAll(set2);
System.out.print("Intersection of set1 and set2 is:");
System.out.println(intersection_data);
// Finding Difference of set1 and set2
Set<Integer> difference_data = new HashSet<Integer>(set1);
difference_data.removeAll(set2);
System.out.print("Difference of set1 and set2 is:");
System.out.println(difference_data);

In the above code, first, we create two arrays, i.e., A and B of type integer. After that, we create
two set, i.e., set1 and set2 of type integer. We convert both the array into a list and add the
elements of array A into set1 and elements of array B into set2.

For performing the union, we create a new set union_data with the same element of the set1. We
then call the addAll() method of set and pass the set2 as an argument to it. This method will add
all those elements to the union_data which are not present in it and gives the union of both sets.

For performing the intersection, we create a new set intersection_data with the same element of
theset1. We then call the retainAll() method of set and pass the set2 as an argument to it. This
method will get all those elements from the intersection_data which are present in set2 and store
it in the intersection_data. Now, the intersection_data contains the intersect value of both the
sets.

For performing the difference, we create a new set difference_data with the same element of
theset1. We then call the removeAll() method of set and pass the set2 as an argument to it. This

57
method will remove all those elements from the difference_data which are present in the set2 and
gives the difference of both the sets.

Set Methods

There are several methods available in the set interface which we can use to perform a certain
operation on our sets. These methods are as follows:

The add() method insert a new value to the set. The method returns true and false depending on
the presence of the insertion element. It returns false if the element is already present in the set
and returns true if it is not present in the set.
Syntax:
boolean add(type element)
Example:
import java.util.*;
public class addMethod {
public static void main(String args[]) {
Set<Integer> data = new LinkedHashSet<Integer>();
data.add(11);
data.add(61);
data.add(51);
System.out.println("data: " + data);
}
}

The addAll() method appends all the elements of the specified collection to the set.
Syntax:
boolean addAll(Collection data)
Example:
import java.util.*;
class addAllMethod {
public static void main(String args[]) {
Set<Integer> data = new LinkedHashSet<Integer>();

58
data.add(31);
data.add(21);
data.add(41);
System.out.println("Set: " + data);
ArrayList<Integer> newData = new ArrayList<Integer>();
newData.add(91);
newData.add(71);
newData.add(81);
data.addAll(newData);
System.out.println("Set: " + data);
}
}

The clear() method removes all the elements from the set. It doesn't delete the reference of the
set. It only deletes the elements of the set.
Syntax:
void clear()
Example:
import java.util.*;
public class clearMethod {
public static void main(String args[]) {
Set<Integer> data = new LinkedHashSet<Integer>();
data.add(31);
data.add(21);
data.add(41);
System.out.println("Set: " + data);
data.clear();
System.out.println("The final set: " + data);
}
}

59
The contains() method is used to know the presence of an element in the set. Its return value is
true or false depending on the presence of the element.
Syntax:
boolean contains(Object element)
Example:
import java.util.*;
class containsMethod {
public static void main(String args[]) {
Set<Integer> data = new LinkedHashSet<Integer>();
data.add(31);
data.add(21);
data.add(41);
System.out.println("Set: " + data);
System.out.println("Does the Set contains '91'?" + data.contains(91));
System.out.println("Does the Set contains 'java'? " + data.contains("4"));
System.out.println("Does the Set contains '51'? " + data.contains(51));
}
}

The containsAll() method is used to check whether all the elements of the collection are
available in the existing set or not. It returns true if all the elements of the collection are present
in the set and returns false even if one of the elements is missing in the existing set.
Syntax:
public boolean containsAll(Collection data)
Example:
import java.util.*;
class containsAllMethod {
public static void main(String args[]) {
Set<Integer> data = new LinkedHashSet<Integer>();
data.add(31);
data.add(21);
data.add(41);
60
System.out.println("data: " + data);
Set<Integer> newData = new LinkedHashSet<Integer>();
newData.add(31);
newData.add(21);
newData.add(41);
System.out.println("\nDoes data contains newData?: "+ data.containsAll(newData));
}
}

The isEmpty() method is used to identify the emptiness of the set . It returns true if the set is
empty and returns false if the set is not empty.
Syntax:
boolean isEmpty()
Example:
import java.util.*;
class isEmptyMethod {
public static void main(String args[]) {
Set<Integer> data = new LinkedHashSet<Integer>();
data.add(31);
data.add(21);
data.add(41);
System.out.println("data: " + data);
System.out.println("\nIs data empty?: "+ data.isEmpty());
}
}

The iterator() method is used to find the iterator of the set. The iterator is used to get the element
one by one.
Syntax:
Iterator iterate_value = set1.iterator();
Example:
import java.util.*;

61
class iteratorMethod {
public static void main(String args[]) {
Set<Integer> data = new LinkedHashSet<Integer>();
data.add(31);
data.add(21);
data.add(41);
System.out.println("data: " + data);
Iterator newData = data.iterator();
System.out.println("The NewData values are: ");
while (newData.hasNext()) {
System.out.println(newData.next());
}
}
}

The remove() method is used to remove a specified element from the Set. Its return value
depends on the availability of the element. It returns true if the element is available in the set and
returns false if it is unavailable in the set.
Syntax:
boolean remove(Object O)
Example:
import java.util.*;
class removeMethod {
public static void main(String args[]) {
Set<Integer> data = new LinkedHashSet<Integer>();
data.add(31);
data.add(21);
data.add(41);
System.out.println("data: " + data);
data.remove(21);
data.remove(11);
System.out.println("data after removing elements: " + data);
62
}
}

The removeAll() method removes all the elements of the existing set from the specified
collection.
Syntax:
public boolean removeAll(Collection data)
Example:
import java.util.*;
class removeAllMethod {
public static void main(String args[]) {
Set<Integer> data = new LinkedHashSet<Integer>();
data.add(31);
data.add(21);
data.add(41);
System.out.println("data: " + data);
ArrayList<Integer> newData = new ArrayList<Integer>();
newData.add(31);
newData.add(71);
System.out.println("NewData: " + newData);
data.removeAll(newData);
System.out.println("data after removing Newdata elements : " + data);
}
}

The retainAll() method retains all the elements from the set specified in the given collection.
Syntax:
public boolean retainAll(Collection data)
Example:
import java.util.*;
class retainAllMethod {
public static void main(String args[]) {

63
Set<Integer> data = new LinkedHashSet<Integer>();
data.add(31);
data.add(21);
data.add(41);
data.add(91);
System.out.println("data: " + data);
ArrayList<Integer> newData = new ArrayList<Integer>();
newData.add(41);
newData.add(91);
System.out.println("newData: " + newData);
data.retainAll(newData);
System.out.println("data after retaining newdata elements : " + data);
}
}

The size() method returns the size of the set.


Syntax:
int size()
Example:
import java.util.*;
class sizeMethod {
public static void main(String args[]) {
Set<Integer> data = new LinkedHashSet<Integer>();
data.add(31);
data.add(21);
data.add(41);
System.out.println("data: " + data);
System.out.println("size of the data is : " + data.size());
}
}

The Object[] toArray() method is used to create an array with the same elements of the set.

64
Syntax:
Object[] toArray()
Example:
import java.util.*;
class toArrayMethod {
public static void main(String args[]) {
Set<Integer> data = new LinkedHashSet<Integer>();
data.add(31);
data.add(21);
data.add(41);
System.out.println("data: " + data);
Object[] array_data = data.toArray();
System.out.println("The array is:");
for (int i = 0; i < array_data.length; i++)
System.out.println(array_data[i]);
}
}

Activity 6.1

 Explain the properties of set data structure?


 Explain the methods used by set data structure?

6.3. The List

List in Java provides the facility to maintain the ordered collection. It contains the index-based
methods to insert, update, delete and search the elements. It can have the duplicate elements also.
We can also store the null elements in the list.

65
The List interface is found in the java.util package and inherits the Collection interface. It is a
factory of ListIterator interface. Through the ListIterator, we can iterate the list in forward and
backward directions.

6.4. List Implementation Classes

The implementation classes of the List interface are ArrayList, LinkedList, Stack, and Vector.
The ArrayList and LinkedList classes are widely used in Java programming.

List Methods

Creating a List of type String using ArrayList


List<String> list=new ArrayList<String>();
Creating a List of type Integer using ArrayList
List<Integer> list=new ArrayList<Integer>();
Creating a List of type String using LinkedList
List<String> list=new LinkedList<String>();

In short, you can create the List of any type. The ArrayList<T> and LinkedList<T> classes are
used to specify the type. Here, T denotes the type.

The add(i,e) or add(e) method is used to insert the specified element at the specified position in a
list or at the end.
Example:
import java.util.*;
public class ListExample1{
public static void main(String args[]){
//Creating a List
List<String> list=new ArrayList<String>();
//Adding elements in the List
list.add("Mango");
list.add("Apple");
list.add("Banana");
list.add("Grapes");

66
list.add(4, "Orange");
//Iterating the List element using for-each loop
for(String fruit:list)
System.out.println(fruit);
}
}

Get and Set Element in List: The get() method returns the element at the given index, whereas
the set() method changes or replaces the element.
Example:
import java.util.*;
public class ListExample2{
public static void main(String args[]){
//Creating a List
List<String> list=new ArrayList<String>();
//Adding elements in the List
list.add("Mango");
list.add("Apple");
list.add("Banana");
list.add("Grapes");
//accessing the element
System.out.println("Returning element: "+list.get(1));//it will return the 2nd element
//changing the element
list.set(1,“Lemon);
//Iterating the List element using for-each loop
for(String fruit:list)
System.out.println(fruit);
}
}

The Collections.sort() method used to sort the list element.


Example:

67
import java.util.*;
public class SortList{
public static void main(String args[]){
//Creating a List
List<String> list=new ArrayList<String>();
//Adding elements in the List
list.add("Mango");
list.add("Apple");
list.add("Banana");
list.add("Grapes");
//Sorting the list
Collections.sort(list);
//Traversing list through the for-each loop
for(String fruit:list)
System.out.println(fruit);
}
}

ListIterator Interface is used to traverse the element in a backward and forward direction.
Example:
import java.util.*;
public class ListIteratorExample{
public static void main(String args[]){
List<String> list=new ArrayList<String>();
list.add("Mango");
list.add("Apple");
list.add("Banana");
list.add("Grapes");
ListIterator<String> itr=list.listIterator();
System.out.println("Traversing elements in forward direction");
while(itr.hasNext()){
System.out.println("index:"+itr.nextIndex()+" value:"+itr.next());
68
}
System.out.println("Traversing elements in backward direction");
while(itr.hasPrevious()){
System.out.println("index:"+itr.previousIndex()+" value:"+itr.previous());
}
}
}

The remove() method is used to remove the element present at the specified position in the list.
Example:
import java.util.*;
public class ListExample1{
public static void main(String args[]){
List<String> list=new ArrayList<String>();
list.add("Mango");
list.add("Apple");
list.add("Banana");
//remove the 2nd element
list.remove(1);
//Iterating the List element using for-each loop
for(String fruit:list)
System.out.println(fruit);
}
}

The removeAll() or clear() methods are used to remove all the elements from the list.
Example:
import java.util.*;
public class ListExample1{
public static void main(String args[]){
List<String> list=new ArrayList<String>();
list.add("Mango");

69
list.add("Apple");
list.add("Banana");
//remove all the elements of the list by using removeAll() or clear() methods
list.removeAll(list);
//list.clear();
//Iterating the List element using for-each loop
for(String fruit:list)
System.out.println(fruit);
}
}

Activity 6.2

 Explain the properties of list data structure?


 Explain the methods used by list data structure?

6.5. The stack

The stack is a linear data structure that is used to store the collection of objects. It is based on
Last-In-First-Out (LIFO). Java collection framework provides many interfaces and classes to
store the collection of objects. One of them is the Stack class that provides different operations
such as push, pop, search, etc. The stack data structure has the two most important operations
that are push and pop. The push operation inserts an element into the stack and pop operation
removes an element from the top of the stack. Empty Stack: If the stack has no element is known
as an empty stack. When the stack is empty the value of the top variable is -1.
When we push an element into the stack the top is increased by 1.
Push 12, top=0
Push 6, top=1
Push 9, top=2
When we pop an element from the stack the value of top is decreased by 1.

70
When the stack is full the value of the top variable is N-1.

6.6. Stack Implementation Classes

In Java, Stack is a class that falls under the Collection framework that extends the Vector class. It
also implements interfaces List, Collection, Iterable, Cloneable, Serializable. Before using the
Stack class, we must import the java.util package.

Stack Methods

Creating stack
Stack stk = new Stack(); Or Stack<type> stk = new Stack<>();
Where type denotes the type of stack like Integer, String, etc.
The empty() method of the Stack class check the stack is empty or not. If the stack is empty, it
returns true, else returns false.
Example:
import java.util.*;
public class StackEmptyMethodExample {
public static void main(String[] args) {
//creating an instance of Stack class
Stack<Integer> stk= new Stack<Integer>();
// checking stack is empty or not
boolean result = stk.empty();
System.out.println("Is the stack empty? " + result);
// pushing elements into stack
stk.push(78);
stk.push(113);
stk.push(90);
stk.push(120);
//prints elements of the stack
System.out.println("Elements in Stack: " + stk);
result = stk.empty();
System.out.println("Is the stack empty? " + result);

71
}
}
The push() method inserts an item onto the top of the stack. It passes a parameter item to be
pushed into the stack.
The pop() method removes an object at the top of the stack and returns the same object. It throws
EmptyStackException if the stack is empty.
Example:
import java.util.*;
public class StackPushPopExample {
public static void main(String args[]) {
//creating an object of Stack class
Stack <Integer> stk = new Stack<Integer>();
System.out.println("stack: " + stk);
//pushing elements into the stack
stk.push(20);
stk.push(13);
stk.push(89);
//popping elements from the stack
try {
Integer x = (Integer) stk.pop();
System.out.println(x);
} //throws exception if the stack is empty
catch (EmptyStackException e) {
System.out.println("empty stack");
}
//prints modified stack
System.out.println("stack: " + stk);
}
}

The peek() method looks at the element that is at the top in the stack. It also throws
EmptyStackException if the stack is empty.
72
Example:
import java.util.*;
public class StackPeekMethodExample {
public static void main(String[] args) {
Stack<String> stk= new Stack<String>();
stk.push("Apple");
stk.push("Grapes");
stk.push("Mango");
System.out.println("Stack: " + stk);
// Access element from the top of the stack
try {
String fruits = stk.peek();
}//throws exception if the stack is empty
catch (EmptyStackException e) {
System.out.println("empty stack");
}
//prints stack
System.out.println("Element at top: " + fruits);
}
}

The search() method searches the object in the stack from the top. It returns the object location
from the top of the stack. If it returns -1, it means that the object is not on the stack.
Example:
import java.util.*;
public class StackSearchMethodExample {
public static void main(String[] args) {
Stack<String> stk= new Stack<String>();
stk.push("Apple");
stk.push("Grapes");
stk.push("Mango");
System.out.println("Stack: " + stk);
73
// Search an element
int location = stk.search(“Lemon");
System.out.println("Location of Lemon: " + location);
}
}

The size() method used to find the size of the stack. It returns the total number of elements (size
of the stack) in the stack.
Example:
import java.util.*;
public class StackSizeMethodExample {
public static void main(String[] args) {
Stack<String> stk= new Stack<String>();
stk.push("Apple");
stk.push("Grapes");
stk.push("Mango");
System.out.println("Stack: " + stk);
// Find the size of the Stack
int x=stk.size();
System.out.println("The stack size is: "+x);
}
}

The iterator() method used to fetch the elements of the stack.


Example:
import java.util.*;
public class StackIteratorMethodExample {
public static void main(String[] args) {
Stack<String> stk= new Stack<String>();
stk.push("Apple");
stk.push("Grapes");
stk.push("Mango");

74
//iteration over the stack
Iterator iterator = stk.iterator();
while(iterator.hasNext()) {
Object values = iterator.next();
System.out.println(values);
}
}

Activity 6.3

 Explain the properties of stack data structure?


 Explain the methods used by stack data structure?

6.7. The Queue

Java Queue interface orders the element in FIFO (First In First Out) manner. In FIFO, first
element is removed first and last element is removed at last. The PriorityQueue class provides
the facility of using queue. But it does not orders the elements in FIFO manner. It inherits
AbstractQueue class.

6.8. Queue Implementation Classes

Some of the frequently used Queue implementation classes are LinkedList, PriorityQueue,
ArrayBlockingQueue, DelayQueue, LinkedBlockingQueue, PriorityBlockingQueue etc.
AbstractQueue provides a skeletal implementation of the Queue interface to reduce the effort in
implementing Queue.

Queue Methods

75
The add() method is used to insert the specified element into this queue and return true upon
success.
The offer() method is used to insert the specified element into this queue.
The remove() method is used to retrieves and removes the head of this queue.
The poll() method is used to retrieves and removes the head of this queue, or returns null if this
queue is empty.
The element() method is used to retrieves, but does not remove, the head of this queue.
The peek() method is used to retrieves, but does not remove, the head of this queue, or returns
null if this queue is empty.
Example:
import java.util.*;
public class QueueMethods {
public static void main(String[] args) {
PriorityQueue <String> queue = new PriorityQueue<String>();
System.out.println("Queue: " + queue);
queue.add("Apple");
queue.add("Grapes");
queue.add("Mango");
System.out.println("head:"+queue.element());
System.out.println("head:"+queue.peek());
System.out.println("iterating the queue elements:");
Iterator itr=queue.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
queue.remove();
queue.poll();
System.out.println("after removing two elements:");
Iterator<String> itr2=queue.iterator();
while(itr2.hasNext()){
System.out.println(itr2.next());

76
}
}
}

Activity 6.4

 Explain the properties of queue data structure?


 Explain the methods used by queue data structure?

6.9. Map/Dictionary

A map contains values on the basis of key, i.e. key and value pair. Each key and value pair is
known as an entry. A Map contains unique keys. A Map is useful if you have to search, update or
delete elements on the basis of a key. There are two interfaces for implementing Map in java:
Map and SortedMap, and three classes: HashMap, LinkedHashMap, and TreeMap.

A Map doesn't allow duplicate keys, but you can have duplicate values. HashMap and
LinkedHashMap allow null keys and values, but TreeMap doesn't allow any null key or value.
A Map can't be traversed, so you need to convert it into Set using keySet() or entrySet() method.

Map Methods

The put() method is used to insert an entry in the map.


The remove() method is used to delete an entry for the specified key.
The keySet() or entrySet() methods are used to return the Set view containing all the keys.
The clear() method is used to reset the map.
The equals() method is used to compare the specified Object with the Map.
The isEmpty() method returns true if the map is empty; returns false if it contains at least one
key.
The size() method returns the number of entries in the map.
Example:

77
import java.util.*;
public class MapExample1 {
public static void main(String[] args) {
Map<Integer,String> map=new HashMap<Integer,String>();
//Adding elements to map
map.put(1,"Amit");
map.put(5,"Rahul");
map.put(2,"Jai");
map.put(6,"Amit");
//map.remove(4);
//map.clear();
boolean x =map.equals(map);
System.out.println(x);
boolean y =map.isEmpty();
System.out.println(y);
int i=map.size();
System.out.println(i);
//Traversing Map
Set set=map.entrySet();//Converting to Set so that we can traverse
Iterator itr=set.iterator();
while(itr.hasNext()){
//Converting to Map.Entry so that we can get key and value separately
Map.Entry entry=(Map.Entry)itr.next();
System.out.println(entry.getKey()+" "+entry.getValue());
}
}
}

Activity 6.5

 Explain the properties of map data structure?


 Explain the methods used by map data structure?

78
Chapter Six Review Questions

1. Write a Java program that implements a set data structure and apply its methods?
2. Write a Java program that implements a list data structure and apply its methods?
3. Write a Java program that implements a stack data structure and apply its methods?
4. Write a Java program that implements a queue data structure and apply its methods?
5. Write a Java program that implements a map data structure and apply its methods?

79

You might also like