You are on page 1of 60

ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY

INTRODUCTION TO JAVA
Java is a simple, object-oriented, distributed, interpreted, robust, secure, architecture neutral,
portable, high-performance, multithreaded, and dynamic language created by James Gosling
from Sun Microsystems in 1990 and was officially released in 1995. Sun Microsystems was
acquired by the Oracle Corporation in 27th Jan, 2010.

In 2006 Sun started to make java available under the GNU General Public License (GPL) and
Oracle continues this project called OpenJDK. The initial version of JDK is 1.0 and current
stable version is 1.8 or JDK 8.

History of Java Development

Year Development

Sun Microsystems decided to develop special software that could used to manipulate
1990
consumer electronic devices.

After exploring the possibility of using the most popular object-oriented language
1991
C++, the team of Sun Microsystems announced a new language “OAK”.

They use their new language to control a list of home appliances using hand held
1992
devices with a tiny touch sensitive screen.

The team came up with idea of developing web applets (tiny programs) using the
1993
new language that could run on all types of computers connected to internet.

The team developed a web browser called “HotJava” to locate and run applet
1994
program on internet. This becomes the most popular among the internet users.

Oak was renamed “Java”. Java is just a name not an acronym and many popular
1995
companies like Netscape and Microsoft also support this language.

A Java virtual machine (JVM) is an abstract computing machine that enables a computer to
run a Java program. There are three notions of the JVM: specification, implementation, and
instance. The specification is a document that formally describes what is required of a JVM
implementation. Having a single specification ensures all implementations are interoperable. A
JVM implementation is a computer program that meets the requirements of the JVM
specification. An instance of a JVM is an implementation running in a process that executes a
computer program compiled into Java bytecode.

1
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY

Java Runtime Environment (JRE) is a software package that contains what is required to run a
Java program. It includes a Java Virtual Machine implementation together with an
implementation of the Java Class Library. The Oracle Corporation, which owns the Java
trademark, distributes a Java Runtime environment with their Java Virtual Machine called
HotSpot.

Java Development Kit (JDK) is a superset of a JRE and contains tools for Java programmers,
e.g. a javac compiler. The Java Development Kit is provided free of charge either by Oracle
Corporation directly, or by the OpenJDK open source project, which is governed by Oracle.

Java Byte-code: When the program written in java is compiled, the compiler generates an
intermediate code
instead of directly to
platform specific
machine code. This
intermediate code is
known as byte-code
and is machine
independent.
This byte code is

2
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY

then translated to machine code by an interpreter known as Java virtual machine which is
incorporated with every operating system.

Object Oriented Programming with java


Object Oriented Programming is a Programming Methodology that associates data structures
with a set of Operators which act upon it. In OOP, an instance of such an entity is known as
object in other words, OOP is a method of implementation in which programs are organized as a
cooperative collection of objects, each of which represents an instance of some class and whose
classes are all member of hierarchy of classes united through property called Inheritance.

Characteristics of OOP’s
 Emphasis is on data rather than procedures.
 Programs are divided into objects.
 Data structures are designed such that they characterize the objects.
 Functions & data are tied together in the data structures so that data abstraction is
introduced in addition to procedural abstraction.
 Data is hidden & can’t be accessed by external functions.
 Object can communicate with each other through function.
 New data & functions can be easily added. – Follows Bottom up approach.

Objects
Objects are the basic runtime in an Object Oriented System. Objects are the entities in an object
oriented system through which we perceive the world around us. We naturally see our
environment as being composed of things which have recognizable identities & behavior. The
entities are then represented as objects in the program. They may represent a Person, a Place, a
Bank Account, or any item that the program must handle. For example Automobiles are objects
as they have size, weight, color etc as attributes (i.e. Data or Properties) and starting, pressing the
brake, turning the wheel, pressing accelerator pedal etc as operation (that is Methods or
Behaviors).

Example of Objects:
Physical Objects:
 Automobiles in traffic flow simulation
 Countries in Economic model
 Air Craft in Traffic Control System
Computer user environment objects:
 Window, menus, icons etc Data storage constructs.
 Stacks, Trees etc

3
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY
Human entities:
 Employees, student, teacher etc.
 Geometric objects: -point, line, Triangle etc.
Objects mainly serve the following purposes:
 Understanding the real world and a practical base for designers
 Decomposition of a problem into objects depends on the nature of problem.

Perosn
Employee Student Account

name, marks, accountNumber,


name,
dateOfBirth accountType, name
basicPay

total(), average(), deposit(), enquiry(),


salary(),
showMarks() widthdraw()
tax()

Classes
A class is a collection of objects of similar type. For example Manager, Peron, Secretary, Clerk
are member of the class Employee and class Vehicle includes objects Car, Bus, etc. It defines a
data type, much like a struct in C programming language and built in data type (int char, float
etc). It specifies what data and functions will be included in objects of that class. Defining class
doesn’t create an object but class is the description of object’s attributes and behaviors.

Person class: Attributes: Name, Age, Sex etc. Behaviors: speak(), listen(), walk() .. etc.
Vehicle class: Attributes: Name, model, color, height etc. Behaviors: start(), stop(), accelerate()
etc.

When class is defined, objects are created as: <classname> <objectname> = new
<classname>(); If Employee has been defined as a class, then the statement Employee
manager= new Employee(); Will create an object manager belonging to the class Employee.

Each class describes a possibly infinite set of individual objects, each object is said to be an
instance of its class and each instance of the class has its own value for each attribute but shares
the attribute name and operations with other instances of the class. The following point gives the
idea of class:
 A class is a template that unites data and operations.
 A class is an abstraction of the real world entities with similar properties.
 Ideally, the class is an implementation of abstract data type.

4
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY
Abstraction
Abstraction refers to the act of representing
essential features without including the background
detail or explanation. That is system hides certain
detail of how the data are stored and maintained,
developers hide the complex-city from users
through several levels of abstraction such as
physical level, logical level, view level. A class
uses the concept of abstraction and is defined as a
list of abstract and attribute.

The Three OOP Principles (Encapsulation, Inheritance, and Polymorphism)


Encapsulation
Encapsulation is data and method into single unit called class is known as encapsulation. Data
encapsulation is the most striking features of class. Encapsulation makes if possible for object to
be created like “Block Boxes” each performing specific task without any concern for internal
implementation.

Information In Data and Methods Information out

Fig: Encapsulation objects as “Block Box”.


Inheritance
Inheritance is the process by which objects of one class acquire the characteristics of object of
another class. In OOP, the concept of inheritance provides the idea of reusability. We can use
additional features to an existing class without modifying it. This is possible by deriving a new
class (derived class) from the existing one (base class).This process of deriving a new class from
the existing base class is called
inheritance.
It supports the concept of
hierarchical classification. It allows
the extension and reuse of existing
code without having to rewrite the
code.

Polymorphism
Polymorphism means “having many
forms”. The polymorphism allows
different objects to respond to the
same message in different ways, the
response specific to the type of
object. Polymorphism is important when object oriented programs dynamically creating and

5
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY
destroying the
objects in runtime.
Example of
polymorphism in
OOP is operator
overloading,
function
overloading.
For example
operator symbol ‘+’
is used for
arithmetic operation
between two
numbers, however by overloading (means given additional job) same operator „+‟ can be used
for different purpose like concatenation of strings.

FEATURES OF JAVA [JAVA BUZZ WORDS]


Simple: The simplicity of Java means that a programmer could learn it quickly. The number of
language constructs has been kept small and it has a look and feel familiar to C, C++ and
Objective-C. Therefore programmers can easily migrate to Java. In java Memory is
automatically allocated and deallocation is done by the garbage collector.

Object Oriented: Java is a pure object oriented language, so it supports Inheritance,


Polymorphism, Dynamic Binding, Encapsulation and Message Passing. Java is an object-
oriented language, which means that you focus on the data in your application and methods that
manipulate that data, rather than thinking strictly in terms of procedures. In an object-oriented
system, a class is a collection of data and methods that operate on that data. The data and
methods describe the state and behavior of an object.

Robust: Java has strong memory allocation and deallocation (automatic garbage connection)
mechanism.
It provides a powerful exception handling and type checking mechanism as compared to other
programming. Compiler checks the program whether there are any errors and interpreter checks
any runtime errors and make the system secure from crash. All of the above feature makes java
as robust language.

Multithreaded: Java allows multiple concurrent threads of execution to be active at once. This
means that you could be listening to an audio clip while scrolling the page and in the background
6
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY
downloading an image. Java contains sophisticated synchronization primitives (monitors and
condition variables), that are integrated into the language to make them easy to use and robust.
The java.lang package provides a Thread class that supports methods to start, run, and stop a
thread, and check on its status.

Architecture Neutral: As Java programs are compiled to byte-code machine, compiled


programs will run on every architecture which implements the Java virtual machine. In this way
programmers do not need to maintain software versions for different platforms; they have only to
maintain one version.

Interpreted and High-performance: The Java compiler generates byte-code instead of


machine-dependent code. To run a program one has to load it into the Java virtual machine. This
machine has been implemented for the most popular operating systems.
As Java is an interpreted language, one cannot expect the performance of a compiled one.
Nevertheless, Java code is faster than other codes of interpreted languages in UNIX
environments such as perl, tcl, etc. or script languages as bash, sh, csh, etc.

