OOPS with JAVA Manual
OOPS with JAVA Manual
STUDENT MANUAL
Course: OBJECT ORIENTED PROGRAMMING WITH JAVA
Course Code: BCS306A
IV-SEMESTER
Prepared by:
Mrs. Sharon D Souza
Assistant Professor
Department of Computer Science & Engineering, AJIET, Mangalore
TABLE OF CONTENTS
Item Page No.
Rubrics xiii-xiv
PEO1: To develop in students, the ability to solve real life problems by applying fundamental science
and elementary strengths of computer science courses.
PEO2: To mould students, to have a successful career in the IT industry where graduates will be able
to design and implement the needs of society and nation.
PEO3: To transform students, to excel in a competitive world through higher education and indulge in
research through continuous learning process.
Object Oriented Programming with JAVA BCS306A
Do's
1. Maintain discipline in the Laboratory.
2. Before entering the Laboratory, keep the footwear on the shoe rack.
3. Proper dress code has to be maintained while entering the Laboratory.
4. Students should carry a lab observation book, student manual and record book completed in
all aspects.
5. Read and understand the logic of the program thoroughly before coming to the laboratory.
6. Enter the login book before switching on the computer.
7. Enter your batch member names and other details in the slips for hardware kits.
8. Students should be at their concerned places; unnecessary movement is restricted.
9. Students should maintain the same computer until the end of the semester.
10. Report any problems in computers/hardware kits to the faculty member in-charge/laboratory
technician immediately.
11. The practical result should be noted down into their observation and the result must be shown
to the faculty member in-charge for verification.
12. After completing the experiments, students should switch off the computers, enter logout
time, return the hardware kits and keep the chairs properly.
Don'ts
1. Do not come late to the Laboratory.
2. Do not enter the laboratory without an ID card, lab dress code, observation book and record.
3. Do not leave the laboratory without the permission of the faculty in-charge.
4. Never eat, drink while working in the laboratory.
5. Do not handle any equipment before reading the instructions/instruction manuals.
6. Do not exchange the computers with others and hardware kits also.
7. Do not misbehave in the laboratory.
8. Do not alter computer settings/software settings.
9. External Disk/drives should not be connected to computers without permission, doing so will
attract fines.
10. Do not remove anything from the kits/experimental set up without permission. Doing so will
attract fines.
11. Do not mishandle the equipment / Computers.
12. Do not leave the laboratory without verification of hardware kits by the lab instructor.
13. Usage of Mobile phones, tablets and other portable devices are not allowed in restricted
places.
INSTRUCTIONS TO STUDENTS
Students must bring Observation book, record and manual along with pen, pencil, anderaser etc.,
no borrowing from others.
Students must handle the trainer kit and other components carefully, as they areexpensive.
Before switch on the trainer kit, must show the connections to one of the faculties orinstructors.
After the completion of the experiment should return the components to the respective lab
instructors.
Before leaving the lab, should check whether they have switch off the power suppliesand keep
their chairs properly.
Be regular to the Lab Do not come late to the Lab
Do not throw connecting wires on the Floor
Wear your College ID card Do not operate the IC trainer kits without permission
Avoid unnecessary talking while doing the experiment
Avoid loose connection and short circuits
Take the signature of the lab in charge before taking the components
Do not interchange the ICs while doing the experiment
Handle the trainer kit properly
Do not panic if you do not get the output
Keep your work area clean after completing the experiment.
After completion of the experiment switch off the power and return the components
Arrange your chairs and tables before leaving.
Put your name, USN and subject on the outside front cover of the record. Put
thatsame information on the first page inside.
Update Table of Contents every time you start each new experiment or topic
Always use pen and write neatly and clearly
Start each new topic (experiment, notes, calculation, etc.) on a right-side (odd
numbered) page
Obvious care should be taken to make it readable, even if you have bad handwriting
Date to be written every page on the top right side corner
On each right-side page
Title of experiment
Aim/Objectives
Components Required
Program
On each left side page
Stick Output snapshot printouts
Use labels and captions for figures and tables
Strictly observe the instructions given by the Teacher/ Lab Instructor.
Course Objectives
CLO 1. To learn primitive constructs JAVA programming languages.
CLO 2. To understand Object Oriented Programming Features of JAVA.
CLO 3. To gain knowledge on: packages, multithreaded programing and exceptions.
Course Outcomes
CO 1. Demonstrate proficiency in writing simple programs involving branching and looping structures.
CO 2. Design a class involving data members and methods for the given scenario.
CO 3. Apply the concepts of inheritance and interfaces in solving real world problems.
CO 4. Use the concept of packages and exception handling in solving complex problem
CO 5. Apply concepts of multithreading, autoboxing and enumerations in program development
The weightage of Continuous Internal Evaluation (CIE) is 50% and for Semester End Exam (SEE) is 50%.
The minimum passing mark for the CIE is 40% of the maximum marks (20 marks out of 50) and for the
SEE minimum passing mark is 35% of the maximum marks (18 out of 50 marks).
A student shall be deemed to have satisfied the academic requirements and earned the credits allotted to
each subject/ course if the student secures a minimum of 40% (40 marks out of 100) in the sum total of the
CIE (Continuous Internal Evaluation) and SEE (Semester End Examination) taken together.
IPCC means practical portion integrated with the theory of the course.
CIE marks for the theory component are 25 marks and that for the practical component is 25 marks.
CIE for the theory component of the IPCC (Maximum Marks 25)
25 marks for the theory component are split into
o 15 marks for two Internal Assessment Tests (Average of Two Tests each of 25 Marks , scale down the
marks scored to 15 marks)
The first test at the end of 40-50% coverage of the syllabus and
The second test after covering 85-90% of the syllabus
o 10 marks for other assessment methods mentioned in 22OB4.2.
Scaled-down marks of the sum of two tests and other assessment methods will be CIE marks for the theory
component of IPCC (that is for 25 marks).
The student has to secure 40% of 25 marks (10 marks) to qualify in the CIE of the theory component of IPCC.
CIE for the practical component of the IPCC (Maximum Marks 25)
25 marks for the practical component are split into
o 15 marks for the conduction of the experiment and preparation of laboratory record, and 10 marks for
the test to be conducted after the completion of all the laboratory sessions.
o On completion of every experiment/program in the laboratory, the students shall be evaluated including
viva-voce and marks shall be awarded on the same day.
The theory portion of the IPCC shall be for both CIE and SEE, whereas the practical portion will have a CIE
component only. Questions mentioned in the SEE paper may include questions from the practical component.
To put it simply, evaluation techniques/methods are listed in the table for further understanding
The laboratory test (duration 02/03 hours) at the end of the 15th week of the semester /after completion of all the
experiments (whichever is early) shall be conducted for 50 marks and scaled down to 10 marks.
2 UPS 10KVA 1
Sl
PROGRAMS
No.
PREREQUISITE
Students should be familiarized about java installation and setting the java environment.
Usage of IDEs like Eclipse/Netbeans should be introduced.
PART A – List of problems for which student should develop program and execute in the Laboratory
Develop a JAVA program to add TWO matrices of suitable order N (The value of N should be read from
1
command line arguments).
Develop a stack class to hold a maximum of 10 integers with suitable methods. Develop a JAVA main
2
method to illustrate Stack operations.
A class called Employee, which models an employee with an ID, name and salary, is designed as shown
3 in the following class diagram. The method raiseSalary (percent) increases the salary by the given
percentage. Develop the Employee class and suitable main method for demonstration.
A class called MyPoint, which models a 2D point with x and y coordinates, is designed as follows:
● Two instance variables x (int) and y (int).
● A default (or "no-arg") constructor that construct a point at the default location of (0, 0).
● A overloaded constructor that constructs a point with the given x and y coordinates.
● A method setXY() to set both x and y.
● A method getXY() which returns the x and y in a 2-element int array.
● A toString() method that returns a string description of the instance in the format "(x, y)".
4
● A method called distance(int x, int y) that returns the distance from this point to another point at the
given (x, y) coordinates
● An overloaded distance(MyPoint another) that returns the distance from this point to the given MyPoint
instance (called another)
● Another overloaded distance() method that returns the distance from this point to the origin (0,0)
Develop the code for the class MyPoint. Also develop a JAVA program (called TestMyPoint) to test all
the methods defined in the class.
Develop a JAVA program to create a class named shape. Create three sub classes namely: circle, triangle
5 and square, each class has two member functions named draw () and erase (). Demonstrate polymorphism
concepts by developing suitable methods, defining member data and main program.
Develop a JAVA program to create an abstract class Shape with abstract methods calculateArea() and
6 calculatePerimeter(). Create subclasses Circle and Triangle that extend the Shape class and implement the
respective methods to calculate the area and perimeter of each shape.
Develop a JAVA program to create an interface Resizable with methods resizeWidth(int width) and
7 resizeHeight(int height) that allow an object to be resized. Create a class Rectangle that implements the
Resizable interface and implements the resize methods
Develop a JAVA program to create an outer class with a function display. Create another class inside the
8
outer class named inner with a function called display and call the two functions in the main class.
Develop a JAVA program to raise a custom exception (user defined exception) for DivisionByZero using
try, catch, throw and finally
9
Develop a JAVA program to create a package named mypack and import & implement it in a suitable
10
class.
Write a program to illustrate creation of threads using runnable class. (start method start each of the
11
newly created thread. Inside the run method there is sleep() for suspend the thread for 500 milliseconds).
The weightage of Continuous Internal Evaluation (CIE) is 50% and for Semester End Exam (SEE) is
50%. The minimum passing mark for the CIE is 40% of the maximum marks (20 marks out of 50)
and for the SEE minimum passing mark is 35% of the maximum marks (18 out of 50 marks). A
student shall be deemed to have satisfied the academic requirements and earned the credits allotted to
each subject/ course if the student secures a minimum of 40% (40 marks out of 100) in the sum total
of the CIE (Continuous Internal Evaluation) and SEE (Semester End Examination) taken together.
CIE for the theory component of the IPCC (maximum marks 50)
● IPCC means practical portion integrated with the theory of the course.
● CIE marks for the theory component are 25 marks and that for the practical component is 25 marks.
● 25 marks for the theory component are split into 15 marks for two Internal Assessment Tests (Two
Tests, each of 15 Marks with 01-hour duration, are to be conducted) and 10 marks for other
assessment methods mentioned in 22OB4.2. The first test at the end of 40-50% coverage of the
syllabus and the second test after covering 85-90% of the syllabus.
● Scaled-down marks of the sum of two tests and other assessment methods will be CIE marks for the
theory component of IPCC (that is for 25 marks).
● The student has to secure 40% of 25 marks to qualify in the CIE of the theory component of IPCC.
1. Open a command prompt by typing cmd in the search bar and press Enter.
2. Run the following command:
java -version
The command outputs the Java version on your system. If Java isn't installed, the output is a
message stating that Java isn't recognized as an internal or external command.
1. Using your preferred web browser, navigate to the Oracle Java Downloads page.
2. On the Downloads page, click the x64 Installer download link under
the Windows category.
2. After clicking Next, the following Destination Folder section is visible. Set the path
wherein the Java 18 directories and files will get installed. Keep it the default i.e., here it will
install under the following path: “C:\Program Files\Java\jdk-18″. Click on Next:
To set JDK Path, the easiest way is to type Environment Variables on Start. On typing, the
following would be visible. Now, click on Edit Environment Variables,
Now, the steps are displayed as a list marked in the below screenshot:
Step 4: Then click on the “Download” button. After clicking on the download button, the
.exe file for the eclipse will be downloaded.
Step 5: Now go to File Explorer and click on “Downloads” after that click on the “eclipse-
inst-jre-win64.exe” file to install Eclipse IDE.
Step 6: Then, click on “Eclipse IDE for Java Developers”.
Theory:
DATA TYPES
Data types are divided into two groups:
Primitive data types - includes byte, short, int, long, float, double, Boolean and char
Non-primitive data types - such as String, Arrays and Classes
Primitive types are predefined (already defined) in Java. Non-primitive types are
created by the programmer and is not defined by Java (except for String).
Non-primitive types can be used to call methods to perform certain operations, while
primitive types cannot.
A primitive type has always a value, while non-primitive types can be null.
A primitive type starts with a lowercase letter, while non-primitive types start with an
uppercase letter.
The size of a primitive type depends on the data type, while non-primitive types have
all the same size.
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Bitwise operators
1. Arithmetic Operators
2. Assignment Operators
Assignment operators are used to assign values to variables.
We can add two matrices in java using binary + operator. A matrix is also known as array
of arrays. We can add, subtract and multiply matrices.
Decision making in Java executes a particular segment of code based on the result of a Boolean
condition. It is important because conditions define the flow of programs and the output of a
particular program.
The decision-making principles in Java chiefly consist of if else statements, continue, break
and switch statements. It decides the flow of the program control during the execution of the
program.
1. If
2. if-else
3. nested-if
4. if-else-if
5. switch-case
6. jump-break, continue
1. IF Statement
2. IF-ELSE Statement
This pair of keywords is used to divide a program to be executed into two parts, one being the
code to be executed if the condition evaluates to true and the other one to be executed if the
value is false. However, if no curly braces are given the first statement after the if or else
keyword is executed.
Syntax Flowchart
if(condition)
{
//code to be executed if the condition is true
}
else
{
//code to be executed if the condition is false
}
Syntax: Flowchart
if(condition)
{
//code to be executed
if(condition)
{
//code to be executed
}
}
These statements are similar to the if else statements. The only difference lies in the fact that
each of the else statements can be paired with a different if condition statement. This renders
the ladder as a multiple-choice option for the user. As soon as one of the if conditions evaluate
to true the equivalent code is executed and the rest of the ladder is ignored.
Syntax: Flowchart
if
{
//code to be executed
}
else if(condition)
{
//code to be executed
}
else if(condition)
{
//code to be executed
}
else
{
//code to be executed
}
This saves the hassle of writing else if for every different option.
It branches the flow of the program to multiple points as and when required or specified
by the conditions.
It bases the flow of the program based on the output of the expression.
As soon as the expression is evaluated, the result is matched with each and every case
listed in the scope. If the output matches with any of the cases mentioned, then the
particular block is executed. A break statement is written after every end of the case block
so that the remaining statements are not executed.
The default case is written which is executed if none of the cases are the result of the
expression. This is generally the block where error statements are written.
Syntax Flowchart
switch(expression)
{
case <value1>:
//code to be executed
1. FOR LOOP
Java for loop provides a concise way of writing the loop structure. The for statement
consumes the initialization, condition and increment/decrement in one line thereby
providing a shorter, easy to debug structure of looping .
Syntax Flowchart
for (initialization expr; test expr; update
exp)
{
// body of the loop
// statements we want to execute
}
2. Test Expression: In this expression, we have to test the condition. If the condition
evaluates to true then, we will execute the body of the loop and go to update expression.
Otherwise, we will exit from the for loop.
Example: i <= 10
3. Update Expression: After executing the loop body, this expression
increments/decrements the loop variable by some value.
Example: i++;
2. WHILE Loop
Java while loop is a control flow statement that allows code to be executed repeatedly based
on a given Boolean condition. The while loop can be thought of as a repeating if statement.
While loop in Java comes into use when we need to repeatedly execute a block of statements.
The while loop is considered as a repeating if statement. If the number of iterations is not
fixed, it is recommended to use the while loop.
Syntax: Flowchart
while (test_expression)
{
// statements
update_expression;
}
2. Update Expression: After executing the loop body, this expression increments/decrements
the loop variable by some value.
Example: i++;
3. DO-WHILE LOOP
Java do-while loop is an Exit control loop. Therefore, unlike for or while loop, a do-while
check for the condition after executing the statements of the loop body.
Syntax: Flowchart
do
{
// Loop Body
Update_expression
}
// Condition check
while (test_expression);
Syntax:
for (type var : array)
{
statements using var;
Program 1:
Develop a JAVA program to add TWO matrices of suitable order N (The value of N
should be read from command line arguments).
import java.util.Scanner;
public class Add_Matrix
{
public static void main(String[] args)
{
int p, q, m, n;
Scanner s = new Scanner(System.in);
System.out.print("Enter number of rows in first matrix:");
p = s.nextInt();
System.out.print("Enter number of columns in first matrix:");
q = s.nextInt();
System.out.print("Enter number of rows in second matrix:");
m = s.nextInt();
System.out.print("Enter number of columns in second matrix:");
n = s.nextInt();
if (p == m && q == n)
{
int a[][] = new int[p][q];
int b[][] = new int[m][n];
int c[][] = new int[m][n];
System.out.println("Enter all the elements of first matrix:");
for (int i = 0; i < p; i++)
{
for (int j = 0; j < q; j++)
{
a[i][j] = s.nextInt();
}
Output:
Enter number of rows in first matrix:2
Enter number of columns in first matrix:3
Enter number of rows in second matrix:2
Enter number of columns in second matrix:3
Enter all the elements of first matrix:
1
2
3
4
5
6
Enter all the elements of second matrix:
7
8
9
4
3
2
First Matrix:
123
456
Second Matrix:
789
432
Matrix after addition:
8 10 12
888
Viva Questions:
OUTPUT:
RESULT:
Java programs to demonstrate the array concept were successfully written and executed
using Eclipse IDE and the result was verified.
Develop a stack class to hold a maximum of 10 integers with suitable methods. Develop a
JAVA main method to illustrate Stack operations.
This is a Java Program to implement a stack. Stack is an area of memory that holds all local
variables and parameters used by any function and remembers the order in which functions are
called so that function returns occur correctly. ‘push’ operation is used to add an element to
stack and ‘pop’ operation is used to remove an element from stack. ‘peek’ operation is also
implemented returning the value of the top element without removing it. The relation between
the push and pop operations is such that the stack is a Last-In-First-Out (LIFO) data structure.
The implemented stack has bounded capacity.
The stack is a linear data structure that is used to store the collection of objects. It is based on
Last-In-First-Out (LIFO). Java collection framework provides many interfaces and classes to
store the collection of objects. One of them is the Stack class that provides different operations
such as push, pop, search, etc.
In this section, we will discuss the Java Stack class, its methods, and implement the stack
data structure in a Java program. But before moving to the Java Stack class have a quick view
of how the stack works.
The stack data structure has the two most important operations that are push and pop. The
push operation inserts an element into the stack and pop operation removes an element from
the top of the stack. Let's see how they work on stack.
Let's push 20, 13, 89, 90, 11, 45, 18, respectively into the stack.
Empty Stack: If the stack has no element is known as an empty stack. When the stack is
empty the value of the top variable is -1.
1. public Stack()
Creating a Stack
If we want to create a stack, first, import the java.util package and create an object of the Stack
class.
Where type denotes the type of stack like Integer, String, etc.
Methods of the Stack Class
We can perform push, pop, peek and search operation on the stack. The Java Stack class
provides mainly five methods to perform these operations. Along with this, it also provides all
the methods of the Java Vector class.
push(E item) E The method pushes (insert) an element onto the top of
the stack.
pop() E The method removes an element from the top of the stack
and returns the same element as the value of that
function.
peek() E The method looks at the top element of the stack without
removing it.
search(Object int The method searches the specified object and returns the
o) position of the object.
Returns: The method returns true if the stack is empty, else returns false.
/* Class StackImplement */
public class StackImplement
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
default :
System.out.println("Wrong Entry \n ");
break;
}
/* display stack */
stk.display();
System.out.println("\nDo you want to continue (Type y or n) \n");
ch = scan.next().charAt(0);
RESULT:
Java programs to demonstrate the stack operation were successfully written and executed
using Eclipse IDE and the result was verified.
OUTPUT:
Enter Size of Integer Stack
3
Stack Operations
1. push
2. pop
1
Enter integer element to push
34
Stack = 34
Do you want to continue (Type y or n)
y
Stack Operations
1. push
2. pop
1
Enter integer element to push
45
Stack = 45 34
1. What is a stack?
3. What are the conditions to be checked before inserting / deleting elements from
the stack?
6. What is recursion?
OBJECT
An entity that has state and behaviour is known as an object e.g., chair, bike, marker, pen, table,
car, etc. It can be physical or logical (tangible and intangible). The example of an intangible
object is the banking system.
An object has three characteristics:
State: represents the data (value) of an object.
Behaviour: represents the behaviour (functionality) of an object such as deposit,
withdraw, etc.
Identity: An object identity is typically implemented via a unique ID. The value of the
ID is not visible to the external user. However, it is used internally by the JVM to
identify each object uniquely.
An object is an instance of a class. A class is a template or blueprint from which objects are
created. So, an object is the instance(result) of a class.
CLASS
A class is a group of objects which have common properties. It is a template or blueprint from
which objects are created. It is a logical entity. It can't be physical.
A class in Java can contain:
Fields
Methods
Constructors
Blocks
Nested class and interface
Syntax to declare a class:
class <class_name>{
field;
method;
}
CONSTRUCTOR
In Java, a constructor is a block of codes similar to the method. It is called when an instance of
the class is created. At the time of calling constructor, memory for the object is allocated in the
memory.
It is a special type of method which is used to initialize the object.
Every time an object is created using the new() keyword, at least one constructor is called.
It calls a default constructor if there is no constructor available in the class. In such case, Java
compiler provides a default constructor by default.
Rules for creating Java constructor
There are two rules defined for the constructor.
Program 3:
A class called Employee, which models an employee with an ID, name and salary, is
designed as shown in the following class diagram. The method raise Salary (percent)
increases the salary by the given percentage. Develop the Employee class and suitable
main method for demonstration.
package employee;
class Employee {
private String name;
private int id;
private double salary;
employee1.raiseSalary(8);
employee2.raiseSalary(12);
Employee Details:
Name: Franziska Waltraud
ID: 1
Salary: 40000.0
Name: Hubertus Andrea
ID: 2
Salary: 60000.0
Viva Questions
1. Create a class named 'Student' with String variable 'name' and integer variable 'roll_no'.
Assign the value of roll_no as '2' and that of name as "John" by creating an object of the
class Student.
1. METHOD OVERLOADING
If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading. If we have to perform only one operation, having same name of the
methods increases the readability of the program.
Suppose you have to perform addition of the given numbers but there can be any number of
arguments, if you write the method such as a(int, int) for two parameters, and b(int, int, int) for
three parameters then it may be difficult for you as well as other programmers to understand
the behaviour of the method because its name differs.
So, we perform method overloading to figure out the program quickly.
2. CONSTRUCTOR OVERLOADING
3. OVERRIDING
Method overriding is one of the ways by which java achieve Polymorphism. The version of
a method that is executed will be determined by the object that is used to invoke it. If an
object of a parent class is used to invoke the method, then the version in the parent class will
be executed, but if an object of the subclass is used to invoke the method, then the version
in the child class will be executed. In other words, it is the type of the object being referred
A class called MyPoint, which models a 2D point with x and y coordinates, is designed
as follows:
● Two instance variables x (int) and y (int).
● A default (or "no-arg") constructor that construct a point at the default location of (0,
0).
● A overloaded constructor that constructs a point with the given x and y coordinates.
● A method setXY() to set both x and y.
● A method getXY() which returns the x and y in a 2-element int array.
● A toString() method that returns a string description of the instance in the format "(x,
y)".
● A method called distance(int x, int y) that returns the distance from this point to
another point at the given (x, y) coordinates
● An overloaded distance(MyPoint another) that returns the distance from this point to
the given MyPoint instance (called another)
● Another overloaded distance() method that returns the distance from this point to the
origin (0,0) Develop the code for the class MyPoint. Also develop a JAVA program
(called TestMyPoint) to test all the methods defined in the class.
PROGRAM 4:
package employee;
class MyPoint
{
private int x = 0;
private int y = 0;
public MyPoint()
{
this(0, 0);
}
public MyPoint(int x, int y)
{
this.x = x;
this.y = y;
}
OUTPUT:
(0, 0)
x is: 8
y is: 6
3
0
(3, 0)
3.0
5.0
6.324555320336759
RESULT:
Java programs to demonstrate the decision-making statements and loops constructs was
successfully written and executed using Eclipse IDE and the result was verified.
OOPs in java is to improve code readability and reusability by defining a Java program
efficiently. The main principles of object-oriented programming are abstraction,
encapsulation, inheritance, and polymorphism. These concepts aim to implement real-world
entities in programs.
List of OOPs Concepts in Java
Objects
Classes
Abstraction
Inheritance
Polymorphism
Encapsulation
1. ABSTRACTION
Abstraction is a process which displays only the information needed and hides the unnecessary
information. The main purpose of abstraction is data hiding. Abstraction means selecting data
from a large number of data to show the information needed, which helps in reducing
programming complexity and efforts.
There are also abstract class and abstract methods. An abstract class is a type of class that
declares one or more abstract methods. An abstract method is a method that has a method
definition but not implementation. Once the object is modelled using data abstraction, the same
sets of data can also be used in different applications—abstract classes, generic types of
behaviours and object-oriented programming hierarchy. Abstract methods are used when two
or more subclasses do the same task in different ways and through different implementations.
An abstract class can have both the methods, i.e., abstract methods and regular methods.
2. INHERITANCE
Inheritance is a method in which one object acquires/inherits another object’s properties, and
inheritance also supports hierarchical classification. The idea behind this is that we can create
new classes built on existing classes, i.e., when you inherit from an existing class, we can reuse
methods and fields of the parent class. Inheritance represents the parent-child relationship. To
know more about this concept check the free inheritance in java course.
There are five types of inheritance single, multilevel, multiple, hybrid and hierarchical.
Single level
In this one class i.e., the derived class inherits properties from its parental class. This enables
code reusability and also adds new features to the code. Example: class B inherits properties
from class A. Class A is the base or parental class and class B is the derived class.
Multilevel
This one class is derived from another class which is also derived from another class i.e., this
class has more than one parental class, hence it is called multilevel inheritance.
Hierarchical level
In this one parental class has two or more derived classes or we can say that two or more child
classes has one parental class.
Hybrid inheritance
This is the combination of multiple and multilevel inheritance and in java multiple inheritance
is not supported as it leads to ambiguity and this type of inheritance can only be achieved
through interfaces.
Consider that class a is the parental or base class of class b and class c and in turn class b and
class c are parental or base class of class d. Class b and class c are derived classes from class a
and class d is derived class from class b and class c.
Single level Multilevel
Class a { Class a {
… ….
} }
Class b extends class a { Class b extends class a {
… ….
} }
Class c extends class b {
…
}
Hierarchical level
Class a {
…
}
3. POLYMORPHISM
Polymorphism refers to many forms, or it is a process that performs a single action in different
ways. It occurs when we have many classes related to each other by inheritance.
Polymorphism is of two different types, i.e., compile-time polymorphism and runtime
polymorphism. One of the examples in Compile time polymorphism is that when we overload
a static method in java. Run time polymorphism is also called a dynamic method dispatch is
a method in which a call to an overridden method is resolved at run time rather than compile
time. In this method, the overridden method is always called through the reference variable.
By using method overloading and method overriding, we can perform polymorphism.
Generally, the concept of polymorphism is often expressed as one interface, multiple
methods. This reduces complexity by allowing the same interface to be used as a general class
of action.
4. ENCAPSULATION
Encapsulation is one of the concepts in OOPs concepts; it is the process that binds together the
data and code into a single unit and keeps both from being safe from outside interference and
misuse. In this process, the data is hidden from other classes and can be accessed only through
the current class’s methods. Hence, it is also known as data hiding. Encapsulation acts as a
protective wrapper that prevents the code and data from being accessed by outsiders. These are
controlled through a well-defined interface.
Encapsulation is achieved by declaring the variables as private and providing public setter and
getter methods to modify and view the variable values. In encapsulation, the fields of a class
are made read-only or write-only. This method also improves the re-usability. Encapsulated
code is also easy to test for unit testing.
Develop a JAVA program to create a class named shape. Create three sub classes
namely: circle, triangle and square, each class has two member functions named draw
() and erase (). Demonstrate polymorphism concepts by developing suitable methods,
defining member data and main program.
package employee;
class Shapes {
public void draw() {
System.out.println("Drawing a shape");
}
System.out.println("Triangle. Erase()");
}
}
System.out.println("Circle. Erase()");
}
}
System.out.println("square. Erase()");
}
OUTPUT:
Drawing a shape
Triangle is ½ * base * height
Drawing a shape
Circle is 3.14 * radius * radius
Drawing a square
Triangle.erase()
Circle.erase()
square.erase()
RESULT:
Java program to demonstrate the core object-oriented concept of Inheritance, polymorphism
was written and executed using Eclipse IDE and the result was verified.
1. Write a program to design Car class (subclass) inherits the attributes and methods from
the Vehicle class (superclass):
2. Loop through the elements of an ArrayList with a for loop, and use the size()
method to specify how many times the loop should run:
1. ABSTRACTION
Data Abstraction is the property by virtue of which only the essential details are displayed to
the user. The trivial or the non-essential units are not displayed to the user. Ex: A car is viewed
as a car rather than its individual components.
Data Abstraction may also be defined as the process of identifying only the required
characteristics of an object ignoring the irrelevant details. The properties and behaviours of an
object differentiate it from other objects of similar type and also help in classifying/grouping
the objects.
Consider a real-life example of a man driving a car. The man only knows that pressing the
accelerators will increase the speed of a car or applying brakes will stop the car, but he does
not know how on pressing the accelerator the speed is actually increasing, he does not know
about the inner mechanism of the car or the implementation of the accelerator, brakes, etc in
the car. This is what abstraction is.
In java, abstraction is achieved by interfaces and abstract classes. We can achieve 100%
abstraction using interfaces.
In java, the following some important observations about abstract classes are as follows:
1. An instance of an abstract class cannot be created.
2. Constructors are allowed.
3. We can have an abstract class without any abstract method.
4. There can be a final method in abstract class but any abstract method in
class(abstract class) cannot be declared as final or in simpler terms final method
cannot be abstract itself as it will yield an error: “Illegal combination of modifiers:
abstract and final”
5. We can define static methods in an abstract class
6. We can use the abstract keyword for declaring top-level classes (Outer class) as
well as inner classes as abstract
7. If a class contains at least one abstract method then compulsory should declare a
class as abstract
8. If the Child class is unable to provide implementation to all abstract methods of
the Parent class, then we should declare that Child class as abstract so that the
next level Child class should provide implementation to the remaining abstract
method
2. ABSTRACT METHOD
PROGRAM 6:
Develop a JAVA program to create an abstract class Shape with abstract methods
calculateArea() and calculatePerimeter(). Create subclasses Circle and Triangle that
extend the Shape class and implement the respective methods to calculate the area and
perimeter of each shape.
package employee;
@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
@Override
public double calculatePerimeter() {
return 2 * Math.PI * radius;
}
}
@Override
public double calculateArea() {
double s = (side1 + side2 + side3) / 2;
return Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));
}
@Override
public double calculatePerimeter() {
return side1 + side2 + side3;
}
}
OUTPUT:
Radius of the Circle4.0
Area of the Circle: 50.26548245743669
Perimeter of the Circle: 25.132741228718345
Java program to introduce concepts of abstract class was successfully written and executed
using Eclipse IDE and the result is verified
Viva Questions
An Interface in Java programming language is defined as an abstract type used to specify the
behaviour of a class. An interface in Java is a blueprint of a class. A Java interface contains
static constants and abstract methods.
The interface in Java is a mechanism to achieve abstraction. There can be only abstract
methods in the Java interface, not the method body. It is used to achieve abstraction
and multiple inheritance in Java. In other words, interfaces can have abstract methods and
variables. It cannot have a method body. Java Interface also represents the IS-A relationship.
Like a class, an interface can have methods and variables, but the methods declared in an
interface are by default abstract (only method signature, no body).
Interfaces specify what a class must do and not how. It is the blueprint of the class.
An Interface is about capabilities like a Player may be an interface and any class
implementing Player must be able to (or must implement) move(). So, it specifies
a set of methods that the class has to implement.
If a class implements an interface and does not provide method bodies for all
functions specified in the interface, then the class must be declared abstract.
A Java library example is Comparator Interface. If a class implements this interface,
then it can be used to sort a collection.
Syntax:
interface {
// declare constant fields
// declare methods that abstract
// by default.
}
To declare an interface, use the interface keyword. It is used to provide total abstraction. That
means all the methods in an interface are declared with an empty body and are public and all
fields are public, static, and final by default. A class that implements an interface must
implement all the methods declared in the interface. To implement interface use implements
keyword.
Why do we use an Interface?
It is used to achieve total abstraction.
Since java does not support multiple inheritances in the case of class, by using an
interface it can achieve multiple inheritances.
It is also used to achieve loose coupling.
Interfaces are used to implement abstraction. So the question arises why use
interfaces when we have abstract classes?
The reason is, abstract classes may contain non-final variables, whereas variables in the
interface are final, public and static
package employee;
//Resizable.java
interface Resizable {
void resizeWidth(int width);
void resizeHeight(int height);
}
//Rectangle.java
class Rectangle implements Resizable {
private int width;
private int height;
rectangle.resizeWidth(150);
rectangle.resizeHeight(200);
rectangle.printSize();
}
OUTPUT:
Width: 100, Height: 150
Width: 150, Height: 200
RESULT:
Java program to Introduce the concept of interface was written and successfully executed using
eclipse IDE and the result was verified.
Viva Questions
3. What do you understand by Object Cloning and how do you achieve it in Java?
In Java, inner class refers to the class that is declared inside class or interface which were
mainly introduced, to sum up, same logically relatable classes as Java is purely object-oriented
so bringing it closer to the real world. Now geeks you must be wondering why they were
introduced?
There are certain advantages associated with inner classes are as follows:
Making code clean and readable.
Private methods of the outer class can be accessed, so bringing a new dimension
and making it closer to the real world.
Optimizing the code module.
PROGRAM 8:
Develop a JAVA program to create an outer class with a function display. Create another
class inside the outer class named inner with a function called display and call the two
functions in the main class.
package employee;
class Outer {
// Method defined inside outer class
void display()
{
// Print statement
System.out.println("inside outerMethod");
}
// Class 2
// Simple nested inner class
class Inner {
// Print statement
System.out.println("In a nested class method");
}
}
}
public class Point {
OUTPUT
Viva Questions:
THEORY:
Exception Handling in Java is one of the effective means to handle the runtime errors so that
the regular flow of the application can be preserved. Java Exception Handling is a mechanism
to handle runtime errors such as ClassNotFoundException, IOException, SQLException,
RemoteException, etc.
Exception is an unwanted or unexpected event, which occurs during the execution of a
program, i.e., at run time, that disrupts the normal flow of the program’s instructions.
Exceptions can be caught and handled by the program. When an exception occurs within a
method, it creates an object. This object is called the exception object. It contains information
about the exception, such as the name and description of the exception and the state of the
program when the exception occurred.
Exception Hierarchy
All exception and error types are subclasses of class Throwable, which is the base class of the
hierarchy. One branch is headed by Exception. This class is used for exceptional conditions
that user programs should catch. NullPointerException is an example of such an exception.
Another branch, Error is used by the Java run-time system(JVM) to indicate errors having to
do with the run-time environment itself(JRE). StackOverflowError is an example of such an
error.
PROGRAM 9:
Develop a JAVA program to raise a custom exception (user defined exception) for
DivisionByZero using try, catch, throw and finally.
package employee;
class DivideByZeroException extends Exception {
public DivideByZeroException(String message) {
super(message);
}
}
public class Point {
OUTPUT 1 :
Result: 7
I am in final block
OUTPUT 2 :
RESULT:
Java program to handle Exception in java, introduction to throwable class, throw, throws,
finally was successfully written and executed using the Eclipse IDE and the result was
verified
Viva Questions:
Package in Java is a mechanism to encapsulate a group of classes, sub packages and interfaces.
Packages are used for:
Preventing naming conflicts. For example there can be two classes with name
Employee in two packages, college.staff.cse.Employee and
college.staff.ee.Employee
Making searching/locating and usage of classes, interfaces, enumerations and
annotations easier
Providing controlled access: protected and default have package level access
control. A protected member is accessible by classes in the same package and its
subclasses. A default member (without any access specifier) is accessible by classes
in the same package only.
Packages can be considered as data encapsulation (or data-hiding).
All we need to do is put related classes into packages. After that, we can simply write an import
class from existing packages and use it in our program. A package is a container of a group of
related classes where some of the classes are accessible are exposed and others are kept for
internal purpose.
We can reuse existing classes from the packages as many times as we need it in our program.
Package naming conventions: Packages are named in reverse order of domain names, i.e.,
org.geeksforgeeks.practice. For example, in a college, the recommended convention is
college.tech.cse, college.tech.ee, college.art.history, etc.
Adding a class to a Package: We can add more classes to a created package by using package
name at the top of the program and saving it in the package directory. We need a new java file
to define a public class, otherwise we can add the new class to an existing .java file and
recompile it.
Subpackages: Packages that are inside another package are the subpackages. These are not
imported by default; they have to imported explicitly. Also, members of a subpackage have no
access privileges, i.e., they are considered as different package for protected and default access
specifiers.
Types of packages:
1. java.lang: Contains language support classes(e.g classed which defines primitive data
types, math operations). This package is automatically imported.
2. java.io: Contains classed for supporting input / output operations.
3. java.util: Contains utility classes which implement data structures like Linked List,
Dictionary and support ; for Date / Time operations.
4. java.applet: Contains classes for creating Applets.
5. java.awt: Contain classes for implementing the components for graphical user interfaces
(like button, menus etc).
6. java.net: Contain classes for supporting networking operations.
User-defined packages
These are the packages that are defined by the user. First, we create a
directory myPackage (name should be same as the name of the package). Then create
the MyClass inside the directory with the first statement being the package names.
How to Create a package?
Creating a package is a simple task as follows
Develop a JAVA program to create a package named mypack and import & implement
it in a suitable class.
package employee2;
package employee;
import employee2.pack;
public class Point {
OUTPUT:
Hello
RESULT:
VIVA QUESTIONS:
4. With an example Java code show the use of super keyword with variables
Aim: Demonstrate creation of threads using Thread class and Runnable interface,
multi-threaded programming.
THEORY:
Typically, threads can be defined as a subprocess with lightweight with the smallest unit of
processes and also has separate paths of execution. These threads use shared memory but they
act independently hence if there is an exception in threads that do not affect the working of
other threads despite them sharing the same memory.
In the above diagram a thread runs inside the process and there will be context-based switching
between threads there can be multiple processes running in OS, and each process again can
have multiple threads running simultaneously. The Multithreading concept is popularly applied
in games, animation…etc.
The Concept of Multitasking
To help users, Operating System accommodates users the privilege of multitasking, where
users can perform multiple actions simultaneously on the machine. This Multitasking can be
enabled in two ways:
1. Process-Based Multitasking
2. Thread-Based Multitasking
We can see the working of different states in a Thread in the above Diagram.
1. New State
By default, a Thread will be in a new state, in this state, code has not yet been run and the
execution process is not yet initiated.
2. Active State
A Thread that is a new state by default gets transferred to Active state when it invokes the
start() method, his Active state contains two sub-states namely:
Runnable State: In This State, The Thread is ready to run at any given time and
it’s the job of the Thread Scheduler to provide the thread time for the runnable state
preserved threads. A program that has obtained Multithreading shares slices of time
intervals which are shared between threads hence, these threads run for some short
3. Waiting/Blocked State
If a Thread is inactive but on a temporary time, then either it is at waiting or blocked state, for
example, if there are two threads, T1 and T2 where T1 need to communicate to the camera and
other thread T2 already using a camera to scan then T1 waits until T2 Thread completes its
work, at this state T1 is parked in waiting for the state, and in another scenario, the user called
two Threads T2 and T3 with the same functionality and both had same time slice given by
Thread Scheduler then both Threads T1, T2 is in a blocked state. When there are multiple
threads parked in Blocked/Waiting state Thread Scheduler clears Queue by rejecting unwanted
Threads and allocating CPU on a priority basis.
4. Timed Waiting State
Sometimes the longer duration of waiting for threads causes starvation, if we take an example
like there are two threads T1, T2 waiting for CPU and T1 is undergoing Critical Coding
operation and if it does not exit CPU until its operation gets executed then T2 will be exposed
to longer waiting with undetermined certainty, In order to avoid this starvation situation, we
had Timed Waiting for the state to avoid that kind of scenario as in Timed Waiting, each thread
has a time period for which sleep() method is invoked and after the time expires the Threads
starts executing its task.
5. Terminated State
A thread will be in Terminated State, due to the below reasons:
Termination is achieved by a Thread when it finishes its task Normally.
Sometimes Threads may be terminated due to unusual events like segmentation
faults, exceptions…etc. and such kind of Termination can be called Abnormal
Termination.
A terminated Thread means it is dead and no longer available.
What is Main Thread?
As we are familiar that, we create Main Method in each and every Java Program, which acts
as an entry point for the code to get executed by JVM, similarly in this Multithreading Concept,
Each Program has one Main Thread which was provided by default by JVM, hence whenever
a program is being created in java, JVM provides the Main Thread for its Execution.
How to Create Threads using Java Programming Language?
We can create Threads in java using two ways, namely:
1. By extending Thread Class
2. By Implementing a Runnable interface
PROGRAM 11:
Write a program to illustrate creation of threads using runnable class. (start method start
each of the newly created thread. Inside the run method there is sleep() for suspend the
thread for 500 milliseconds).
import java.util.Random;
import java.util.Scanner;
class randThread extends Thread
{
Random rm=new Random();
public void run()
{
for(int i=0;i<10;i++)
{
System.out.println("Random no. : "+rm.nextInt(100));
try
{
Thread.sleep(1000);
}
catch(InterruptedException ex)
{
ex.printStackTrace();
}
}
}
}
class squareThread extends Thread
{
int num;
squareThread(int n)
{
num=n;
}
public void run()
{
for(int i=1;i<+num;i++)
System.out.println("square of "+i+"-"+(i*i));
}
}
class cubeThread extends Thread
{
int num;
cubeThread(int n)
{
num=n;
}
OUTPUT
RESULT:
Java program to demonstrate creation of threads using Thread class and Runnable interface,
multi-threaded programming was successfully written and executed using eclipse IDE and the
result was verified.
VIVA QUESTIONS
1) What is multithreading?
2) What is thread?
PROGRAM 12:
Develop a program to create a class MyThread in this class a constructor, call the base
class constructor, using super and start the thread. The run method of the class starts
after this. It can be observed that both main thread and created child thread are
executed concurrently.
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(getName() + ": Count " + i);
try {
Thread.sleep(1000); // Sleep for 1 second
} catch (InterruptedException e) {
System.out.println(e);
}
}
System.out.println(getName() + " has finished.");
}
}
class HelloWorld {
public static void main(String[] args) {
MyThread childThread = new MyThread("Child Thread");
childThread.start(); // Start the child thread
OUTPUT 1:
Main Thread: Count 1Child Thread: Count 1
Main Thread: Count 2
Child Thread: Count 2
Main Thread: Count 3
Child Thread: Count 3Main Thread: Count 4
Child Thread: Count 4
Main Thread: Count 5
Child Thread: Count 5
Main Thread has finished.
Child Thread has finished.
RESULT:
This program demonstrates the concurrent execution of the main thread and the child
thread.
VIVA QUESTIONS:
12. Create a class called Invoice that a hardware store might use to represent an invoice for
an item sold at the store. An Invoice should include four pieces of information as instance
variables‐a part number (type String), a part description (type String),a quantity of the item
being purchased (type int) and a price per item (double). Your class should have a constructor
that initializes the four instance variables. Provide a set and a get method for each instance
variable. In addition, provide a method named getInvoice Amount that calculates the invoice
amount (i.e., multiplies the quantity by the price per item), then returns the amount as a double
value. If the quantity is not positive, it should be set to 0. If the price per item is not positive, it
should be set to 0.0. Write a test application named InvoiceTest that demonstrates class
Invoice’s capabilities.
13. Create a class called Employee that includes three pieces of information as instance
variables—a first name (typeString), a last name (typeString) and a monthly salary (double).
Your class should have a constructor that initializes the three instance variables. Provide a set
and a get method for each instance variable. If the monthly salary is not positive, set it to 0.0.
14. Create a class called Date that includes three pieces of information as instance
variables—a month (typeint), a day (typeint) and a year (typeint). Your class should have a
constructor that initializes the three instance variables and assumes that the values provided are
correct. Provide a set and a get method for each instance variable. Provide a method
displayDate that displays the month, day and year separated by forward slashes(/). Write a test
application named DateTest that demonstrates classDate’s capabilities.
15. Create class SavingsAccount. Usea static variable annualInterestRate to store the
annual interest rate for all account holders. Each object of the class contains a private instance
variable savingsBalance indicating the amount the saver currently has ondeposit. Provide
method calculateMonthlyInterest to calculate the monthly www.oumstudents.tk interest by
multiplying the savingsBalance by annualInterestRate divided by 12 this interest should be
added to savingsBalance. Provide a static method modifyInterestRate that sets the
annualInterestRate to a new value. Write a program to test class SavingsAccount. Instantiate
two savingsAccount objects, saver1 and saver2, with balances of $2000.00 and $3000.00,
respectively. Set annualInterestRate to 4%, then calculate the monthly interest and print the
new balances for both savers. Then set the annualInterestRate to 5%, calculate the next month’s
interest and print the new balances for both savers.
16. Create a class called Book to represent a book. A Book should include four pieces of
information as instance variables‐a book name, an ISBN number, an author name and a
publisher. Your class should have a constructor that initializes the four instance variables.
Provide a mutator method and accessor method (query method) for each instance variable.
Inaddition, provide a method named getBookInfo that returns the description of the book as a
String (the description should include all the information about the book). You should use this
keyword in member methods and constructor. Write a test application named BookTest to
create an array of object for 30 elements for class Book to demonstrate the class Book's
capabilities.
17. Create MyOwnAutoShop class which contains the main() method. Perform the
following within the main() method. ◦Create an instance of Sedan class and initialize all the
fields with appropriate values. Use super(...) method in the constructor for initializing the fields
of the superclass. ◦Create two instances of the Ford class and initialize all the fields with
appropriate values. Use super(...) method in the constructor for initializing the fields of the
super class. www.oumstudents.tk ◦Create an instance of Car class and initialize all the fields
with appropriate values. Display the sale prices of all instance.
18. Write an applet that asks the user to enter two floating‐point numbers, obtains the two
numbers from the user and draws their sum, product (multiplication), difference and quotient
(division). Use the techniques shown in example.
19. Create an applet that can display the following component. No event handling is needed
for the components.