Introduction To Java Programming
Introduction To Java Programming
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.
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 [email protected] 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 [email protected] 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.
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 [email protected] 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
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 [email protected] 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.
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 [email protected] 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.
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 [email protected] 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.
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 [email protected] 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 [email protected] 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 [email protected] 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");
}
}
10
Instructor: Sunil Bahadur Bist [email protected] 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 [email protected] 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 [email protected] 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);
}
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 [email protected] 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{
14
Instructor: Sunil Bahadur Bist [email protected] URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY
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.
15
Instructor: Sunil Bahadur Bist [email protected] 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 [email protected] 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
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.
18
Instructor: Sunil Bahadur Bist [email protected] 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
19
Instructor: Sunil Bahadur Bist [email protected] URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY
System.out.println("delete(): " + sb.delete(7, 7+ "[INSERT THIS] ".length()));
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
20
Instructor: Sunil Bahadur Bist [email protected] 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;
21
Instructor: Sunil Bahadur Bist [email protected] 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));
if(v.contains(new Integer(3)))
System.out.println("Vector contains 3.");
System.out.println("\nElements in vector:");
while(vEnum.hasMoreElements())
System.out.print(vEnum.nextElement() + " ");
System.out.println();
}
}
Another example,
import java.util.*;
vec.addElement("fruit1");
vec.addElement("fruit2");
vec.addElement("fruit3");
22
Instructor: Sunil Bahadur Bist [email protected] 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.
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 [email protected] 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);
}
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 [email protected] 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 [email protected] 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 [email protected] 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];
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;
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 [email protected] 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 [email protected] 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 [email protected] 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 [email protected] 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 [email protected] 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
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 [email protected] 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);
}
}
35
Instructor: Sunil Bahadur Bist [email protected] 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 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.
37
Instructor: Sunil Bahadur Bist [email protected] URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY
void eat(){
System.out.print("Bird eats Fish!");
}
}
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!");
}
}
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.
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 [email protected] 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;
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 [email protected] 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;
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 [email protected] 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){
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:
42
Instructor: Sunil Bahadur Bist [email protected] URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY
int cadence = 0;
int speed = 0;
int gear = 1;
class InterfaceDemo{
public static void main(String... args){
ACMEBicycle aBike = new ACMEBicycle();
aBike.changeGear(2);
aBike.printStates();
}
43
Instructor: Sunil Bahadur Bist [email protected] 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.
@Override
public void showMajorSubect(String sMajor) {
System.out.print(" Major Subject: "+sMajor);
}
}
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.
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 [email protected] 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{
…
}
47
Instructor: Sunil Bahadur Bist [email protected] 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");
}
}
48
Instructor: Sunil Bahadur Bist [email protected] URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY
}
}
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);
}
}
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.
50
Instructor: Sunil Bahadur Bist [email protected] 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.
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.
51
Instructor: Sunil Bahadur Bist [email protected] 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)
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.
}
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 [email protected] URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY
@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();
te.start();
54
Instructor: Sunil Bahadur Bist [email protected] 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.
55
Instructor: Sunil Bahadur Bist [email protected] 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();
}
}
}
}
}
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();
}
}
}
}
}
57
Instructor: Sunil Bahadur Bist [email protected] URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY
Y ty = new Y();
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 [email protected] 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();
}
}
}
}
}
}
}
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 [email protected] 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();
}
}
}
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 [email protected] URL: www.sunilbist.com.np