Distributed: Java has been designed to support applications on networks. It supports different
levels of connectivity through classes in the java.net package. The URL class allows a Java
application to open and access remote objects on the internet. In Java, it is transparent if a file is
local or remote. Using the Socket class, one can create distributed clients and servers. New
upgrades of Java support Remote Method Invocation (RMI).

Dynamic: Java was designed to adapt to an evolving environment, even after binaries have been
released, they can adapt to a changing environment. Java manipulates memory in a dynamic
way. Classes are loaded by demand even across a network to access resources in dynamic
fashion.
CONTROL STATEMENTS
The control statements are used to control the flow of execution of the program. This execution
order depends on the supplied data values and the conditional logic of the program. Java’s
program control statements can be put into the following categories: Selection, Iteration, and
Branching or Jump Statements.
Java’s Selection Statements: Java supports two selection statements: if and switch. These
statements allow you to control the flow of your program’s execution based upon conditions

7
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY
known only during run time. Java selection statements are also known as control or branching or
decision making statements. Java supports following selection statements:
1. If statement
2. Switch statement
The if statement: The if statement is a powerful decision making statement and it is used to
control the flow of execution of statements. It is the two-way statement and is used in
conjunction with a test condition. The general form of if statement is:
if(condition){
//Statement
}
And if –else condition
if(condition){
//perform the operation is condition true
}
else{
//if the condition flase
}
Here, if is a keyword and the condition following the keyword if is always enclosed within the
pair of parenthesis. The value of test condition may be true (non zero) or false (zero). The if
statement allow the computer to test the condition first and depending on whether the value of
the condition is true or false, it transfer the control to a particular statement. The if statement has
two paths: one for the true condition and other for false condition. The if statements may be of
different forms depending upon the complexity of conditions to be tested.
1. Simple if statement
2. if-else statement
3. Nested if-else statement
4. else-if ladder statement
Nested if: A nested if is a if statement that is (placed or put inside another if or else) the target of
another if or else. Nested ifs are very common in programming. When you nest ifs, the main
thing to remember is that an else statement always refers to the nearest if statement that is within
the same block as the else and that is not already associated with an else.
SYNTAX:
if(condition){
//perform the operation is condition true
if(Conditon){
// if inner condition true
}
else{
8
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY
// if inner condition false
}
}
else{
//if the condition flase
}
And if-else ladder has the following syntax:
if(condition){
//perform the operation is condition true
}
else if(another condition){
//if another condition true
}
.
.
else{
//false condition
}
Switch Case Statement
The switch case statement, also called a case statement is a multi-way branch with several
choices. It is easier to implement than a series of if/else statements. The switch statement begins
with a keyword switch followed by an expression that evaluates to a no long integral value.
Following the controlling expression is a code block that contains zero or more labeled cases.
Each label must equate to an integer constant and each must be unique. When the switch
statement executes, it compares the value of the controlling expression to the values of each case
label. The program will select the value of the case label that equals the value of the controlling
expression and branch down that path to the end of the code block. If none of the case label
values match, then none of the codes within the switch statement code block will be executed.
Java includes a default label to use in cases where there are no matches. We can have a nested
switch within a case block of an outer switch. Its general form is as follows:
SYNTAX:
switch(testExpression){
case constant 1:
statement 1
...
break;
case constant 2:
statement 2
...
break;
case constant N:
statement N
...
break;

9
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY
default:
statement
break;
}
When executing a switch statement, the program falls through to the next case. Therefore, if you
want to exit in the middle of the switch statement code block, you must insert a break statement,
which causes the program to continue executing after the current code block.
Example,
class ControlStatement{
static void sipleIf(int s){
if(s==10){
System.out.println(s+" is equals to 10");
}
}

static void ifElse(int s){


if(s==10){
System.out.println(s+" is equals to 10");
}
else{
System.out.println(s+" is not equals to 10");
}
}

static void ifElseLadder(int s){


if(s==10){
System.out.println(s+" is equals to 10");
}
else if(s>10){
System.out.println(s+" is greater than 10");
}
else{
System.out.println(s+" is less than 10");
}
}
static void switchCase(int s){
switch(s){
case 1:
System.out.println("One");
break;
case 2:
System.out.println("Two");
break;
default:
System.out.println("Greater than Two");
break;
}
}
public static void main(String ... args){
int value=10;

10
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY
sipleIf(value);
ifElse(value);
ifElseLadder(value);
switchCase(value);
}
}

LOOPING STATEMENTS
While loop statements: while is a looping or repeating statement. It executes a block of code or
a statement till the given condition is true. The expression must be evaluated to a Boolean value.
It continues testing the condition and executes the block of code. When the expression results to
false control comes out of loop. The while loop check the condition at the entry level so it is also
called entry controlled loop.
SYNTAX:
initialization
while(condition){
//statement

increment /decrement
}

do-while loop statements: This is another looping statement that tests the given condition at the
end so you can say that the do-while looping statement is a exit control looping statement. First
the do block statements are executed then the condition given in while statement is checked. So
in this case, even the condition is false in the first attempt, do block of code is executed at least
once.
SYNTAX:
initialization
do{
//statements
increment/decrement

}while(condition);

for loop statements: This is also a loop statement that provides a compact way to iterate over a
range of values. From a user point of view, this is reliable because it executes the statements
within this block repeatedly till the specified conditions are true.
SYNTAX:
for(initialization; condition; increment/decrement){
//Statements
}

11
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY
WHERE initialization: The loop is started with the value specified. Condition: It evaluates to
either 'true' or 'false'. If it is false then the loop is terminated. Increment or decrement: After
each iteration, value increments or decrements.

The for-each version of the for Loop: Beginning with JDK 5, a second form of for was defined
that implements a “for-each” style loop. As you may know, contemporary language theory has
embraced the for-each concept, and it is quickly becoming a standard feature that programmers
have come to expect. A for-each style loop is designed to cycle through a collection of objects,
such as an array, in strictly sequential fashion, from start to finish. Unlike some languages, such
as C#, that implement a for-each loop by using the keyword for-each, Java adds the for-each
capability by enhancing the for statement. The advantage of this approach is that no new
keyword is required, and no pre-existing code is broken. The for-each style of for is also
referred to as the enhanced for loop. The general form of the for-each version of the for is
shown here:
SYNTAX:
for(data-type variableName : arrayOfSameType){
//statement
}
Here, data type specifies the type and variableName specifies the name of an iteration variable
that will receive the elements from a collection, one at a time, from beginning to end.

Nested Loops: Like all other programming languages, Java allows loops to be nested. That is,
one loop may be inside another. For example, here is a program that nests for loops:
SYNTAX:
for(initialization; condition; increment/decrement){
//statements
for(initialization; condition; increment/decrement){
//statements
}
}
For example,
class LoopingStatement{
static void forLoop(int n){
System.out.print("\n FOR LOOP: ");
for(int i=0; i<=n; i++){
System.out.print(i +" ");
}
}
static void whileLoop(int n){
int x=0;
System.out.print("\n WHILE LOOP: ");
while(x<n){
12
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY
System.out.print(x +" ");
x++;
}
}
static void doWhile(int n){
int y=0;
System.out.print("\n DO WHILE LOOP: ");
do{
System.out.print(y+ " ");
y++;
}while(y<n);
}

static void forEach(){


int[] rollNumber ={2,5,4,3,6,7,8,9,100};
System.out.print("\n FOR-EACH LOOP: ");
for(int a : rollNumber){
System.out.print(a+ " ");
}
}
public static void main(String... args){
forLoop(25);
whileLoop(14);
doWhile(10);
forEach();
}
}
BRANCHING STATEMENTS
Break statements: The break statement is a branching statement that contains two forms:
labeled and unlabeled. The break statement is used for breaking the execution of a loop (while,
do-while and for). It also terminates the switch statements.
For example,
for(int a =0 ; a<40; a++){
if(a==3){
break;
}
System.out.print(" "+a);
}
OUTPUT WILL BE:0 1 2

Continue statements: This is a branching statement that is used in the looping statements
(while, do-while and for) to skip the current iteration of the loop and resume the next iteration.
for(int a =0 ; a<6; a++){
if(a==3){
continue;
}
System.out.print(" "+a);
}
OUTPUT WILL BE: 0 1 2 4 5

13
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY
Here in this example the program will print 0, 1, 2, and skip 3 and continue to print 4,5.

Return statements: It is a special branching statement that transfers the control to the caller of
the method. This statement is used to return a value to the caller method and terminates
execution of method. This has two forms: one that returns a value and the other that cannot
return. The returned value type must match the return type of method.
For example,
int addition(){
return 4+5;
}
This program will return 9 as output and we can print as
System.out.println(addition()); it will print 9.

For example,
class BranchingStatement{

public static void main(String argd[]){


System.out.print(returnHello() +" World");
pLine();
makeContinue();
pLine();
doBreak();
}

static String returnHello(){


return "Hello ";
}

static void pLine(){


System.out.print("\n-----------------\n");
}

static void makeContinue(){


for(int x = 0; x<=2;x++){
if(x==1)
continue;
System.out.print(" "+x);
}
}

static void doBreak(){


int[] id ={101,102,103};
for(int i: id){
if(i==102)
break;
System.out.print(" "+i);
}
}
}

14
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY

ARRAY || STRINGS, STRINGBUFFER AND || VECTORS


