OOP-I Lab Manual
OOP-I Lab Manual
Laboratory Manual
Year: 2024-2025
INDEX
From To
1. Basics of java
3. Constructors
6. Exception Handling
7. Abstract classes
8. Interfaces
Page 2 of 30
EXPERIMENT NO: 1 DATE: / /
THEORY:
What is Java:
Java is a programming language and a platform. Java is a high level, robust, secured and object- oriented
programming language. Any hardware or software environment in which a program runs, is known as a platform.
Since Java has its own runtime environment (JRE) and API, it is called platform
What is JVM
1. A specification where working of Java Virtual Machine is specified. But implementation provider is
independent to choose the algorithm. Its implementation has been provided by Sun and other companies.
2. An implementation Its implementation is known as JRE (Java Runtime Environment).
3. Runtime Instance Whenever you write java command on the command prompt to run the java class, an
instance of JVM is created.
The JVM loads code, verifies code, executes code and provides runtime environment. It provides definitions for
the memory area , class file format, register set, garbage-collected heap, fatal error reporting etc.
Page 3 of 30
Internal Architecture of JVM
EXERCISE:
1. Write a program to display “Welcome To Java World”.
REVIEW QUESTIONS:
1. Explain features of Java briefly
2. JVM is platform independent. Justify.
3. List out and explain three main principles of object-oriented programming.
EVALUATION:
Understanding /
Involvement Timely
Problem solving Total
Completion
(10)
(4) (3)
(3)
Page 4 of 30
.
EXPERIMENT NO: 2 DATE: / /
THEORY:
Methods can be used to define reusable code and organize and simplify coding. A method definition consists
of its method name, parameters, return value type, and body. To execute the method, you have to call or invoke
it.
Array Normally, array is a collection of similar type of elements that have contiguous memory location
It is an object that contains elements of similar data type. It is a data structure where we store similar elements.
We can store only fixed set of elements in a java array.
Array in java is index based, first element of the array is stored at 0 index.
Page 5 of 30
Size Limit: We can store only fixed size of elements in the array. It doesn't grow its size at runtime. To
solve this problem, collection framework is used in java.
EXERCISES:
1. Write a method to enter two integers and compute the gcd of two integers.
2. Write a program that creates a Random object with seed 1000 and displays the first 100 random integers between
1 and 49 using the NextInt (49) method.
3. Write a test program that prompts the user to enter ten numbers, invoke a method to reverse the numbers, display
the numbers.
REVIEW QUESTIONS:
1. Explain array implementation in Java.
EVALUATION:
Understanding /
Involvement Timely
Problem solving Total
Completion
(10)
(4) (3)
(3)
Page 6 of 30
EXPERIMENT NO: 3 DATE: / /
THEORY:
Object Definitions:
• Object is a real world entity.
• Object is a run time entity.
• Object is an entity which has state and behavior.
• Object is an instance of a class
Class in Java
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.
Constructor
In Java, constructor is a block of codes similar to method. It is called when an instance of object is created and
memory is allocated for the object. It is a special type of method which is used to initialize the object.
Page 7 of 30
There are basically two rules defined for the constructor.
EXCERCISE:
1. Write a program that declares a class named Person. It should have instance variables to record name, age and
salary. Use new operator to create a Person object. Set and display its instance variables. Add a constructor to the
Person class developed above.
2. The employee list for a company contains employee code, name, designation and basic pay. The employee is
given HRA of 10% of the basic and DA of 45% of the basic pay. The total pay of the employee is calculated as
Basic pay+HRA+ DA. Write a class to define the details of the employee. Write a constructor to assign the required
initial values. Add a method to calculate HRA, DA and Total pay and print them out. Write another class with a
main method. Create objects for three different employees and calculate the HRA, DA and total pay.
REVIEW QUESTIONS:
1. What is a constructor in JAVA? How many types of constructors are there in JAVA? Explain with examples.
2. Justify:
i) Why we declare main() method as public and static member.
ii) Why we generally declare constructor as public member.
iii) Why there is no destructor in java.
EVALUATION:
Understanding /
Involvement
Problem solving Timely Completion Total
(3) (10)
(4)
(3)
Page 8 of 30
EXPERIMENT NO: 4 DATE: / /
1) String Literal
Java String literal is created by using double quotes. For Example: String
s="welcome";
Each time you create a string literal, the JVM checks the string constant pool first. If the string already exists in the
pool, a reference to the pooled instance is returned. If string doesn't exist in the pool, a new string instance is created
and placed in the pool. For example:
1. String s1="Welcome";
2. String s2="Welcome";//will not create new instance
In such case, JVM will create a new string object in normal(non pool) heap memory and the literal "Welcome" will be
placed in the string constant pool. The variable s will refer to the object in heap(non pool).
Java String class provides a lot of methods to perform operations on string such as compare(), concat(), equals(), split(),
length(), replace(), compareTo(), intern(), substring() etc.
The java.lang.String class implements Serializable, Comparable and CharSequence interfaces.
Consider below code with three concatenation functions with three different types of parameters, String, StringBuffer
and StringBuilder.
// Java program to demonstrate difference between String, StringBuilder and StringBuffer class
Stringclasses
Page 9 of 30
{
public static void main(String[] args)
{
String s1 = "Ahmedabad"; concat1(s1);
// s1 is not changed
System.out.println("String: " + s1);
StringBuilder: AhmedabadInstitute
StringBuffer: AhmedabadUniversity
Explanation:
1. Concat1 : In this method, we pass a string “Ahmedabad” and perform “s1 = s1 + ”Institute”. The string passed
from main() is not changed, this is due to the fact that String is immutable. Altering the value of string creates
another object and s1 in concat1() stores reference of new string. References s1 in main() and cocat1() refer to
different strings.
2. Concat2 : In this method, we pass a string “Ahmedabad” and perform “s2.append(“Institute”)” which changes
the actual value of the string (in main) to “AhmedabadInstitute”. This is due to the simple fact that StringBuilder is
mutable and hence changes its value.
Page 10 of 30
2. Concat3 : StringBuffer is similar to StringBuilder except one difference that StringBuffer is thread safe, i.e., multiple
threads can use it without any issue. The thread safety brings a penalty of performance.
EXCERCISES:
REVIEW QUESTIONS:
1. State difference between String Class and StringBuffer Class.
EVALUATION:
Understanding /
Involvement
Problem solving Timely Completion Total
(3) (10)
(4)
(3)
Page 11 of 30
EXPERIMENT NO: 5 DATE: / /
Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent
object. It is an important part of OOPs (Object Oriented programming system). The idea behind inheritance in
java is that you can create new classes that are built upon existing classes. When you inherit from an existing
class, you can reuse methods and fields of parent class. Moreover, you can add new methods and fields in your
current class also.
Page 12 of 30
Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived class, extended class,
or child class.
Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is also called a base
class or a parent class.
Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the fields and methods
of the existing class when you create a new class. You can use the same fields and methods already defined in the
previous class.
Polymorphism in java is ‘a state of having many shapes’ or ‘the capacity to take on different forms’. When
applied to object-oriented programming languages like Java, it describes a language’s ability to process objects
of various types and classes through a single, uniform interface.
Method Overloading
Method overloading enables you to define the methods with the same name as long as their signatures are different.
Following program creates three methods. The first finds the maximum integer, the second finds the maximum
double, and the third finds the maximum among three double values. All three methods are named max.
Page 13 of 30
Method Overriding : If subclass (child class) has the same method as declared in the parent class, it is known as
method overriding in java. In other words, If subclass provides the specific implementation of the method that has
been provided by one of its parent class, it is known as method overriding.
Whenever you create the instance of subclass, an instance of parent class is created implicitly which is referred by
super reference variable.
class Animal{
String color="white";
} class Dog extends
Animal{String
color="black"; void printColor(){
System.out.println(color);//prints color of Dog class System.out.println(super.color);//prints color of Animal class } }
class TestSuper1{ public static void main(String args[]){
Dog d=new Dog(); d.printColor();
}}
black
white
REVIEW QUESTIONS:
1. What is inheritance in java? Explain different types of inheritance with proper example.
2. Explain following with example:
i) Finalize() ii) static iii) super iv) final
EVALUATION:
Understanding /
Involvement
Problem solving Timely Completion Total
(3) (10)
(4)
(3)
Page 15 of 30
EXPERIMENT NO: 6 DATE: / /
Types of Exception
There are mainly two types of exceptions: checked and unchecked where error is considered as unchecked
exception. The sun microsystem says there are three types of exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error
1) Checked Exception
The classes that extend Throwable class except Runtime Exception and Error are known as checked exceptions
e.g.IOException, SQLException etc. Checked exceptions are checked at compile-time.
2) Unchecked Exception
The classes that extend Runtime Exception are known as unchecked exceptions e.g. Arithmetic Exception, Null
Pointer Exception, Array Index Out Of Bounds Exception etc. Unchecked exceptions are not checked at compiletime
rather they are checked at runtime.
3) Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
Page 16 of 30
Java try block must be followed by either catch or finally block.
EXERCISE:
1. Write an exception class for a time of day that can accept only 24 hour representation of clock hours. Write a java
program to input various formats of timings and throw suitable error messages.
2. Write a method for computing by doing repetitive multiplication. x and y are of type integer and are to be
given as command line arguments. Raise and handle exception(s) for invalid values of x and y. Also define method
main. Use finally in above program and explain its usage.
3. Write a program to input name and age of a person and throws a user defined exception, if entered age is negative.
REVIEW QUESTIONS:
1. What is Exception? Demonstrate how you can handle different types of exception separately.
2. Differentiate the following: Checked and Unchecked exceptions.
.
EVALUATION:
Understanding /
Involvement
Problem solving Timely Completion Total
(3) (10)
(4)
(3)
Page 17 of 30
EXPERIMENT NO: 7 DATE: / /
THEORY:
Abstract class in Java
A class that is declared with abstract keyword, is known as abstract class in java. It can have abstract and nonabstract
methods (method with body).
Abstraction is a process of hiding the implementation details and showing only functionality to the user.
Another way, it shows only important things to the user and hides the internal details for example sending sms, you just
type the text and send the message. You don't know the internal processing about the message delivery.
Abstraction lets you focus on what the object does instead of how it does it.
abstract method
A method that is declared as abstract and does not have implementation is known as abstract method.
2. Create an abstract class ‘Shape’ with two members base and height , a member function for initialization and a
pure virtual function to compute area(). Derive two specific classes ‘Triangle’ and ‘Rectangle’ which override the
function area(). Use these classes in main function and display the area of triangle and rectangle.
Page 18 of 30
REVIEW QUESTIONS:
1. Differentiate between abstract class and Interface.
2. State whether the following statements are true or false.
(i) An abstract class contains constructors.
EVALUATION:
Understanding /
Involvement
Problem solving Timely Completion Total
(3) (10)
(4)
(3)
Page 19 of 30
EXPERIMENT NO: 8 DATE: / /
THEORY:
Interface
An interface in java is a blueprint of a class. It has 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 method body. It is used to achieve abstraction and multiple inheritance in Java.
In other words, you can say that interfaces can have methods and variables but the methods declared in interface contain
only method signature, not body.
Java Interface also represents IS-A relationship. It cannot
be instantiated just like abstract class.
An interface is a completely "abstract class" that is used to group related methods with empty bodies:
Page 20 of 30
EXCERCISE:
1. Write a program that illustrates interface inheritance. Interface A is extended by A1 and A2. Interface A12 inherits
from both P1 and P2.Each interface declares one constant and one method. Class B implements A12.Instantiate B
and invoke each of its methods. Each method displays one of the constants.
2. Write an interface called shape with methods draw() and getArea(). Further design two classes called ‘Circle’
and ‘Rectangle’ that implements ‘Shape’ to compute area of respective shapes. Use appropriate getter and setter
methods. Write a java program for the same.
REVIEW QUESTIONS:
1. What is Interface? Write steps to declare and define an interface and explain with sample program.
EVALUATION:
Understanding /
Involvement
Problem solving Timely Completion Total
(3) (10)
(4)
(3)
Page 21 of 30
EXPERIMENT NO: 9 DATE: / /
To fully benefit from JavaFX it is useful to understand how JavaFX is designed, and to have a good overview of
what features JavaFX contains. The purpose of this text is to give you that JavaFX overview. This text will first look
at the general JavaFX design, then look at the various features in JavaFX.
If you are familiar with Flash / Flex, you will see that JavaFX is somewhat inspired by Flash / Flex. Some of the
same ideas are found in JavaFX. In general, a JavaFX application contains one or more stages which corresponds
to windows. Each stage has a scene attached to it. Each scene can have an object graph of controls, layouts etc.
attached to it, called the scene graph. These concepts are all explained in more detail later. Here is an illustration of
the general structure of a JavaFX application:
Page 22 of 30
Stage:
The stage is the outer frame for a JavaFX application. The stage typically corresponds to a window. In the early
days where JavaFX could run in the browser, the stage could also refer to the area inside the web page that JavaFX
had available to draw itself.
Since the deprecation of the Java browser plugin JavaFX is mostly used for desktop applications. Here, JavaFX
replaces Swing as the recommended desktop GUI framework. When used in a desktop environment, a JavaFX
application can have multiple windows open. Each window has its own stage.
Each stage is represented by a Stage object inside a JavaFX application. A JavaFX application has a primary Stage
object which is created for you by the JavaFX runtime. A JavaFX application can create additional Stage objects if
it needs additional windows open. For instance, for dialogs, wizards etc.
Scene:
To display anything on a stage in a JavaFX application, you need a scene. A stage can only show one scene at a
time, but it is possible to exchange the scene at runtime. Just like a stage in a theater can be rearranged to show
multiple scenes during a play, a stage object in JavaFX can show multiple scenes (one at a time) during the life time
of a JavaFX application.
Imagine a computer game. A game might have multiple "screens" to show to the user. For instance, an initial menu
screen, the main game screen (where the game is played), a game over screen and a high score screen. Each of these
screens can be represented by a different scene. When the game needs to change from one screen to the next, it
simply attaches the corresponding scene to the Stage object of the JavaFX application.
A scene is represented by a Scene object inside a JavaFX application. A JavaFX application must create all Scene
objects it needs.
Scene Graph:
All visual components (controls, layouts etc.) must be attached to a scene to be displayed, and that scene must be
attached to a stage for the whole scene to be visible. The total object graph of all the controls, layouts etc. attached
to a scene is called the scene graph.
Nodes:
All components attached to the scene graph are called nodes. All nodes are subclasses of a JavaFX class called
javafx.scene.Node .
There are two types of nodes: Branch nodes and leaf nodes. A branch node is a node that can contain other nodes
(child nodes). Branch nodes are also referred to as parent nodes because they can contain child nodes. A leaf node
is a node which cannot contain other nodes.
Controls
JavaFX controls are JavaFX components which provide some kind of control functionality inside a JavaFX
application. For instance, a button, radio button, table, tree etc.
For a control to be visible it must be attached to the scene graph of some Scene object.
Page 23 of 30
Controls are usually nested inside some JavaFX layout component that manages the layout of controls relative to
each other.
Layouts
JavaFX layouts are components which contains other components inside them. The layout component manages
the layout of the components nested inside it. JavaFX layout components are also sometimes called parent
components because they contain child components, and because layout components are subclasses of the
JavaFX class javafx.scene.Parent.
A layout component must be attached to the scene graph of some Scene object to be visible. JavaFX contains
the following layout components:
Group StackPane VBox
Region TilePane FlowPane
Pane GridPane TextFlow
HBox AnchorPane BorderPane
Nested Layouts
It is possible to nest layout components inside other layout components. This can be useful to achieve a specific
layout. For instance, to get horizontal rows of components which are not layed out in a grid, but differently for
each row, you can nest multiple HBox layout components inside a VBox component.
Charts
JavaFX comes with a set of built-in ready-to-use chart components, so you don't have to code charts from scratch
everytime you need a basic chart. JavaFX contains the following chart components:
Page 24 of 30
AreaChart LineChart StackedAreaChart
BarChart PieChart StackedBarChart
BubbleChart ScatterChart
Audio
JavaFX contains features that makes it easy to play audio in JavaFX applications. This is typically useful in games
or educational applications.
Video
JavaFX contains features that makes it easy to play video in JavaFX applications. This is typically useful in
streaming applications, games or educational applications.
WebView
JavaFX contains a WebView component which is capable of showing web pages (HTML5, CSS etc.). The JavaFX
WebView component is based on WebKit - the web page rendering engine also used in Chrome and Safari.
EXCERCISE:
1. Write a program that displays an image in a label, a title in a label, and text in the text area as follows:
2. Write a JavaFX program to display the mouse position in the form of (x,y) co-ordinates, when the text present on
the screen is dragged somewhere else.
REVIEW QUESTIONS:
1. What methods do you use to register a handler for a mouse pressed, released, clicked, entered, exited, movedand
dragged event?
2. What is an event source object? What is an event object? Describe the relationship between an event sourceobject and
an event object
EVALUATION:
Understanding /
Involvement
Problem solving Timely Completion Total
(3) (10)
(4)
(3)
Binary I/O
The legacy API (classes in the java.io.* package) is perfect for manipulating low-level binary I/O operations such
as reading and writing exactly one byte at a time, whereas the NIO API (classes in the java.nio.* package) is
more convenient for reading and writing the whole file at once, and of course, faster than the old File I/O API.
The java.io package contains nearly every class you might ever need to perform input and output (I/O) in Java.
All these streams represent an input source and an output destination. The stream in the java.io package supports
many data such as primitives, object, localized characters, etc.
Stream
A stream can be defined as a sequence of data. There are two kinds of Streams − InputStream
− The InputStream is used to read data from a source.
OutputStream − The OutputStream is used for writing data to a destination.
Byte Streams
Java byte streams are used to perform input and output of 8-bit bytes. Though there are many classes related to byte
streams but the most frequently used classes are, FileInputStream and FileOutputStream.
Character Streams
Java Byte streams are used to perform input and output of 8-bit bytes, whereas Java Character streams are used to
perform input and output for 16-bit unicode. Though there are many classes related to character streams but the
most frequently used classes are, FileReader and FileWriter. Though internally FileReader uses FileInputStream
and FileWriter uses FileOutputStream but here the major difference is that FileReader reads two bytes at a time
and FileWriter writes two bytes at a time.
Standard Streams
All the programming languages provide support for standard I/O where the user's program can take input from a
keyboard and then produce an output on the computer screen. If you are aware of C or C++ programming
languages, then you must be aware of three standard devices STDIN, STDOUT and STDERR. Similarly, Java
provides the following three standard streams −
• Standard Input − This is used to feed the data to user's program and usually a keyboard is used as standard
input stream and represented as System.in.
• Standard Output − This is used to output the data produced by the user's program and usually a computer
screen is used for standard output stream and represented as System.out.
Page 26 of 30
• Standard Error − This is used to output the error data produced by the user's program and usually a computer
screen is used for standard error stream and represented as System.err.
FileInputStream
This stream is used for reading data from the files. Objects can be created using the keyword new and there are
several types of constructors available.
Following constructor takes a file name as a string to create an input stream object to read the file − InputStream f
= new FileInputStream("C:/java/hello");
Following constructor takes a file object to create an input stream object to read the file. First we create a file
object using File() method as follows − File f = new File("C:/java/hello");
InputStream f = new FileInputStream(f);
FileOutputStream
FileOutputStream is used to create a file and write data into it. The stream would create a file, if it doesn't already
exist, before opening it for output.
Here are two constructors which can be used to create a FileOutputStream object.
Following constructor takes a file name as a string to create an input stream object to write the file − OutputStream
f = new FileOutputStream("C:/java/hello")
Page 27 of 30
Following constructor takes a file object to create an output stream object to write the file. First, we create a
file object using File() method as follows − File f = new File("C:/java/hello");
OutputStream f = new FileOutputStream(f);
Recursion in Java
Recursion is the process in which a function calls itself directly or indirectly is called recursion and the
corresponding function is called as recursive function. Using recursive algorithm, certain problems can be solved
quite easily.
Examples of such problems are Towers of Hanoi (TOH), Inorder/Preorder/Postorder Tree Traversals, DFS of
Graph, etc.
If the base case is not reached or not defined, then the stack overflow problem may arise.
What is the difference between direct and indirect recursion?
A function fun is called direct recursive if it calls the same function fun. A function fun is called indirect recursive
if it calls another function say fun_new and fun_new calls fun directly or indirectly. Difference between direct and
indirect recursion has been illustrated in Table 1.
• Direct recursion: void directRecFun()
{
// Some code....
directRecFun();
// Some code...
}
• Indirect recursion: void indirectRecFun1()
{
// Some code...
Page 28 of 30
indirectRecFun2();
// Some code...
}
void indirectRecFun2()
{
// Some code...
indirectRecFun1();
// Some code...
}
Generics in Java
Generics in Java is similar to templates in C++. The idea is to allow type (Integer, String, … etc. and user defined
types) to be a parameter to methods, classes and interfaces. For example, classes like HashSet, ArrayList,
HashMap, etc. use generics very well. We can use them for any type.
Generic Class
Like C++, we use <> to specify parameter types in generic class creation. To create objects of generic class, we use
following syntax.
// To create an instance of generic class
Page 29 of 30
BaseType <Type> obj = new BaseType <Type>()
Note: In Parameter type we can not use primitives like
'int','char' or 'double'.
Generic Functions:
We can also write generic functions that can be called with different types of arguments based on the type of
arguments passed to generic method, the compiler handles each method.
Advantages of Generics:
Programs that uses Generics has got many benefits over non-generic code.
1. Code Reuse: We can write a method/class/interface once and use for any type we want.
2. Type Safety : Generics make errors to appear compile time than at run time (It’s always better to know
problems in your code at compile time rather than making your code fail at run time). Suppose you want to
create an ArrayList that store name of students and if by mistake programmer adds an integer object instead
of string, compiler allows it. But, when we retrieve this data from ArrayList, it causes problems at runtime.
3. Individual Type Casting is not needed: If we do not use generics, then, in the above example every-time we
retrieve data from ArrayList, we have to typecast it. Typecasting at every retrieval operation is a big headache.
If we already know that our list only holds string data then we need not to typecast it every time.
4. Implementing generic algorithms: By using generics, we can implement algorithms that work on different
types of objects and at the same they are type safe too.
EXCERCISE:
1. Write a program to count the total number of chars, words, lines, alphabets, digits, white spaces in given file.
2. Write the program for factorial using the concept of recursion.
3. Write a program to implement Tower of Hanoi through recursion
4. Implement sorting of an array of comparable object using Generic Method.
REVIEW QUESTIONS:
1. How to define Generic class and interface explain with example.
2. Explain usage of class FileInputStream and FileOutputStream by giving an example.
EVALUATION:
Understanding /
Involvement
Problem solving Timely Completion Total
(3) (10)
(4)
(3)
Page 30 of 30