CE OOP Student Manual
CE OOP Student Manual
(FOR STUDENT)
To foster and permeate higher and quality education with value added engineering
and technology programs by providing all facilities in terms of technology and
platforms for all round development with social awareness for youths.
To become a pivotal center of service to Industry, academy and society with the
latest technology by providing facilities for advanced research and development
programs on par with international standards.
We at RAIT assure our main stakeholders 100% quality of students for the
programmes we deliver. This quality assurance stems from the teaching and
learning processes we have at work at our campus. The teachers are handpicked
from reputed institutions IIT/NIT/MU, etc. and they inspire the students to be
innovative in thinking and practical in approach. We have installed internal
procedures to better skill sets of instructors by sending them to training courses,
workshops, seminars and conferences. We also have a full-fledged course
curriculum and deliveries planned in advance for a structured semester long
programme. These tools help us to ensure same quality of teaching independent
of any individual instructor. Each classroom is equipped with internet and other
digital learning resources.
2
The effective learning process in the campus comprises a clean and stimulating
classroom environment and availability of lecture notes and digital resources
prepared by instructor from the comfort of home. In addition, a student is provided
with good number of assignments that would trigger his thinking process. The
testing process involves an objective test paper that would gauge the
understanding of concepts of the students. The Q&A process also ensures that the
learning process is effective. The summer internships and project work-based
training ensure learning process to include practical and industry relevant aspects.
Various technical events, seminars and conferences make the student learning
complete.
To impart higher and quality education in computer science with value added
engineering and technology programs to prepare technically sound, ethically
strong engineers with social awareness. To extend the facilities, to meet the fast
changing requirements and nurture the youths with international competencies
and exemplary level of employability and research under highly competitive
environments.
3
• To prepare the students to sustain the impact of computer education for
social needs encompassing industry, educational institutions and public
service.
• To collaborate with IITs, reputed universities and industries for the technical
and overall upliftment of students for continuing learning and
entrepreneurship.
4
Index
Sr. Page
Title of the Experiment
No. No.
1. Demonstration of Branching Statement 12
2. Demonstration of Looping Statement 17
3. Demonstration of Class, Objects, Methods 21
4. Method Overloading 25
5. Constructor Overloading 30
6. Demonstration of 2D- Array 35
7. Demonstration of StringBuffer methods 42
8. Demonstration of Multilevel Inheritance 46
9. Demonstration of Interface 53
10. Create User-Defined Exception 57
11. Demonstration of Multithreading 61
12. Creating GUI application 68
5
Course Objective, Course
Outcome & Experiment Plan
Course Objective:
Course Objective
1 To understand the object-oriented programming basics and its features.
2 Able to use a programming language to resolve problems.
To understand and apply Object Oriented Programming (OOP) principles
3
using Java.
To study various java programming concept like multithreading, exception
4
handling, packages etc.
5 To explain components of GUI based programming.
6 To understand the object-oriented programming basics and its features.
Course Outcomes:
CO CO Description
Understand basics of OOP and apply fundamental programming
CO1
constructs
CO2 Understand and illustrate the features of classes and objects
CO3 Elaborate the concept of strings, arrays and vectors
6
Exp. Week
Experiment Name CO Weightage
No. No.
The grading system describes how well
students have achieved the learning
objectives or goals established for a class
of course of study. This system helps to
1 W1 CO1 5
categorize the students according to their
grades. Design a system that reads marks
obtained by a student in a test of 100
marks and assign the grade.
Prime numbers are important because the
security of many encryption algorithms are
based on the fact that it is very fast to
multiply two large numbers and get the
2 W2 CO1 5
result, while it is extremely computer-
intensive to do the reverse. Enlist all the
prime numbers between 1 and 1000 to
create a base for cryptography.
The vendor provide a rubber material that
provides the protection to the edges of
rectangular object and paper material for
protection of front and back of rectangular
object. So a vendor needs an application
3 W3 CO2 4
to calculate the amount of rubber and
paper material required for covering
rectangular object. Write area method for
calculating area of rectangle and
square.(using class and object)
School students need to study and learn
formula for calculating area of different
4 W4 shapes like circle, rectangle, triangle and CO2 3
square. Design an application which will
read require parameters for the area
7
calculation of different shapes (use method
overloading)
An electrical engineer needs a complex
number calculator for performing the
operation of addition of alternating current
represented using complex number. Create
5 W5 CO2 3
an application that takes 2 objects complex
number as parameters and return the
object which is addition of 2 numbers
passed as parameter of complex number.
2D array is used in many real-life
applications where we need to organize
data in tabular/matrix format. Hence a
matrix manipulator is required with
6 W6 CO3 5
functionality of reading, displaying and
flipping data from the matrix. Generate the
methods, for the functionality mentioned
above for creation the matrix manipulator.
A character sequence is to be read as an
input and result need to declare as “yes” or
“no” by investigating the fact that
7 W7 traversing the characters sequence CO3 5
backwards and forwards results in same
sequence. Write a program for the same
using StringBuffer.
Write a program to calculate volume of
sphere using multilevel inheritance. The
base class method will accept the radius
from user. A class will be derived from the
8 W8 CO4 5
above mentioned class that will have a
method to find the area of a circle derived
from this will have method to calculate and
display the volume of the sphere.
8
Consider a university where students who
participate in the National Games or
Olympics are given some grace marks. The
grace marks provided are fixed and same
for every student. Create an application
9 W9 that keeps student’s academic marks and CO4 5
Sports grace marks separate and generate
total of marks considering academics and
sports both. Also invoke methods of base
class & interface using reference. (Hint:
Make use of Interface).
Through Custom exception user can raise
application-specific error code. You are
required to calculate a square of even
number provided as input by user.
10 W10 CO5 5
However if a user provides an odd number
as input, then an exception must be thrown
explicitly with message indicating the input
number must be even number.
Divide your program into two parts: One to
read a number and the other to calculate
11 W11 its square. Provide a simultaneous CO5 5
execution of both parts of a program to
maximum utilize the CPU time.
Create a GUI application which is fully
equipped with the functionality of solving
various computation problems such as
12 W12 Addition, subtraction, Multiplication and CO6 10
Division. The GUI application should runs
in a browser and displays the output as
result of these mathematical operations.
9
Study & Evaluation Scheme
Object
231CEU Oriented
CL32 Program -- 02 -- -- 01 -- 01
ming Lab
Object
231CEU Oriented
CL32 Program -- -- -- 25 25 -- 50
ming Lab
Term Work:
student with every experiment graded from time to time. The grades should
be converted into marks as per the Credit and Grading System manual and
10
Practical & Oral:
Practical & Oral exam will be based on the entire syllabus of Object Oriented
Programming
11
OOP Lab
EXPERIMENT NO.
1
Demonstration of Branching Statement
12
Experiment No.
1. Aim:
The grading system describes how well students have achieved the learning objectives or
goals established for a class of course of study. This system helps to categorize the students
according to their grades. Design a system that reads marks obtained by a student in a
test of 100 marks and assign the grade.
Marks Grade
0 to 39 Fail
40 to 49 Pass
50 to 59 Second Class
60 to 69 First Class
70 to 100 Distinction
2. Objectives:
To understand the concept of Object Oriented Programming.
To understand the switch case statement
3. Outcomes:
4. Software Required:
13
5. Theory:
The control statement that allows us to make a decision from the number of choices is
called a switch .A switch statement allows you to test the value of an expression and,
depending on that value, to jump directly to some location within the switch statement.
Only expressions of certain types can be used. The value of the expression can be one of
the primitive integer type’s int, short, or byte. It can be the primitive char type.
The positions that you can jump to are marked with case labels that take the form: "case
constant:" This marks the position the computer jumps to when the expression evaluates
to the given constant. As the final case in a switch statement you can, optionally, use the
label "default:" which provides a default jump point that is used when the value of the
expression is not listed in any case label.
switch (expression )
break ;
break;
break;
default : statement ;
Sample Program:
class sample
int i = 1 ;
14
switch ( i )
6. Algorithm:
Step 4: Stop
7. Conclusion:
After performing this experiment we are able to use branching structures, control structure
and switch case which helps in making decision by using switch cases.
15
8. Quiz / Viva Questions:
Explain switch case statement?
What is use of default label in switch case?
9. References:
1. Jaime Nino, Frederick A. Hosch, ‘An introduction to Programming and Object
Oriented Design using Java’, Wiley Student Edition.
2. E Balgurusamy, “Programming with JAVA”, Tata McGraw Hill
16
OOP Lab
EXPERIMENT NO.
2
Demonstration of Looping Statement
17
Experiment No.
1. Aim:
Prime numbers are important because the security of many encryption algorithms are
based on the fact that it is very fast to multiply two large numbers and get the result,
while it is extremely computer-intensive to do the reverse. Enlist all the prime numbers
between 1 and 1000 to create a base for cryptography.
2. Objectives:
Understand the basics of Control Statements
Use the Selection (if-else) statements and Repetition (for loop) statement.
3. Outcomes:
4. Software Required:
5. Theory:
Control Statements: The control statement are used to control the flow of execution of the
program. This execution order depends on the supplied data values and the conditional
logic. Java contains the following types of control statements:
1- Selection Statements
2- Repetition Statements
3- Branching Statements
18
Selection statements:
Syntax:
if(conditional expression){
<Statements>;
...;
...;
}
2. If-else Statement: The "if-else" statement is an extension of if statement that provides
another option when 'if' statement evaluates to "false" i.e. else block is executed if "if"
statement is false.
Syntax:
if(conditional expression){
<Statements>;
...;
...;
}
else{
<Statements>;
....;
....;
}
6. Algorithm:
Step 2: If i<=num
19
Step 2.2.1.2: break
Step 3: STOP
7. Conclusion:
After performing this experiment we are able to create a class and control statements.
9. References:
1. Ralph Bravaco , Shai Simoson , “Java Programing From the Group Up” ,Tata
McGraw-Hill
2. Java 2, “The Complete Reference of Java”, Schildt publication
20
OOP Lab
EXPERIMENT NO.
3
Demonstration of Class, Objects, Methods
21
Experiment No.
1. Aim:
The vendor provide a rubber material that provides the protection to the edges of
rectangular object and paper material for protection of front and back of rectangular
object. So a vendor needs an application to calculate the amount of rubber and paper
material required for covering rectangular object. Write area method for calculating area
of rectangle and square (using class and object).
2. Objectives:
To understand the object-oriented programming basics and its features.
Able to use a programming language to resolve problems.
To understand and apply Object Oriented Programming (OOP) principles using
Java.
3. Outcomes:
4. Software Required:
5. Theory:
Objects are the basic runtime entities in an object oriented system. A class may be thought
of as a ‘data type’ and an object as ‘variable’ of that data type. The data and code of the
class are accessed by object of that class. In this program, the object of class circle is used
to access the methods: getdata() & area() of this class.
22
Syntax:
class Class_Name
// Statements;
For example:
class Room
float length;
float breadth;
length=a;
breadth=b;
float area;
R1.getdata(20,10);
area=r1.length*r1.breadth;
System.out.println(“Area= ”+area);
23
}
Output: Area=200.0
6. Algorithm:
1. Start
2. Declare a class named Rectangle
3. Declare data members length and breadth
4. Define a method getDim() to take input for data members
5. Define a method area() to calculate area of Rectangle
6. Declare a method perimeter() to calculate the perimeter of Rectangle
7. Create object of Rectangle class and invoke methods of Rectangle class inside
main() method
8. Stop
7. Conclusion:
After performing this experiment we are able to create a class and object. The classes are
interacting with each other by accessing the methods and members of class using different
objects.
9. References:
1. Ralph Bravaco , Shai Simoson , “Java Programing From the Group Up” ,Tata
McGraw-Hill
2. Grady Booch, Object Oriented Analysis and Design
3. Jaime Nino, Frederick A. Hosch, ‘An introduction to Programming and Object
Oriented Design using Java’, Wiley Student Edition. Wayne Tomasi, “Electronics
Communication Systems”, Pearson education, Fifth edition.
4. Java 2, “The Complete Reference of Java”, Schildt publication
24
OOP Lab
EXPERIMENT NO.
4
Method Overloading
25
Experiment No.
1. Aim:
School students need to study and learn formula for calculating area of different shapes
like circle, rectangle, triangle and square. Design an application which will read require
parameters for the area calculation of different shapes (use method overloading).
2. Objectives:
To understand the object-oriented programming basics and its features.
Able to use a programming language to resolve problems.
To understand and apply Object Oriented Programming (OOP) principles using
Java.
3. Outcomes:
4. Software Required:
5. Theory:
Java allows to create methods that have the same name, but different parameter lists and
different definitions. This is called method overloading.
Method Overloading:
Two or more methods within the same class that have the same name but methods
must differ in the type and/or number of their parameters.
Method overloading is one of the ways that Java implements polymorphism.
26
When an overloaded method is invoked, Java uses the type and/or number of
arguments to determine which version of the overloaded method to actually call.
Syntax:
class ClassName
{
void Function1(data_type a, data_type b)
{
// Statements
}
void Function1(data_type a, data_type b, data_type c)
{
// Statements
}
public static void main(String args[])
{
ClassName obj=new ClassName();
obj.Function1(Value1,Value2);
obj.Function1(Value1,Value2,Value3);
}
}
For example:
class Calculation
{
void sum(int a,int b)
{
System.out.println("Addition of two numbers is:"+(a+b));
}
void sum(int a, int b, int c)
{
System.out.println("Addition of three numbers is:"+(a+b+c));
}
27
Calculation c=new Calculation();
c.sum(10,40,60);
c.sum(20,20);
}
}
Output:
Addition of two numbers is: 110
Addition of three numbers is: 40
6. Algorithm:
1. Start
2. Declare a class named Shapes
3. Overload a method area(int) to calculate area of Square
4. Overload a method area(int, int) to calculate area of Rectangle
5. Overload a method area(int, int, int) to calculate area of Triangle
6. Create object of Shapes class and invoke methods with different parameters inside
main() method to achieve method overloading.
7. Stop
7. Conclusion:
After performing this experiment we are able to create a class and object. The classes are
interacting with each other by accessing the methods and members of class using different
objects.
9. References:
1. Ralph Bravaco , Shai Simoson , “Java Programing From the Group Up” ,Tata
McGraw-Hill
2. Grady Booch, Object Oriented Analysis and Design
28
3. Jaime Nino, Frederick A. Hosch, ‘An introduction to Programming and Object
Oriented Design using Java’, Wiley Student Edition. Wayne Tomasi, “Electronics
Communication Systems”, Pearson education, Fifth edition.
4. Java 2, “The Complete Reference of Java”, Schildt publication
29
OOP Lab
EXPERIMENT NO.
5
Constructor Overloading
30
Experiment No.
1. Aim:
An electrical engineer needs a complex number calculator for performing the operation of
addition of alternating current represented using complex number. Create an application
that takes 2 objects complex number as parameters and return the object which is addition
of 2 numbers passed as parameter of complex number.
2. Objectives:
Solve the real world scenarios using top down approach.
Understand the concept and properties of constructor
3. Outcomes:
4. Software Required:
5. Theory:
A constructor is a special public member method whose task is to initialize the object data
members when an object is declared. The constructor of a class should have the same
name as the class. For example if the name of class is Employee then the constructor is a
method with the name Employee( ).
Characteristics of a constructor:
31
3. They do not have return types not even void and therefore they cannot return
values.
Types of Constructor:
Constructor Overloading:
Constructor overloading means we can create and use more than one constructor in a
class. A constructor can be overloaded on the basis of following facts:
1. Number of parameters
3. Order of parameters
When we create object of the classes, the instance variables are initialized according to
the constructor signature.
For example:
class Product
int x, y;
32
6. Algorithm:
Step 1: Start
Step 4: Stop
7. Conclusion:
This experiment implements constructors and give us the clear scenario of characteristics
and types of constructor along with parameters passing to constructor. We can formulate
and solve real world problems.
9. References:
1. Ralph Bravaco , Shai Simoson , “Java Programing From the Group Up” ,Tata
McGraw-Hill
2. Grady Booch, Object Oriented Analysis and Design
33
3. Jaime Nino, Frederick A. Hosch, ‘An introduction to Programming and Object
Oriented Design using Java’, Wiley Student Edition. Wayne Tomasi, “Electronics
Communication Systems”, Pearson education, Fifth edition.
4. Java 2, “The Complete Reference of Java”, Schildt publication
34
OOP Lab
EXPERIMENT NO.
6
Demonstration of 2D- Array
35
Experiment No.
1. Aim:
2. Objectives:
To understand the concept of Object Oriented Programming.
To understand how to use of Array in java
3. Outcomes:
4. Software Required:
5. Theory:
Java provides a data structure, the array, which stores a fixed-size sequential collection of
elements of the same type. An array is used to store a collection of data, but it is often
more useful to think of an array as a collection of variables of the same type. Instead of
declaring individual variables, such as number0, number1, ..., and number99, you declare
one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99]
to represent individual variables. This tutorial introduces how to declare array variables,
create arrays, and process arrays using indexed variables.
36
Declaring Array Variables:
To use an array in a program, you must declare a variable to reference the array,
and you must specify the type of array the variable can reference. Here is the syntax
for declaring an array variable:
OR
Note: The style dataType[] arrayRefVar is preferred. The style dataType arrayRefVar[]
comes from the C/C++ language and was adopted in Java to accommodate C/C++
programmers.
Example: The following code snippets are examples of this syntax:
OR
Creating Arrays:
You can create an array by using the new operator with the following syntax:
The array elements are accessed through the index. Array indices are 0-based; that
is, they start from 0 to arrayRefVar.length-1.
Example: Following statement declares an array variable, myList, creates an array of
10 elements of double type, and assigns its reference to myList:
37
double[] myList = new double[10];
Following picture represents array myList. Here myList holds ten double values and
the indices are from 0 to 9.
6. Algorithm:
1. Create a class Matrix and declare two 2D array for addition and transpose of matrix
and variables r, c, i, j are used.
class Matrix
int a[][],b[][],sum[][],t[][];
int r,c,i,j;
2. Create a method read() and enter the elements for two matrices
void read()
r=sc.nextInt();
c=sc.nextInt();
a =new int[r][c];
38
b =new int[r][c];
for(i=0;i<r;i++)
for(j=0;j<c;j++)
//System.out.print("Enter data:");
a[i][j]=sc.nextInt();
for(i=0;i<r;i++)
for(j=0;j<c;j++)
//System.out.print("Enter data:");
b[i][j]=sc.nextInt();
} //end of read
void addition()
sum=new int[r][c];
for(i=0;i<r;i++)
for(j=0;j<c;j++)
39
sum[i][j]=a[i][j]+b[i][j];
} //end of addition
void display()
for(i=0;i<r;i++)
for(j=0;j<c;j++)
System.out.print(sum[i][j]+" ");
System.out.println();
} //end of display
5. Create a method transpose() to transpose the matrix after the addition of two
matrices.
void transpose()
t=new int[r][c];
for(i=0;i<c;i++)
for(j=0;j<r;j++)
t[i][j]=sum[j][i];
for(i=0;i<r;i++)
for(j=0;j<c;j++)
System.out.print(t[i][j]+" ");
System.out.println();
40
} //end of transpose
6. Stop
7. Conclusion:
This experiment implements transpose matrix, we also learnt how to create an array data
structure which include 2Dimentional array.
9. References:
1. Jaime Nino, Frederick A. Hosch, ‘An introduction to Programming and Object
Oriented Design using Java’, Wiley Student Edition.
2. E Balgurusamy, “Programming with JAVA”, Tata McGraw Hill
41
OOP Lab
EXPERIMENT NO.
7
Demonstration of StringBuffer methods
42
Experiment No.
1. Aim:
A character sequence is to be read as an input and result need to declare as “yes” or “no”
by investigating the fact that traversing the characters sequence backwards and forwards
results in same sequence. Write a program for the same using StringBuffer.
2. Objectives:
Understand basic concepts in Object Oriented Programming
Study different operations on strings and string Buffer class
3. Outcomes:
4. Software Required:
5. Theory:
String manipulation is the most common part of many Java programs. Strings are very
important in programming languages as they are used to process long textual/symbolic
information. The information you provide is in form of ordered sequence of characters and
symbols is called as string.
In C, C++ character arrays are used to process long textual information. Using character
arrays is time consuming so in java, strings are not considered as the fundamental data
type. In Java String class is provided to work with strings along with facility of character
array.
43
In Java, Strings are immutable as once an object of the String class is created and initialized
with some value then it cannot be changed. The Java development environment provides
two classes that store and manipulate character data: String, for constant strings, and
StringBuffer, for mutable strings.
Another way of making a string in java is making an object of StringBuffer class. One major
speciality of the object of this class is that it is mutable. The size of this object can be
changed again and again during runtime i.e. we can insert, append, and delete etc. a
character from the string. An object of StringBuffer has some advantages of extra methods
provided in the class. Let us see methods supported in this class.
insert(int,char): This method is used to insert the character passed at indexed passed.
replace(int startIndex, int endIndex, String str): This method is used to replace the
string from specified startIndex and endIndex.
delete(int startIndex, int endIndex): This method is used to delete the string from
specified startIndex and endIndex.
capacity(): This method is used to return the current capacity of the StringBuffer object.
char charAt(int index): This method is used to return the character at the specified
position.
setcharAt(int,index): The character passed is set at the index specified in the brackets.
length(): This method is used to return the length of the string i.e. total number of
characters.
public String substring(int beginIndex, int endIndex): is used to return the substring
from the specified beginIndex and endIndex.
44
Defining string with StringBuffer class:
6. Algorithm:
Step 1: Start.
Step 2: Define class Palindrome.
Step 3: Declare 2 String variables str and rev.
Step 4: Take input from user for String str
Step 5: Declare StringBuffer variable str1 using String str as a parameter
Step 6: Reverse StringBuffer str1
Step 7: Convert StringBuffer str1 to String and store it in String rev
Step 8: if String str equals to String rev
Step 8.1: Display String str is a palindrome
Step 8.2: else display String str is not a palindrome
Step 9: Stop
7. Conclusion:
With this experiment we have learned difference between String and StringBuffer, different
methods of String class and StringBuffer class. We have checked whether the given string
is palindrome or not and also we are able to solve real time problems.
9. References:
1. Jaime Nino, Frederick A. Hosch, ‘An introduction to Programming and Object
Oriented Design using Java’, Wiley Student Edition.
2. E Balgurusamy, “Programming with JAVA”, Tata McGraw Hill
45
OOP Lab
EXPERIMENT NO.
8
Demonstration of Multilevel Inheritance
46
Experiment No.
1. Aim:
Write a program to calculate volume of sphere using multilevel inheritance. The base class
method will accept the radius from user. A class will be derived from the above mentioned
class that will have a method to find the area of a circle derived from this will have method
to calculate and display the volume of the sphere.
2. Objectives:
To understand the concept of inheritance.
To understand how to use method overriding.
3. Outcomes:
4. Software Required:
5. Theory:
Types of Inheritance:
1. Single Inheritance: A derived class with only one base class is called as Single Inheritance.
47
2. Multiple Inheritances: A derived class with several base classes is called Multiple
Inheritance.
3. Hierarchical Inheritance: More than one class may inherit the features of one class this
process is called as Hierarchical Inheritance.
4. Multilevel Inheritance: The mechanism of deriving a class from another derived class is
called Multilevel Inheritance.
5. Hybrid Inheritance: There could be situations where we need to apply one or more types
of inheritances to design a program this process is called Hybrid Inheritance.
48
Syntax:
class A
class B extends A
class C extends B
Instance Methods
An instance method in a subclass with the same signature (name, plus the number and
the type of its parameters) and return type as an instance method in the superclass
overrides the superclass's method. The ability of a subclass to override a method allows a
class to inherit from a superclass whose behavior is "close enough" and then to modify
behavior as needed. The overriding method has the same name, number and type of
parameters, and return type as the method it overrides. An overriding method can also
return a subtype of the type returned by the overridden method. This is called a covariant
return type.
When overriding a method, you might want to use the @Override annotation that instructs
the compiler that you intend to override a method in the superclass. If, for some reason,
the compiler detects that the method does not exist in one of the superclasses, it will
generate an error.
Class Methods
If a subclass defines a class method with the same signature as a class method in the
superclass, the method in the subclass hides the one in the superclass.
The distinction between hiding and overriding has important implications. The version of
the overridden method that gets invoked is the one in the subclass. The version of the
49
hidden method that gets invoked depends on whether it is invoked from the superclass
or the subclass. Let's look at an example that contains two classes. The first is Animal,
which contains one instance method and one class method:
Animal.testClassMethod();
myAnimal.testInstanceMethod();
50
The Cat class overrides the instance method in Animal and hides the class method in
Animal. The main method in this class creates an instance of Cat and calls
testClassMethod() on the class and testInstanceMethod() on the instance.
6. Algorithm:
Step 1: Start
Step 2: Create base class Circle with method to accept radius from user.
Step 3: Derive class Area from the base class with methods calculate() to calculate area
and display() to display area.
Step 4: Derive another class Volume from Area which will calculate volume of sphere
and have method display () to display the volume.
Step 5: Stop
Here, the method display () of the derived class ‘Volume’ overrides the method display ()
of the class ‘Area’
7. Conclusion:
From this experiment we have learnt how to inherit the property of base class. Also learnt
how to perform hiding and overriding concept.
51
9. References:
1. Jaime Nino, Frederick A. Hosch, ‘An introduction to Programming and Object
Oriented Design using Java’, Wiley Student Edition.
2. E Balgurusamy, “Programming with JAVA”, Tata McGraw Hill
52
OOP Lab
EXPERIMENT NO.
9
Demonstration of Interface
53
Experiment No.
1. Aim:
Consider a university where students who participate in the National Games or Olympics
are given some grace marks. The grace marks provided are fixed and same for every
student. Create an application that keeps student’s academic marks and Sports grace marks
separate and generate total of marks considering academics and sports both. Also invoke
methods of base class & interface using reference. (Hint: Make use of Interface).
2. Objectives:
Study feature of OOP like inheritance.
Study implementation of multiple inheritance in Java
3. Outcomes:
4. Software Required:
5. Theory:
The mechanism of inheriting the features of more than one base class into a single class
is known as multiple inheritances. Java does not support multiple inheritance but the
multiple inheritance can be achieved by using the interface.
54
responsibility of the class that implements an interface to define the code for
implementation of these methods.
Syntax:
interface InterfaceName
return_type method_name1(parameter-list);
6. Algorithm:
Step 1: Start
Step 5: Define class Result which extends test & implements sports
55
5.2.3 Print total
Step 7: Define Main method, Create object of class Result and Invoke getnumber(),
getmarks(), display().
Step 8: Stop
7. Conclusion:
With this experiment we have understood that Interfaces are mainly used to provide
polymorphic behavior and its function to break up the complex designs and clear the
dependencies between objects.
9. References:
1. Ralph Bravaco , Shai Simoson , “Java Programing From the Group Up” ,Tata
McGraw-Hill
2. Grady Booch, Object Oriented Analysis and Design
3. Jaime Nino, Frederick A. Hosch, ‘An introduction to Programming and Object
Oriented Design using Java’, Wiley Student Edition. Wayne Tomasi, “Electronics
Communication Systems”, Pearson education, Fifth edition.
4. Java 2, “The Complete Reference of Java”, Schildt publication
56
OOP Lab
EXPERIMENT NO.
10
Create User-Defined Exception
57
Experiment No.
1. Aim:
Through Custom exception user can raise application-specific error code. You are required
to calculate a square of even number provided as input by user. However if a user provides
an odd number as input, then an exception must be thrown explicitly with message
indicating the input number must be even number.
2. Objectives:
Study feature of OOP like exception handing.
Study how to create own exception in Java
3. Outcomes:
4. Software Required:
5. Theory:
Exceptions are usually used to denote something unusual that does not conform to the
standard rules. In programming, exceptions are events that arise due to the occurrence of
unexpected behaviour in certain statements, disrupting the normal execution of a program.
Exception is a run time error. Exceptions can arise due to a number of situations. For
example,
Trying to access the 11th element of an array when the array contains of only 10
element (ArrayIndexOutOfBoundsException)
Division by zero (ArithmeticException)
58
Accessing a file which is not present (FileNotFoundException)
Failure of I/O operations (IOException)
Illegal usage of null. (NullPointerException)
Top class in exception hierarchy is Throwable. This class has two siblings: Error and
Exception. All the classes representing exceptional conditions are subclasses of the
Exception class.
try/catch: All the statements to be tried for exceptions are put in a try block. The
catch block is used to catch any exception raised from the try block. If exception
occurs in any statement in the try block control immediately passes to the
corresponding catch block.
finally: The finally block will execute whether or not an exception is thrown.
throw: It is used to explicitly throw an exception. It is useful when we want to throw
a user-defined exception.
throws: If a method is capable of causing an exception that it does not handle, it
must specify this behavior using throws keyword so that callers of the method can
guard themselves against that exception
6. Algorithm:
1. Start
2. Create class OddException which extends Exception class
3. Declare num as int type
4. Write OddException(int x) constructor to get numbers as input.
5. Write toString() method to display a message when exception is thrown.
6. Create a class MyExceptionDemo with main function and Write static function
OddNoException() throws OddException when number is odd.
7. Define main method
8. In try block
9. Invoke OddException(3)
10. In catch block
11. Print catch exception
12. Stop
59
7. Conclusion:
9. References:
1. Java 2, “The Complete Reference of Java”, Schildt publication.
2. Ivor Horton, ‘Beginning JAVA’, Wiley India.
3. DietalandDietal, ‘Java: How to Program’, 8/e,PHI
4. ‘JAVA Programming’, Black Book, Dreamtech Press.
60
OOP Lab
EXPERIMENT NO.
11
Demonstration of Multithreading
61
Experiment No.
1. Aim:
Divide your program into two parts: One to read a number and the other to calculate its
square. Provide a simultaneous execution of both parts of a program to maximum utilize
the CPU time.
2. Objectives:
Study basic constructs of java
Understand importance of multithreading
3. Outcomes:
4. Software Required:
5. Theory:
Processes and Threads: In concurrent programming, there are two basic units of execution:
processes and threads. In the Java programming language, concurrent programming is
mostly concerned with threads.
Threads: Threads are sometimes called lightweight processes. Both processes and threads
provide an execution environment, but creating a new thread requires fewer resources
than creating a new process. Threads exist within a process — every process has at least
62
one thread. Threads share the process's resources, including memory and open files.
Multithreaded execution is an essential feature of the Java platform. Every application has
at least one thread — or several, if you count "system" threads that do things like memory
management and signal handling. But from the application programmer's point of view,
you start with just one thread, called the main thread.
New state: After the creations of Thread instance the thread is in this state but before the
start() method invocation. At this point, the thread is considered not alive.
Runnable (Ready-to-run) state: A thread start its life from Runnable state. A thread first
enters runnable state after the invoking of start() method but a thread can return to this
state after either running, waiting, sleeping or coming back from blocked state also. On
this state a thread is waiting for a turn on the processor.
Running state: A thread is in running state that means the thread is currently executing.
There are several ways to enter in Runnable state but there is only one way to enter in
running state: the scheduler select a thread from runnable pool.
Dead state: A thread can be considered dead when its run() method completes. If any
thread comes on this state that means it cannot ever run again.
Blocked: A thread can enter in this state because of waiting the resources that are hold
by another thread.
As we have seen different states that may be occur with the single thread. A running
thread can enter to any non-runnable state, depending on the circumstances. A thread
cannot enter directly to the running state from non-runnable state, firstly it goes to
63
runnable state. Now let’s understand the some non-runnable states which may be occur
handling the multithreads.
Sleeping: On this state, the thread is still alive but it is not runnable, it might be return to
runnable state later, if a particular event occurs. On this state a thread sleeps for a specified
amount of time. You can use the method sleep( ) to stop the running state of a thread.
Waiting for Notification: A thread waits for notification from another thread. The thread
sends back to runnable state after sending notification from another thread.
64
Threads can be created in Java in the following ways:
This is a simplest form of creating threads in a program. Consider the following code
snippet.
-----
-----
In this code snippet, the ThreadExample class is created by extending the Thread class.
The run( ) method of the Thread class is overridden by the ThreadExample class to provide
the code to be executed by a thread. In Java we cannot extend a class from more than
one class. Therefore while creating a thread by extending the Thread class we cannot
simultaneously extend any other class.
Threads can also be created by implementing the Runnable interface of the java.lang
package. This package allows to define a class that can implement the Runnable interface
and extend any other class. Consider the following code snippet.
65
System.out.println(“This is an example on runnable interface”);
6. Algorithm:
1. Start
print i
for(int i=1;i<=10;i++)
print i*i
66
6. Invoke t1.start( ) then t2.start( )
7. Stop
7. Conclusion:
9. References:
1. Ralph Bravaco , Shai Simoson , “Java Programing From the Group Up” ,Tata
McGraw-Hill
2. Grady Booch, Object Oriented Analysis and Design
3. Jaime Nino, Frederick A. Hosch, ‘An introduction to Programming and Object
Oriented Design using Java’, Wiley Student Edition. Wayne Tomasi, “Electronics
Communication Systems”, Pearson education, Fifth edition.
4. Java 2, “The Complete Reference of Java”, Schildt publication.
67
OOP Lab
EXPERIMENT NO.
12
Creating GUI application
68
Experiment No.
1. Aim:
Create a GUI application which is fully equipped with the functionality of solving various
computation problems such as Addition, subtraction, Multiplication and Division. The GUI
application should runs in a browser and displays the output as result of these
mathematical operations.
2. Objectives:
To explain components of GUI based programming
3. Outcomes:
4. Software Required:
5. Theory:
Swing is a part of Java Foundation classes (JFC), the other parts of JFC are java2D and
Abstract window toolkit (AWT). AWT, Swing & Java 2D are used for building graphical user
interfaces (GUIs) in java. In this tutorial we will mainly discuss about Swing API which is
used for building GUIs on the top of AWT and are much more light-weight compared to
AWT.
69
The controller component of the MVC architecture reads input from the user on
the view and then these changes are passed to the component data.
In each Swing component, the view and controller are clubbed together while the
model is a separate one. This gives swing a pluggable look and feel feature.
JFrame: A frame is an instance of JFrame. Frame is a window that can have title, border,
menu, buttons, text fields and several other components. A Swing application must have
a frame to have the components added to it.
JPanel: A panel is an instance of JPanel. A frame can have more than one panels and each
panel can have several components. You can also call them parts of Frame. Panels are
useful for grouping components and placing them to appropriate locations in a frame.
JLabel: A label is an instance of JLabel class. A label is unselectable text and images. If you
want to display a string or an image on a frame, you can do so by using labels. In the
above example we wanted to display texts “User” & “Password” just before the text fields,
we did this by creating and adding labels to the appropriate positions.
JTextField: Used for capturing user inputs, these are the text boxes where user enters the
data.
JPasswordField: Similar to text fields but the entered data gets hidden and displayed as
dots on GUI.
JButton: A button is an instance of JButton class. In the above example we have a button
“Login”.
70
The hierarchy of java swing API is given below:
The methods of Component class are widely used in java swing that are given below,
Method Description
public void add(Component c) add a component on another component.
public void setSize(int width,int height) sets size of the component.
public void setLayout(LayoutManager m) sets the layout manager for the
component.
public void setVisible(boolean b) sets the visibility of the component. It is by
default false.
71
6. Algorithm:
1. Start
4. Create the container and add controls for digits, scientific calculations and decimal
Manipulations.
6. When the user presses the control, the event is generated and handled.
8. Stop
7. Conclusion:
9. References:
1. Java 2, “The Complete Reference of Java”, Schildt publication.
2. Ivor Horton, ‘Beginning JAVA’, Wiley India.
3. DietalandDietal, ‘Java: How to Program’, 8/e,PHI
4. ‘JAVA Programming’, Black Book, Dreamtech Press.
72
73