An array is a group of contiguous or related data items that share a common name. For instance,
we can define an array name rollNumber to represents a set of roll numbers of the students. A
particular value is indicated by writing a number called index number or subscript in brackets
after the array name. For example, rollNumber[5] represents the roll number of 5th students.
While the complete set of values is referred t as an array, the individual values are called
elements. Arrays can be of any variable type and size according to the need of your program.
Java supports two types of arrays as-
1. One-Dimensional array
2. Two-Dimensional array

ONE-DIMENSIONAL ARRAY: A list of items can be given one variable name using only one
subscript and such a variable is called a single-subscript variable or a one-dimensional array. The
subscript value xi refers to the ith elements of x. In java the subscript variable xi can be expressed
as x[0], x[1]…….. x[n] For example, If we want to represents a set of four numbers, say { 42,
52, 32, 63}, by an array variable number, then we may create the variable number as follow:
int number [ ] = new int[5] and the computer reserves four storage location and the values to the
array elements can be assigned as number[0] = 42; number[1] = 52; number[2] = 32; number [3]
= 63;

CREATING AN ARRAY: Like any other variables, array must be declared and created in the
computer’s memory before they are used. Creation of an array involves three steps:
1. Declaring an array
2. Creating memory locations
3. Putting values into the memory locations.

DECLARATION OF AN ARRAY: Array in java is declared in two forms: datatype


arrayName[]; or datatype[] arrayName[]; eg. int rollNumber[]; or int[]
rollNumber;

CREATION OF AN ARRAY: After declaring an array, we need to declare it in the memory.


Java allows us to create arrays using new operator only, as shown below: arrayName = new
datatype[size]; eg. rollNumber = new int[30];

15
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY
The above line creates an
array called rollNumber
of type integer having
size 30. To be more clear
about the arrays the see
the following figure.

INITIALIZATION OF
AN ARRAY: The final
steps are to put values into the array. This process is known as initialization. This is done by
using the array subscript as shown below:
arrayName[subscript] = value; for example number[0] = 45;
We can also initialize arrays automatically in the same way as the ordinary values where they are
declared as shown below: arrayName[] = {list of values}; for example
number[]={4, 56, 85, 9};

ARRAY LENGTH: In java, all arrays stored the allocated size in a variable named length. We
can obtain the length of number using number.length;
Q) Write a java program to sort the numbers in ascending order the array is initialized
automatically.
Soln:-
class SortAscending {
public static void main(String[] args) {
int number[]={42,35,55,90,10};
int n = number.length;
System.out.print("Given Numbers are: ");
for(int i=0;i<n;i++){
System.out.print(" " +number[i]);
}
System.out.println();
//Sorting the given numbers
for(int i=0; i<n;i++){
for(int j=i+1;j<n;j++){
if(number[i]>number[j]){
//swap values
int temp = number[j];
number[j]=number[i];
number[i]=temp;
}
}
}
System.out.print("Sorted Numbers are: ");
16
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY
for(int s:number){
System.out.print(" "+s);
}
}
}
OUTPUT:
Given Numbers are: 42 35 55 90 10
Sorted Numbers are: 10 35 42 55 90

TWO-DIMENSIONAL ARRAY: In java programming there will be a situation where a table


of values is will have to be stored. Consider the table.
The table contains total of 9 values, three of each line. We can think this table as a matrix
consisting of four rows and three columns. The
two dimensional array are stored in the memory
location as shown in the figure.
For creating two-dimensional arrays, we must
follow the same
steps as that of
simple array. We
may create two-
dimensional array
like this: int
myArray[][];
myArray = new
int[3][3]; or
int
myArray[][]=
new int[3][3];
This creates a table
that can store 9
integer values, four cross and three down. Like the one-dimensional array, two-dimensional
array may be initialized be following:
int table[][]={{0,0,0},{1,1,1},{2,2,2}};
Q) Write a program to print the multiplication table using matrix;
public class PrintTable {
final static int ROW=11;
final static int COLUMN=11;

public static void main(String[] args) {


int product[][] = new int[ROW][COLUMN];
System.out.println("MULTIPLICATION TABLE");
for(int i =1;i<=10; i++){
for(int j=1;j<=10; j++){
product[i][j]=i*j;
17
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY
System.out.print(" " +product[i][j]);
}
System.out.println();
}
}
}
OUTPUT:
MULTIPLICATION TABLE
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100

STRING: String manipulation is the most common part of many java programs. String
represents a sequence of characters. The easiest way to represent a sequence of characters in java
is by using a character array. For example char name[] = new char [5];
name[0]='S'; name[1]='U'; name[2]='N'; name[3]='I'; name[4]='L';
In java, strings are class objects and implemented using two classes String and StringBuffer.
String may be declared and created as follow: String stringName;
stringName = new
String("VALUE OF STRING");
for example, String name; name = new String("SUNIL"); or String name =
new String("SUNIL");

STRING ARRAY: We can also create and use arrays that contains string. The statement
String itemString[]=new String[10]; will create itemString of size 10.

STRING METHODS: The string class defines a numbers of method that allows us to
accomplish a variety of string manipulation tasks. The following are some common method of
string widely used. For example, toLowerCase(), toUpperCase(), replace(),
trim(), equals(), equalsIgnoreCase(),length(), charAt(),
compareTo(),concat(), subString(), valuesOf(),indexOf()..etc.

Q) Write a program to sort an array of string to alphabetical order.


class StringOrdering {
static String name[]={"Sunil", "Surya", "Deepak", "Raju"};
public static void main(String[] args) {
String temp;
int size= name.length;
//printing original array of string
System.out.print("Given Name List: ");
for(String n: name){

18
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY
System.out.print(" " +n);
}
//swapping
for(int i=0;i<size;i++){
for(int j=i+1;j<size;j++){
if(name[i].compareTo(name[j])>0){
temp=name[j];
name[j]=name[i];
name[i]=temp;
}
}
}
//printing sorted array
System.out.print("\nSorted Name List: ");
for(String s: name){
System.out.print(" "+s);
}
}
}
OUTPUT:
Given Name List: Sunil Surya Deepak Raju
Sorted Name List: Deepak Raju Sunil Surya

STRING BUFFER CLASS: StringBuffer is a peer class of String. While String creates string
of fixed length, StringBuffer creates Strings of flexible length that can be modified in items of
both length and content. We can insert characters and substrings in the middle of the string, or
append another string to the end. It supports various method, the commonly used methods are:
setCharAt(n, 'X'), append(s2), insert(n, s2), setLength(n)...etc

Q) Write a program that shows the operation manipulation of string in StringBuffer.


class StringBufferExample{
public static void main(String[] args) {

StringBuffer sb = new StringBuffer("Hello this is from KCC college");

System.out.println("original: " + sb);

System.out.println("length(): " + sb.length() + ", capacity(): " +


sb.capacity());

System.out.println("charAt(2): " + sb.charAt(2));

System.out.println("codePointAt(7): " + sb.codePointAt(7));

System.out.println("append(): " + sb.append(" by Sunil Bahadur Bist"));

System.out.println("insert(): " + sb.insert(7, "[INSERT THIS FROM KCC] "));

System.out.println("indexOf():" + sb.indexOf("[INSERT THIS FROM KCC]"));

19
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY
System.out.println("delete(): " + sb.delete(7, 7+ "[INSERT THIS] ".length()));

System.out.println("substing(): " + sb.substring(31,39));

System.out.println("reverse(): " + sb.reverse());


}
}
OUTPUT WILL BE:
original: Hello this is from KCC college
length(): 30, capacity(): 46
charAt(2): l
codePointAt(7): 104
append(): Hello this is from KCC college by Sunil Bahadur Bist
insert(): Hello t[INSERT THIS FROM KCC] his is from KCC college by Sunil Bahadur Bist
indexOf():7
delete(): Hello tROM KCC] his is from KCC college by Sunil Bahadur Bist
substing(): college
reverse(): tsiB rudahaB linuS yb egelloc CCK morf si sih ]CCK MORt olleH

Vector
Java J2SE 5.0 version supports the concept of variable arguments to methods. This feature can
also be achieved in java through the use of Vector class contained in the java.util package. This
class can be used to create a generic dynamic array known as Vector that can hold objects of any
type and any numbers.
Vector implements a dynamic array. It is similar to ArrayList, but with two differences:
 Vector is synchronized.
 Vector contains many legacy methods that are not part of the collections framework.
Vector proves to be very useful if you don't know the size of the array in advance or you just
need one that can change sizes over the lifetime of a program.
Vectors process a numbers of advantages over arrays:
a) It is convenient to used vectors to store objects
b) A vector can be used to store a list of objects that may vary in size
c) We can add and delete objects from the list as and when required

Below given is the list of constructors provided by the vector class.


1. Vector ( ): This constructor creates a default vector, which has an initial size of 10
2. Vector (int size): This constructor accepts an argument that equals to the required size, and
creates a vector whose initial capacity is specified by size

20
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY
3. Vector (int size, int incr): This constructor creates a vector whose initial capacity is
specified by size and whose increment is specified by incr. The increment specifies the number
of elements to allocate each time that a vector is resized upward

4. Vector (Collection c): creates a vector that contains the elements of collection c

Apart from the methods inherited from its parent classes, Vector defines the following
methods:
1. void add(int index, Object element): Inserts the specified element at the specified position in
this Vector.
2. Object lastElement(): Returns the last component of the vector.
3. boolean add(Object o): Appends the specified element to the end of this Vector.
4. int size(): Returns the number of components in this vector.
5. Object firstElement(): Returns the first component (the item at index 0) of this vector.
6. void addElement(Object obj): Adds the specified component to the end of this vector,
increasing its size by one.
7. boolean addAll(Collection c): Appends all of the elements in the specified Collection to the
end of this Vector, in the order that they are returned by the specified Collection's Iterator.
8. int capacity(): Returns the current capacity of this vector.
9. boolean addAll(int index, Collection c): Inserts all of the elements in in the specified
Collection into this Vector at the specified position.
---------------
--------------etc
For more: http://www.tutorialspoint.com/java/java_vector_class.htm
import java.util.Enumeration;
import java.util.Vector;

public class VectorExample {


public static void main(String args[]) {

// initial size is 3, increment is 2


Vector<Integer> v = new Vector<Integer>(3, 2);
System.out.println("Initial size: " + v.size());
System.out.println("Initial capacity: " +
v.capacity());
v.add(1);
v.addElement(new Integer(2));
v.addElement(new Integer(3));
v.addElement(new Integer(4));

21
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY
System.out.println("Capacity after four additions: " +
v.capacity());
v.addElement(new Integer(11));
v.addElement(new Integer(12));

System.out.println("First element: " + (Integer)v.firstElement());


System.out.println("Last element: " + (Integer)v.lastElement());

if(v.contains(new Integer(3)))
System.out.println("Vector contains 3.");

// enumerate the elements in the vector.


Enumeration<Integer> vEnum = v.elements();

System.out.println("\nElements in vector:");
while(vEnum.hasMoreElements())
System.out.print(vEnum.nextElement() + " ");
System.out.println();
}
}

Another example,
import java.util.*;

public class AnotherVectorExample {

public static void main(String args[]) {


/* Vector of initial capacity(size) of 2 */
Vector<String> vec = new Vector<String>(2);

/* Adding elements to a vector*/


vec.addElement("Apple");
vec.addElement("Orange");
vec.addElement("Mango");
vec.addElement("Fig");

/* check size and capacityIncrement*/


System.out.println("Size is: "+vec.size());
System.out.println("Default capacity increment is: "+vec.capacity());

vec.addElement("fruit1");
vec.addElement("fruit2");
vec.addElement("fruit3");

/*size and capacityIncrement after two insertions*/


System.out.println("Size after addition: "+vec.size());
System.out.println("Capacity after increment is: "+vec.capacity());

/*Display Vector elements*/


Enumeration<String> en = vec.elements();
System.out.println("\nElements are:");
while(en.hasMoreElements())
System.out.print(en.nextElement() + " ");
}
}

22
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY

Object - Objects have states and behaviors. Example: A dog has states - color, name, breed as
well as behaviors -wagging, barking, and eating. An object is an instance of a class.

o Let us now look deep into what are objects. If we consider the real-world we can
find many objects around us, Cars, Dogs, Humans, etc. All these objects have a
state and behavior.
o If you compare the software object with a real world object, they have very
similar characteristics.
o Software objects also have a state and behavior. A software object's state is stored
in fields and behavior is shown via methods.
o So in software development, methods operate on the internal state of an object
and the object-to-object communication is done via methods.

Class - A class can be defined as a template/blue print that describes the behaviors/states that
object of its type support.

A class can contain any of the following variable types.

 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 with in a class, outside any
method, with the static keyword.

A class can have any number of methods to access the value of various kinds of methods. In the
above example, barking (), hungry () and sleeping () are methods.

Q. Create a class HelloWorld that has main method to print “HELLO WORLD!!!” and a method
sayHelloAgain() to repeat the “Hello Again” message in the screen

class HelloWorld{
public static void main(String args[]){
System.out.print("HELLO WORLD!!!");
sayHelloAgain();
}
static void sayHelloAgain(){
System.out.printf("Hello Again");
}
23
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY
}

Q. Create a class Apple having id, name, color, size, price and currency as instance variable.
Create two method one is used to setApple() and another is getApple(). Now create main method
and create 5 instance and call setApple(), and getApple() from the consol.

class Apple{
int id;
String name, color, size;
double price;
char currency;

void setApple(int id, String name, String color, String size, double price,
char currency){
this.id=id;
this.name=name;
this.color=color;
this.size=size;
this.price=price;
this.currency=currency;
}
void getApple(){
System.out.println("ID: "+id +". NAME:"+name +"\t COLOR:"+color + "\t
SIZE: "+size+ "\t PRICE: "+price+currency);
}

public static void main(String args[]){


Apple a= new Apple();
Apple a1= new Apple();
Apple a2= new Apple();
Apple a3= new Apple();
Apple a4= new Apple();
a.setApple(1, "Nepali Apple","Red", "Small",200.57,'$');
a.getApple();
a1.setApple(2, "Indian Apple","Red", "Mediun",650.57,'$');
a1.getApple();
a2.setApple(3, "Chinese Apple","Red", "Large",450.57,'$');
a2.getApple();
a3.setApple(4, "Korian Apple","Red", "Medium",150.57,'$');
a3.getApple();
a4.setApple(5, "USA Apple","Red", "Extra Large",350.57,'$');
a4.getApple();
System.out.println("--------------------------------------------");
}
}

Q. Create a class Ball having id, name, color, price, weight and currency as instance variable and
one method is used to setBall() and two methods is used to getBall() will return nothing and
getBallInfo() will return string. Now create an instance of Ball to set and display information of
Ball from main Method.

class Ball{
int id;
String name;
String color;
24
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY
double price;
double weight;
char currency;
void setBall(int id, String name, String color, double price,
double weight, char currency){
this.id = id;
this.name = name;
this.color = color;
this.price = price;
this.weight = weight;
this.currency = currency;
}
void getBall(){
System.out.print("ID: "+id + " NAME: "+name +" COLOR: "+
color + " PRICE: "+price +currency+" WEIGHT: "+ weight+"\n");
}
String getBallInfo(){
return "ID: "+id + " NAME: "+name +" COLOR: "+ color + "
PRICE: "+price +currency+" WEIGHT: "+ weight+"\n";
}
public static void main(String... args){
Ball objName = new Ball();
objName.setBall(1, "Foot Ball","Red", 2500,150,'$');
objName.getBall();
String a= objName.getBallInfo();
System.out.print(a);
System.out.print(objName.getBallInfo());
}
}

Q. Create a class Calculator having addition (int ... n), subtraction (int x, int y), multiplication
(int... n) and subtraction (int a, int b); Now create an instance of Class and call all the methods
and pass parameter according to the method signature created.
class Calculator{
public static void main(String a[]){
Calculator c = new Calculator();
c.addition(8, 9, 6);
c.subtraction(40, 20);
c.multiplication(4, 5, 6);
c.division(40, 10);
}
void addition(int ... n){
int sum = 0;
for(int x : n){
sum+=x;
}
System.out.println("Addition of "+ n.length + " parameter is "+ sum);
}
void subtraction(int x, int y){
System.out.println(" x - y :"+(x-y));
}
void multiplication(int... n){
int mul = 1;
for(int x : n){
25
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY
mul*=x;
}
System.out.println("Multiple of "+ n.length + " parameter is "+ mul);

}
void division(int a, int b){
System.out.println("a/b"+ (a/b));
}
}

Q. Create a class Course having id, code, name, credit; description as instance varible and One
constructor used to initialize default values and two methods one setCource(), and getCourse();
Now create main method that creates an instance of class and Call all the methods and display
result to console.
class Course{
int id;
String code;
String name;
int credit;
String description;

Course(){
id =1;
code = "BIT123-CO";
name = "Advance Object Oriented Programming";
credit =4;
description ="Programming Language used to develop application s/w";
}

void setCourse(int id, String code, String name, int credit, String
description){
this.id = id;
this.code = code;
this.name = name;
this.credit = credit;
this.description = description;
}
void getCourse(){
System.out.println("Id: "+id + " Name: "+ name + " Credit: "+credit +
"Description: "+ description);
}
public static void main(String... arv){
Course c = new Course();
c.getCourse();
c.setCourse(2,"BIT-170-CO", "Fundamentals of IT",3, "Course related to
fundamental knowledge.");
c.getCourse();
}
}

Q. Create a class Employee having id, name and salary as instance variable and two methods
setEmployeeInfo() and getEmployeeInfo() to set and print information. Now create main method
and declare 5 size array of object then initialize the array object now assign the difference value
and call the metnods getEmployeeInfo() using fore-each loop.
26
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY

class Employee{
int id;
String name;
double salary;
void setEmployeeInfo(int id, String name, double salary){
this.id = id;
this.name = name;
this.salary = salary;
}
void getEmployeeInfo(){
System.out.println(" ID: "+ id + " NAME: "+ name + " SALARY: "+salary);
}
public static void main(String... args){
Employee emp[] = new Employee[5];
for(int i= 0; i<emp.length; i++){
emp[i] = new Employee();
}
emp[0].setEmployeeInfo(1,"SUNIL", 50000);
emp[1].setEmployeeInfo(2,"SAROJ", 100000);
emp[2].setEmployeeInfo(3,"NABIN", 50000);
emp[3].setEmployeeInfo(4,"BHAWANA", 50000);
emp[4].setEmployeeInfo(5,"KAPIL", 50000);

for(Employee e : emp){
e.getEmployeeInfo();
}
}
}

Q. Create a class Student having id, name and gpa as instance variable and one constructor to
assign values to the instance variable and create show () method to display information of the
Student to the screen. Now create a 5 size arry of object and assign values and call show ()
method using fore-each loop.
class Student{
int id;
String name;
double gpa;
Student(int id, String name, double gpa){
this.id = id;
this.name = name;
this.gpa = gpa;
}
void show(){
System.out.println("ID: "+id+ " NAME: "+ name + " GPA: "+gpa);
}
public static void main(String... args){
Student std[] = new Student[5];

std[0] = new Student(1, "ANIB", 4.0);


std[1] = new Student(2, "SUDARSAN", 3.1);
std[2] = new Student(3, "ROSHAN", 3.5);
std[3] = new Student(4, "PHURPA", 4.0);
std[4] = new Student(5, "ASHIM", 2.5);
27
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY

for(Student s : std){
s.show();
}
}
}

Q. Create a class BCA having name as instance variable which holds name of 24 student create a
method to set name of 24 students from setStudentName()and another displayStudentName().
Now create main method to set and display information to the Screen

import java.util.Scanner;

public class BCA {


String[] names = new String[24];
void setStudentName(){
Scanner s = new Scanner(System.in);
for(int i =0;i<names.length;i++){
names[i]=s.nextLine();
}

void displayStudentName(){
System.out.println("Name List of BCA 5th Semester
Students");
int c =1;
for(String n: names){
System.out.println(c+ ". "+n);
c++;
}
}
public static void main(String[] args) {
BCA bca = new BCA();
bca.setStudentName();
bca.displayStudentName();
}

INHERITANCE
The process of deriving a new class from an old one is called inheritance or derivation. The old
class is referred to as the base class or super class or parent class and new one is called
the derived class or subclass or child class. The derived class inherits some or all of the
properties from the base class. A class can inherit properties from more than one class or
from more than one level.

28
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY
The main purpose of derivation or inheritance is reusability. Java strongly supports the
concept of reusability. The Java classes can be reused in several ways. Once a class has been
written and tested, it can be used by another by another class by inheriting the
properties of parent class.

Defining a subclass
A subclass can be defined as follows:
class SubClassName extends SuperClassName{
// instance variables

//Methods
}

The keyword extends signifies that the properties of the SuperClassName are extended
to the SubClassName. The subclass will now contain its own variables and methods as well
those of the super class. This kind of situation occurs when we want to add some more
properties to an existing class without actually modifying it.

Types of inheritance
The following kinds of inheritance are there in java.
 Simple Inheritance
 Multilevel Inheritance
 Hierarchical Inheritance
 Multiple Inheritance
 Hybrid Inheritance
In java programming, Multiple and Hybrid inheritance is not directly supported. It is supported
indirectly by using interface.
Simple Inheritance
When a subclass is derived simply from it's parent class then this mechanism is known as simple
inheritance or (a parent class with only one child class is known as single inheritance).
In case of simple inheritance there is only one subclass and it's parent class. It is also called
single inheritance or one level inheritance.

Vehicle

Car
29
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY
Pictorial Representation of Simple Inheritance
For Example,
class Parent
{
int x;
int y;
void get(int p, int q)
{
x=p; y=q;
}
void Show()
{
System.out.println("x=" +x + " and y= " +y);
}
}
class Child extends Parent
{
public static void main(String args[])
{
Parent p = new Parent();
p.get(5,6);
p.Show();
}
}

Subclass constructor
A subclass constructor is used to construct the instance variables of both the subclass
and the superclass. The subclass constructor uses the keyword super to invoke the constructor
method of the superclass. The keyword super is used as
- Super may only be used within a subclass constructor method.
- The call to superclass constructor must appear as the first statement within the
subclass constructor.
- The parameters in the super call must match the order and type of the instance
variable declared in the superclass.
For Example, WAP that demonstrate the use of the keyword super
class Room
{
int length;
int breadth;
Room(int x, int y)
{
length= x;
breadth = y;
}
int area()
30
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY
{
return(length*breadth);
}
}
class BedRoom extends Room
{
int height;
BedRoom(int
x, int y, int z)
{
super(x,y);
//call the superclass constructor with value x and y
height = z;
}
int volume()
{
return(length*breadth*height);
}
}

class SuperTest
{
public static void main(String args[])
{
BedRoom room1 = new BedRoom(2,3,4);//call subclass
constructor
int area1 = room1.area();//superclass method
int volume1 = room1.volume();//call subclass method
System.out.println("Area of the room is= " +area1);
System.out.println("Volume of the bedroom is = " +volume1);
}
}

Multilevel Inheritance
When a subclass is derived from a derived class then this mechanism is known as the multilevel
inheritance. The derived class is called the subclass or child class for it's parent class
and this parent class works as the child class for it's just above (parent) class. Multilevel
inheritance can go up to any number of levels.

Vehicle

Car

RacingCar
Pictorial Representation of Simple and Multilevel Inheritance

31
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY
In Multilevel Inheritance a derived class with multilevel base classes is declared as follows:
class vehicle{
//Instance variables;
//Methods;
}
class Car extends Vehicle{
//first level
//Instance variables;
//Methods;
//..............

}
class RacingCar extends Car{
//second level
//Instance variables;Methods;
//..................................
}
Q. WAP that demonstrate the concept of multilevel inheritance class

class Student{
int roll_number;
Student(int x){
roll_number = x;
}
void put_number(){
System.out.println("Roll number = " +roll_number);
}
}
class Test extends Student{
double sub1;double sub2;
Test(int a, double b, double c){
super(a);
sub1 = b;sub2 = c;
}
void put_marks(){
System.out.println("Marks in subject first is = " +sub1);
System.out.println("Marks in subject second is = " +sub2);
}
}
class Result extends Test{
double total;
Result(int a, double b, double c){
super(a,b,c);
}void display(){
total = sub1 +sub2;
put_number();
put_marks();
System.out.println("Total marks = " +total);
}
}
class MultiLevelDemo{
public static void main(String args[]){
32
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY
Result ram = new Result(5,55.5,67.5);
ram.display();
}
}
Hierarchical Inheritance
As you can see in the diagram below that when a class has more than one child classes (sub
classes) or in other words more than one child classes have the same parent class then such kind
of inheritance is known as hierarchical

WAP to demonstrate the hierarchical inheritance


class A{
public void methodA(){
System.out.println("method of Class A");
}
}
class B extends A{
public void methodB(){
System.out.println("method of Class B");
}
}
class C extends A{
public void methodC(){
System.out.println("method of Class C");
}
}
class D extends A{
public void methodD(){
System.out.println("method of Class D");
}
}
class MyClass{
public void methodB(){
System.out.println("method of Class B");
}
public static void main(String args[]) {
B obj1 = new B();
C obj2 = new C();
D obj3 = new D();
obj1.methodA();
obj2.methodA();
obj3.methodA();
33
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY
}
}
Java Does not support Multiple and Hybrid inheritance directly it is supported by package
and interface
VISIBILITY CONTROL
There are mainly three types of visibility control that are used to restrict the access to
certain variables and methods from outside the class. The visibility modifiers are also known as
access modifiers. They provide different level of protection as described below they follow the
following syntax.
Syntax:
visibility-control type variablename;
visibility-control type methodname(arglist){.................}

Public Access Members (Variables or methods) that are declared as public are known as public
member of the class. Those members shave widest level of visibility. Those members that are
declared as public can have access from same class, subclass in same package, other
classes in same package, subclass in other packages and non-subclasses in other packages.
Protected Access Members that are declared as protected are known as protected members. The
protected modifier makes the fields visible not only to all classes and subclasses in the
same package but also to subclasses in other packages. Protected members are not accessible
from non-subclasses in other packages.

Private Access Members that are declared as private are known as private members. The
private modifier makes field visible only within their own class. They cannot be inherited by
subclasses and therefore not accessible in subclasses.

34
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY

Q. Create a class Person having id and name as instance variable. Create a Constructor to
initialize an instance variable of class Person. Declare a method showPerson(void) that will
display the id and name of Person.

Create a subclass Student having gpa as instance variable and a constructor to initialize instance
variable and a method showStudent(void) to display the gpa of Student. Create another class
StudentDemo having main method and declare a 5 size array of Student and initialize the values
and display id, name and gpa of Student.

class Person{
int id;
String name;
Person(int id, String name){
this.id = id;
this.name = name;
}
void showPerson(){
System.out.print("ID: "+id+ " NAME: "+name);
}
}

class Student extends Person{


double gpa;
Student(int id, String name, double gpa){
super(id, name);

35
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY
this.gpa = gpa;
}
void showStudent(){
System.out.println(" GPA: "+gpa);
}
}

class StudentDemo{
public static void main(String... args){
Student std[] = new Student[5];
std[0] = new Student(1,"Roshan", 3.5);
std[1] = new Student(2,"Sudarsan", 4.0);
std[2] = new Student(3,"Anib", 3.56);
std[3] = new Student(4,"Ashim", 2.5);
std[4] = new Student(5,"Sandesh", 1.5);

for(Student s : std){
s.showPerson();
s.showStudent();
}
}
}

Q. Create a class Person having id and name as instance variable. Create a Constructor to
initialize an instance variable of a class Person. Declare a method showPerson(void) that will
display id and name of Person.

Create a subclass Employee having salary as instance variable and a constructor to initialize
instance variable and a method showEmployee(void) to display the salary of Employee. Create
another class EmployeeDemo having main method, declare a 3 size array object of Employee to
initialize the values and display id, name and salary of Employee.

class Person{
int id;
String name;
Person(int id, String name){
this.id = id;
this.name = name;
}
void showPerson(){
System.out.print("ID: "+id+ " NAME: "+name);
}
}

class Employee extends Person{


double salary;
Employee(int id, String name, double salary){
super(id, name);
this.salary = salary;
}
36
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY
void showEmployee(){
System.out.println(" SALARY: "+salary);
}
}

class EmployeeDemo{
public static void main(String... args){
Employee emp[] = new Employee[4];
emp[0] = new Employee(1,"SUNIL", 30000);
emp[1] = new Employee(2,"BHAWANA", 30000);
emp[2] = new Employee(3,"KAPIL", 30000);

for(Employee e : emp){
e.showPerson();
e.showEmployee();
}
}
}

POLYMORPHISM

Polymorphism is the ability of an object to take on many forms. The most common use of
polymorphism in OOP occurs when a parent class reference is used to refer to a child class
object. It is important to know that the only possible way to access an object is through a
reference variable. A reference variable can be of only one type. Once declared, the type of a
reference variable cannot be changed. The reference variable can be reassigned to other objects
provided that it is not declared final. The type of the reference variable would determine the
methods that it can invoke on the object. A reference variable can refer to any object of its
declared type or any subtype of its declared type. A reference variable can be declared as a class
or interface type.

For example,
Q. Create a class Animal which have eats(void) method and Three Sub-class Bird, Dog and Fish
and override the eat(void) method of parent class, Create another calss PolyDemo and create
three size 3 object array of Animal and create the objects of all child class and call the eat(void)
method using for-each loop that must meet polymorphism.

public class Animal {


void eat(){
System.out.print("Digestable Things");
}
}

public class Bird extends Animal{


@Override

37
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY
void eat(){
System.out.print("Bird eats Fish!");
}
}

public class Dog extends Animal {


void eat(){
System.out.print("Dog eats Meat!");
}
}

public class Fish extends Animal{


void eat(){
System.out.print("Fish eats Gadaula");
}
}

public class PolyDemo {

public static void main(String[] args) {


Animal[] a = new Animal[3];

Fish f = new Fish();


Bird b = new Bird();
Dog d = new Dog();

a[0]=b;
a[1]=d;
a[2]=f;
for(Animal z: a){
z.eat();
}
}
}

Q. Create a class Shape having draw(void) method and create three sub-classes Box, Triangle,
and Rectangle and override draw(void) method. Now Create another Class PolyDemo having
main method and create 3 size array of Shape class and store thr objects of the three-sub class
and finally call the draw(void) method by using for-each loop that must meet concept of
polymorphism.
public class Shape {
void draw(){
System.out.println("This is Shape!");
}
}

public class Box extends Shape {


void draw(){
38
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY
System.out.println("Draw a Box!");
}
}

public class Rectangle extends Shape {


void draw(){
System.out.println("Draw a Rectangle!");
}
}

public class Triangle extends Shape {


void draw(){
System.out.println("Draw a Triangle!");
}
}
public class PolyDemo {
public static void main(String[] args) {
Shape[] s = new Shape[3];

Rectangle r = new Rectangle();


Box b = new Box();
Triangle t = new Triangle();

s[0]=b;
s[1]=r;
s[2]=t;
for(Shape z : s){
z.draw();
}

}
}
PACKAGE

A package is a namespace that organizes a set of related classes and interfaces. Conceptually you
can think of packages as being similar to different folders on your computer.

Software written in Java programming language can be composed of hundreds or thousands of


individual classes; it makes sense to keep things organized by placing related classes and
interfaces into packages.

STEPS TO CREATE PACKAGE

1. Declare a package at the beginning of a file using the form: package packagename;
2. Define the class that is to be put in the package and declare it public
3. Define methods that we want to put inside the class as public
4. Create a sub-directory under the directory where the main source files are stored. Where as the
name of sub-directory is exactly same as package name eg. E:\java8\student

39
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY
5. Store the source file as the ClassName.java file in the sub-directory created eg.
E:\java8\student\
6. Compile the java file. This creates .class file inside the subdirectory E:\java8\student\
7. To use this package include E:\java8 path in CLASSPATH environment variable.

Q. Create a package student and put a class Student inside that package; Student having id,
name gpa and description as instance variable and two methods one is setStudent() and
getStudent() to set and display information.

Now create a class College and import the package student call create an instance of class
Student and set and display the information in the screen.

package student;
public class Student{
int id;
String name;
double gpa;
String description;

public void setStudent(int id, String name, double gpa, String


description){
this.id = id;
this.name = name;
this.gpa = gpa;
this.description = description;
}
public void getStudent(){
System.out.print(" ID:"+id+ " NAME:"+" "+name+ " "+"
GPA:"+gpa+ " DESCRIPTION:"+description +"\n");
}
}

import student.Student;
class College{
public static void main(String... args){
Student s = new Student();
s.setStudent(1, "RAM",3.5,"Good Student");
s.getStudent();
}
}

Q. Create a package employee and add three classes Person, Employee, Salary. Person class has
id, name gender, and dateOfBirth as instance variable and one constructor which are used to
initialize instance variable given by the user and one method to display the information of
Person.

Create sub-class Employee from Person, Employee class has designation as instance variable and
One constructor to set values and one method to display information of Employee. Finally create

40
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY
sub-class Salary from Employee, Employee class has basicSalary and bonous as instance
variable and one constructor to set and a method to display salary and bonous information of
Employee.

Finally create a class College having main method and import the package and create an
instance of Salary and call necessary methods to set and display values to the screen

package employee;
public class Person{
int id;
String name;
String gender;
String dateOfBirth;

public Person(int id, String name, String gender, String


dateOfBirth){
this.id = id;
this.name = name;
this.gender = gender;
this.dateOfBirth = dateOfBirth;
}
public void displayPerson(){
System.out.print(" ID: " +id+" NAME: "+name + " GENDER:
"+gender + " DATE OF BIRTH: "+dateOfBirth);

package employee;
public class Employee extends Person{
String designation;
public Employee(int id, String name, String gender, String
dateOfBirth, String designation){
super(id, name, gender,dateOfBirth);
this.designation = designation;
}
public void displayEmployee(){
System.out.print( " DESIGNATION: "+ designation);
}

package employee;
public class Salary extends Employee{
double basicSalary;
double bonus;
public Salary(int id, String name, String gender, String
dateOfBirth, String designation, double basicSalary, double bonus){
super(id, name, gender,dateOfBirth,designation);
this.basicSalary = basicSalary;
this.bonus =bonus;
}
41
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY
public void displaySalary(){
System.out.print( " BASIC PAY: "+ basicSalary + " BONUS:
"+bonus +"\n");
}
}

New Set CLASSPATH variable and paste the path of root Folder and create a Class as follow
and compile and run:

import employee.*;
class College{
public static void main(String... args){

Salary std = new Salary(1, "SUNIL", "MALE", "2040-01-


20","LECTUROR",35000,25000);
std.displayPerson();
std.displayEmployee();
std.displaySalary();
}
}

INTERFACE

Java does not support multiple inheritance directly, that is classes in java cannot have more than
one super class. For instance, a definition like: class Apple extends BerryApple,
CuteApple{
......
......
} is not permitted in java.

Java provides an alternative approach known as interface to support the concept of multiple
inheritances.

An interface is basically a kind of class. Like classes interface contains methods and variables
but the difference is that interface defines only abstract method ie. the methods that do not have
body and final fields.

This means that interface does not specify and code to implement methods and data fields
contains any constants. It is the responsibility of that class who use the interface has to
implement all the methods to be defines inside the interface.

Syntax:

access-specifier interface InterfaceName{


data-type VARIABLE_NAME = VALUE;
.....
.....
return-type methodName(parameters);
.....
.....
}

42
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY

Q. Create an interface having four method changeCadence(int newValue),changeGear(int


newValue), speedUp(int increment), and applyBrakes(int decrement) and Declare a class
ACMEBicycle that implements all the methods of an interface Bicycle, Declare a method
printStates() to display the status of the Bicycle. Now Create another class Called InterfaceDemo
and create instance and call necessary methods of ACMEBicycle.
Soln:
interface Bicycle {
// wheel revolutions per minute
void changeCadence(int newValue);
void changeGear(int newValue);
void speedUp(int increment);
void applyBrakes(int decrement);
}
class ACMEBicycle implements Bicycle {

int cadence = 0;
int speed = 0;
int gear = 1;

public void changeCadence(int newValue) {


cadence = newValue;
}

public void changeGear(int newValue) {


gear = newValue;
}

public void speedUp(int increment) {


speed = speed + increment;
}

public void applyBrakes(int decrement) {


speed = speed - decrement;
}

public void printStates() {


System.out.println("cadence:" +
cadence + " speed:" +
speed + " gear:" + gear);
}
}

class InterfaceDemo{
public static void main(String... args){
ACMEBicycle aBike = new ACMEBicycle();
aBike.changeGear(2);
aBike.printStates();
}

43
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY
}

Q. Create a class named StudentInfo that has instance variables first name, last name and
address. Make suitable methods to set values. Then create another interface ClassInfo with two
methods showclass(int) and showMajorSubject(String). Create a derived class Info that inherits
StudentInfo and ClassInfo and displays total information. Make a class StudentShow that creates
objects of necessary classes.

public class StudentInfo{


String firstName;
String lastName;
String address;

public void setStudentInfo(String a, String b, String c){


firstName=a;
lastName=b;
address=c;
}
public void getStudentInfo(){
System.out.print("Frist Name: "+firstName+" Last Name: "+lastName+"
Address:"+address+ "\n");
}
}

public interface ClassInfo{


void showClass(int sClass);
void showMajorSubect(String sMajor);
}

public class Info extends StudentInfo implements ClassInfo {


@Override
public void showClass(int sClass) {
System.out.print("Class: "+sClass);
}

@Override
public void showMajorSubect(String sMajor) {
System.out.print(" Major Subject: "+sMajor);

}
}

public class StudentShow{


public static void main(String... ar){
Info in= new Info();
in.setStudentInfo("Prabin","Shrestha","kavre");
in.getStudentInfo();
in.showClass(11);
in.showMajorSubect("Java Programming");
}
}
EXCEPTION HANDLING
44
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY
Error
It is common to make mistakes while developing as well as typing a program. A mistake might
lead to an error causing the program to produce unexpected results. An error may produce
an incorrect output or may terminate the execution of the program abruptly of even may cause
the system to crash. It is therefore important to detect and manage properly all the
possible error conditions in the program so that the program will not terminate or crash during
execution.

Types of errors
Errors are broadly classified into two categories:
 Compile time errors
 Run-time errors
Compile time errors: Those errors that encounter at compilation time are known as
compile time errors.
All syntax errors will be detected and displayed by the java compiler and therefore these errors
are known as compile time errors. Whenever the compiler displays an error, it will not create the
.class file. It is therefore necessary that all the errors should be fixed before successfully compile
and run the program. Most of the compile time errors are due to typing mistakes. The
most common compile time errors are:
 Missing semicolon
 Missing (or mismatch of) brackets in classes and methods
 Misspelling of identifiers and keywords
 Missing double quotes in string
 Use of undeclared variables
 Incompatible types in assignment/initialization
 Bad reference to objects
 And so on.

Run time errors


All the errors that encounter at run time are known as run time errors. During runtime
errors a program may compile successfully creating the .class file but may not run
properly. Such programs may produce wrong results due to wrong logic or may terminate
due to errors. Most common runtime errors are:
45
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY
 Dividing an integer by zero.
 Accessing an element that is out of the bounds of an array.
 Trying to store a value into an array of an incompatible class or type.
 Trying to cast an instance of a class to one of its subclasses
 Passing a parameter that is not in a valid range or value for a method
 Trying to illegally change the state of a thread
 Attempting to use a negative size for an array
 Converting invalid string to a number
 Accessing a character that is out of bounds of a string
 And so on.

Exceptions
An exception is a condition that is caused by a runtime error in the program. When the
Java interpreter encounters an error such as dividing an integer by zero, it creates an exception
object and throws (i.e., inform us that an error has occurred)
If the exception object is not caught and handled properly, the interpreter will display an
error message and will terminate the program. To continue the program execution, we should
try to catch the exception object thrown by the error condition and then display an appropriate
message for taking corrective actions. This task is known as exception handling. The purpose of
exception handling is to provide a means to detect and report an exceptional circumstance
so that appropriate action can be taken.

Java exception handling is managed by five keywords: try, catch, throw, throws and finally
Program statements that may generate exception are contained within try block. If an exception
occurs within the try block, it is thrown. Those statements that are used to catch those
exceptions are kept in catch block and handled in some relational manner. System generated
exceptions are automatically thrown by the java runtime system. To manually throw an
exception, use the keyword throw. Any exception that is thrown out of a method must be
specified as such by a throws clause. Any code that absolutely must be executed before
a method returns is put in a finally block.

Exception hierarchy

46
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY

Syntax:
try {
//code of block that may cause runtime error
}
catch (ExceptionType e) {
// code to handle exception
}
finally{
….
}
Multiple catch statement syntax:
try {
//code of block that may cause runtime error
}
catch (ExceptionType e) {
// code to handle exception
}
catch(ExceptionType2 e2){

}
.
.
catch(ExceptionTypeN en){

}
finally{

}

Syntax for throws


return-type methodname(parameters) throws ExceptionType{
…………………………………………
throw ExceptionType;
}

47
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY
Q. Program which includes try and catch block that processes the ArithmeticException
generated by the division-by-zero error.
public class ArithmaticExceptionExample {
public static void main(String[] args) {

int a,b;
try{
b = 0;
a = 12/b;
System.out.println(" Inside try block");
}
catch(ArithmeticException e){
System.out.println("Division by zero.");
}
System.out.println("Outside try and catch block");
}
}

Q. Write a program that demonstrate the concept of multiple catch blocks


class MultipleCatch{
public static void main(String args[]){
int a[] = {5,10};
int b = 5;
try{
int x = a[2]/(b-a[1]);
}
catch(ArithmeticException e){
System.out.println("Divisionby zero");
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("Array index error");
}
catch(ArrayStoreException e){
System.out.println("Wrong data type");
}
}
}

Q. WAP that demonstrate the concept of finally


class MultipleCatch{
public static void main(String args[]){
int a[] = {5,10};
int b = 5;
try{
int x = a[2]/(b-a[1]);
}
catch(ArithmeticException e){
System.out.println("Division by zero");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Array index error");
}catch(ArrayStoreException e){
System.out.println("Wrong data type");
}
finally{
int y = a[1]/a[0];
System.out.println("Y= " +y);}

48
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY
}
}

Q. Program that demonstrate the concept of user-defined exception


Soln:-
import java.lang.Exception;
class MyException extends Exception{
MyException(String message){
super(message);
}
}
class TestMyException{
public static void main(String args[]){
int x = 5, y = 1000;
try{float z = (float) x / (float) y;
if(z < 0.01){
throw new MyException("Number is too small");
}
}
catch(MyException e){
System.out.println("Caught my Exception");
System.out.println(e.getMessage());
}
finally{
System.out.println("I am always here");
}
}
}

Q. Write a program that throws Exception from method and handled by the calling function
class ThrowsFromMethod{
public static void main(String args[]){
try {
generate();
} catch (Exception e) {
System.out.println("DIVIDE BY ZERO!");
}
}
static void generate() throws Exception{
System.out.println(20/0);
}
}

Q. Create InsufficientBalance user-defined exception that handles users thrown exception.


Create another class Withdraw having id, name and balance as instance variable of customer,
One constructor to initialize instance variables and another method to display information. If the
balance of customer is less than 1000 then InsufficientBalance exception will be thrown and
handle it properly otherwise display the information of customer in the screen.
Soln:-
import java.lang.Exception;
class InsufficientBalanceException extends Exception{
InsufficientBalanceException(String message){
super(message);
49
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY
}
}

Now Another class,


class Widthdraw{
private int id;
private String name;
private double balance;

BankAccount(int id, String name, double balance){


this.id=id;
this.name=name;
this.balance=balance;
}
public void display(){
System.out.println("ID: "+id +" NAME: "+ name + " BALANCE: "+balance);
}

public static void main(String args[]){


BankAccount a = new BankAccount(1,"Sunil Bahadur Bist",900.25);
try{

if(a.balance < 1000){


throw new InsufficientBalanceException("Widthdrawl
Denied!, Your Minimum balance must be 1000");
}
a.display();
}
catch(InsufficientBalanceException e){
System.out.println(e.getMessage());
}
}
}

MULTITHREADING IN JAVA
Multithreading in java is a process of executing multiple threads simultaneously. Thread is
basically a lightweight sub-process, a smallest unit of processing. Multiprocessing and
multithreading, both are used to achieve multitasking.
But we use multithreading than multiprocessing because threads share a common memory area.
They don't allocate separate memory area so saves memory, and context-switching between the
threads takes less time than process. Java Multithreading is mostly used in games, animation etc.

Advantage of Java Multithreading


1) It doesn't block the user because threads are independent and you can perform multiple
operations at same time.
2) You can perform many operations together so it saves time.

50
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY
3) Threads are independent so it doesn't affect other threads if exception occurs in a single
thread.

Life cycle of a Thread (Thread States)


A thread can be in one of the five states. According to sun, there are only 4 states in thread life
cycle in java new, runnable, non-runnable and terminated. There is no running state.
But for better understanding the threads, we are explaining it in the 5 states.
The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:

1) New: The thread is in new state if you create an instance of Thread class but before the
invocation of start() method.
2) Runnable: The thread is in runnable state after invocation of start() method, but the thread
scheduler has not selected it to be the running thread.
3) Running: The thread is in running state if the thread scheduler has selected it.
4) Non-Runnable (Blocked): This is the state when the thread is still alive, but is currently not
eligible to run.
5) Terminated: A thread is in terminated or dead state when its run() method exits.

How to create thread: There are two ways to create a thread:


1. By extending Thread class
2. By implementing
Runnable
interface.

Thread class: Thread


class provides
constructors and methods
to create and perform
operations on a thread.
Thread class extends
Object class and
implements Runnable
interface.

51
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY
Commonly used Constructors of Thread class
Thread()
Thread(String name)
Thread(Runnable r)
Thread(Runnable r,String name)

Commonly used methods of Thread class


public void run(): is used to perform action for a thread.
public void start(): starts the execution of the thread.JVM calls the run() method on the
thread.
public void sleep(long miliseconds): Causes the currently executing thread to sleep
(temporarily cease execution) for the specified number of milliseconds.
public void join(): waits for a thread to die.
public void join(long miliseconds): waits for a thread to die for the specified miliseconds.
public int getPriority(): returns the priority of the thread.
public int setPriority(int priority): changes the priority of the thread.
public String getName(): returns the name of the thread.
public void setName(String name): changes the name of the thread.
public Thread currentThread(): returns the reference of currently executing thread.
public int getId(): returns the id of the thread.
public Thread.State getState(): returns the state of the thread.
public boolean isAlive(): tests if the thread is alive.
public void yield(): causes the currently executing thread object to temporarily pause and
allow other threads to execute.
public void suspend(): is used to suspend the thread(depricated).
public void resume(): is used to resume the suspended thread(depricated).
public void stop(): is used to stop the thread(depricated).
public boolean isDaemon(): tests if the thread is a daemon thread.
public void setDaemon(boolean b): marks the thread as daemon or user thread.
public void interrupt(): interrupts the thread.
public boolean isInterrupted(): tests if the thread has been interrupted.
public static boolean interrupted(): tests if the current thread has been interrupted.
Runnable interface:
52
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY

The Runnable interface should be implemented by any class whose instances are intended to be
executed by a thread. Runnable interface have only one method named run().
public void run(): is used to perform action for a thread.

Starting a thread: start() method of Thread class is used to start a newly created thread. It
performs following tasks:
 A new thread starts(with new callstack).
 The thread moves from New state to the Runnable state.
 When the thread gets a chance to execute, its target run() method will run.

Creating Thread by extending Thread class:


class Example extends Thread{
public void run(){
System.out.println("I am extended thread...");
}
public static void main(String args[]){
Example t1=new Example();
t1.start();
}
}
Who makes your class object as thread object?
Thread class constructor allocates a new thread object. When you create object of Multi class,
your class constructor is invoked(provided by Compiler) from where Thread class constructor is
invoked(by super() as first statement).So your Multi class object is thread object now.

Creating thread by implementing the Runnable interface:


class Example implements Runnable{
public void run(){
System.out.println("thread is running...");
}

public static void main(String args[]){


Example m1=new Example();
Thread t1 =new Thread(m1);
t1.start();
}

}
If you are not extending the Thread class,your class object would not be treated as a thread
object.So you need to explicitely create Thread class object.We are passing the object of your
class that implements Runnable so that your class run() method may execute.

53
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY

Other More examples,


Write a program to create Two threads one is to display sum of every odd number in 2 seconds
and other is to sum of every even number in 1.5 seconds using Runnable interface from 200 to
500.
Soln:-
class SumOfOdd implements Runnable{
@Override
public void run() {
int oSum=0;
for(int i= 200; i<=500;i++){
if(i%2==1){
oSum+=i;
System.out.println(" "+oSum);
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
}
}
}
}
public class SumOfEven implements Runnable {

@Override
public void run() {
int eSum=0;
for(int i= 200; i<=500;i++){
if(i%2==0){
eSum+=i;
System.out.println(" "+eSum);
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
}
}
}
}
class OddEvenSum {
public static void main(String[] args) {
SumOfEven e = new SumOfEven();
SumOfOdd o = new SumOfOdd();

Thread te = new Thread(e);


Thread to = new Thread(o);

te.start();

54
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY
to.start();
}
}

Make a thread using Runnable interface to display number from 1 to 20; each number should be
displayed in the interval of 2 seconds.
Soln:-
class DisplayNumber implements Runnable{

@Override
public void run() {
for(int i=1;i<=20;i++){
System.out.print(" "+i);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
System.out.println("Intrrrupted:
"+e.getMessage());
}
}
}
}
/*start the run method from main method*/
class DisplayNumberDemo {
public static void main(String[] args) {
DisplayNumber n = new DisplayNumber();
Thread t = new Thread(n);
t.start();
}
}

Make two threads, one displays odd number after one second and another thread display even
number after half second between -200 and -10.

Soln:- class Odd extends Thread {


@Override
public void run(){
for(int i=-10 ;i>=-200;i--){
if(i%2==-1)
System.out.print(" "+i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("Interrupted:
"+e.getMessage());
}
}
}
}
class Even extends Thread {

55
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY
@Override
public void run(){
for(int i=-10 ;i>=-200;i--){
if(i%2==-0)
System.out.print(" "+i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
System.out.println("Interrupted:
"+e.getMessage());
}
}
}
}
class Display {
public static void main(String[] args) {
new Even().start();
new Odd().start();
}
}

Create two threads by extending Thread class. The first class prints odd number in two seconds
from 21 to 51 and the second class prints even numbers in half seconds from 52 to 20. Create
another class to call start both the thread and display the result.
Soln:-
public class A extends Thread{
public void run(){
for(int i=21; i<52;i+=2){
if(i%2==1){
System.out.println(" " +i);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}

public class B extends Thread{


public void run(){
for(int i=52; i>=20;i-=2){
if(i%2==0){
System.out.print(" "+i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
56
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY
}
}

public class PosativeOddEven {


public static void main(String[] args) {
new A().start();
new B().start();
}
}

Create two threads by implementing Runnable interface. The first Thread prints odd number in
one second from -21 to -51 and the second Thread prints even numbers in half seconds from -52
to -20. Create another class to call start both the thread and display the result.

Soln:-
public class Y implements Runnable{
@Override
public void run(){
for(int i=-21; i>=-52;i-=2){
if(i%2==-1){
System.out.println(" " +i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}

public class Z implements Runnable{


@Override
public void run() {
for(int i=-52; i<=-20;i+=2){
if(i%2==-0){
System.out.print(" "+i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}

public class NegativeOddEven {


public static void main(String[] args) {
Z tz = new Z();

57
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY
Y ty = new Y();

Thread runnableZ = new Thread(tz);


Thread runnableY = new Thread(ty);

runnableZ.start();
runnableY.start();
}
}

Thread Synchronization

Threads communicate primarily by sharing access to fields and the objects reference fields refer
to. This form of communication is extremely efficient, but makes two kinds of errors
possible: thread interference and memory consistency errors. The tool needed to prevent these
errors is synchronization.
However, synchronization can introduce thread contention, which occurs when two or more
threads try to access the same resource simultaneously and cause the Java runtime to execute one
or more threads more slowly, or even suspend their execution. Starvation and livelock are forms
of thread contention. See the section Liveness for more information.
This section covers the following topics:
 Thread Interference describes how errors are introduced when multiple threads access
shared data.
 Memory Consistency Errors describes errors that result from inconsistent views of
shared memory.
 Synchronized Methods describes a simple idiom that can effectively prevent thread
interference and memory consistency errors.
 Implicit Locks and Synchronization describes a more general synchronization idiom,
and describes how synchronization is based on implicit locks.
 Atomic Access talks about the general idea of operations that can't be interfered with
by other threads.

Create a class Draw and declare a synchronized method shape which accepts a character as
parameter and print that character in triangle shape. Create two classes by extending Thread and
override the run method to call pattern synchronized method of Draw class. Finally create a
class DrawAShape having main method and create an instance of all to display result.

58
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY
Soln:-
public class Draw {
synchronized void shape(char ch){
for(int i=0 ;i<10; i+=2){
for(int j=10-i; j>0; j-=2){
System.out.print(" ");
}
for(int k=0; k<=i; k++){
System.out.print(ch);
}
System.out.println();
}
}
}

public class Thread1 extends Thread {


Draw d;
Thread1(Draw d){
this.d=d;
}
public void run(){
d.shape('c');

}
}

public class Thread2 extends Thread {


Draw d;
Thread2(Draw d){
this.d=d;
}
public void run(){
d.shape('h');

}
}

public class DrawAShape {


public static void main(String[] args) {
Draw d = new Draw();
new Thread1(d).start();
new Thread2(d).start();
}
}

Create a class Print and declare a synchronized method printPattern which accepts a character
as parameter and print that character in flag shape of Nepal. Create two Threads by
implementing Runnable interface and override the run method to call printPattern
synchronized method of Print class. Finally create a class PrintAPattern having main method
and create an instance of all to display result.

59
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY
Soln:-
public class Print {
synchronized void printPattern(char ch){
for(int i=0 ;i<10; i+=2){
for(int k=0; k<=i; k++){
System.out.print(ch);
}
System.out.println();
}
}
}

public class Print1 implements Runnable {


Print p;
Print1(Print p){
this.p=p;
}
@Override
public void run() {
p.printPattern('o');
}
}

public class Print2 implements Runnable {


Print p;
Print2(Print p){
this.p=p;
}
@Override
public void run() {
p.printPattern('o');
}
}

public class PrintAPattern {


public static void main(String[] args) {

Print p = new Print();


Print1 p1 = new Print1(p);
Print2 p2 = new Print2(p);

Thread t1 = new Thread(p1);


Thread t2 = new Thread(p2);

t1.start();
t2.start();
}
}

Practice Question: Create two threads by extending Thread class. One thread is used to display
series 1, 2, 3, 5, 8, 13 up to 20 terms in every two seconds and another thread is to display
another series in every half seconds 2, 5, 10, 18, 31, 52…up to 20terms.

60
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np

You might also like