OOP With Java, Lab Manual, 2nd Yr
OOP With Java, Lab Manual, 2nd Yr
5 KM Stone Delhi, Meerut Road, Near Raj Nagar Extension Road, Ghaziabad, UP-201017 Approved by AICTE
th
New Delhi & Affiliated to Dr. A. P. J. Abdul Kalam Technical University, Lucknow
NBA Accredited Program ( B.Tech-ECE,IT) & B.Pharma
LABORATORY MANUAL
PEO 2: Employable: To develop the ability among students to synthesize data and technical
concepts for application to software product design for successful careers that meet the needs
students which they can use at different levels according to their experience and contribute for
OOP with Java(BCS 452), Lab Manual (CS, IV SEM) Page No. 1
Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering
PO2: Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences.
PO5: Modern tool usage: Create, select, and apply appropriate techniques, resources, a n d
modern engineering and IT tools including prediction and modelling to complex engineering
activities with an understanding of the limitations.
PO6: The engineer and society: Apply reasoning informed by the contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent responsibilities
relevant to the professional engineering practice.
PO8: Ethics: Apply ethical principles and commit to professional ethics and responsibilities
and norms of the engineering practice.
PO9: Individual and team work: Function effectively as an individual, and as a member or
leader in diverse teams, and in multidisciplinary settings.
OOP with Java(BCS 452), Lab Manual (CS, IV SEM) Page No. 2
Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering
the engineering community and with society at large, such as, being able to comprehend and
write effective reports and design documentation, make effective presentations, and give and
receive clear instructions.
PO12: Life-long learning: Recognize the need for, and have the preparation and
ability to engage in independent and life-long learning in the broadest context of technological
change.
PSO2: The ability to employ latest computer languages and platforms in creating innovative
career opportunities.
OOP with Java(BCS 452), Lab Manual (CS, IV SEM) Page No. 3
Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering
B217.4 Create JAVA package and construct programming using I/O package.
CO-PO MAPPING
PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12
B217.1 2 2 3 3 2 2 2
B217.2 2 2 3 3 2 2 2
B217.3 2 2 3 3 2 2 2
B217.4 2 2 3 3 2 2 2
B217.5 2 2 3 3 2 2 2
B217 2 2 3 3 2 2 2
CO-PSO MAPPING
PSO1 PSO2
B217.1 2 2
B217.2 2 2
B217.3 2 2
B217.4 2 2
B217.5 2 2
B217 2 2
OOP with Java(BCS 452), Lab Manual (CS, IV SEM) Page No. 4
Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering
LIST OF EXPERIMENTS
B217.1
the given number of type float into integer data type.
2. Write a Java program that prompts the user for a character, converts it to
B217.1
its ASCII value, and displays the result.
Gopal is developing a Java program that requires reading a person's
3.
first name, middle name, and last name as command-line arguments.
The program needs to concatenate these names with space and print
the full name in a single line. B217.1
Can you provide the Java code that Gopal can use to achieve this task?
You are developing a program to determine the month of the year based
5.
on the given month number. The months are represented by numbers from
1 to 12, where 1 corresponds to January, 2 to February, and so on. Create
a Java program using a switch-case statement that takes the month number
as input and prints the corresponding month of the year.
Attributes: B217.2
title: Represents the title of the book.
publicationyear: Represents the year the book was published.
Methods:
getTitle(): Returns the title of the book.
getPublicationYear(): Returns the publication year of the book.
setTitle(String title): Sets the title of the book.
OOP with Java(BCS 452), Lab Manual (CS, IV SEM) Page No. 5
Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering
Create a class named Citizen that inherits from Person and has the
following characteristics:
• An int variable age. B217.2
• A method inputAge() that takes user input for the age.
• A method displayAge() that prints the age to the console.
Note: The main class has been provided to you in the editor.
The MainPerson class creates an instance of Citizen, takes user input
for name and age, and then displays the entered name and age. The
program demonstrates the use of inheritance, where the Citizen class
inherits attributes and methods from the Person class.
Create an abstract class called Shape
8.
• Declare an abstract method of type double: calculateArea(). This
method will be implemented by subclasses.
• Implement a concrete method named displayDetails() that
displays information about the shape, including its area.
Next, create two subclasses called Rectangle and Circle that extend the
Shape class:
• Implement the calculateArea() method in the Rectangle class. It B217.2
should take input from the user for the length (double) and width
(double) of the rectangle and calculate its area.
• Implement the calculateArea() method in the Circle class. It
should take input from the user for the radius (double) of the circle
and calculate its area.
Note: The main method and the input statements are already provided.
Neha is developing a Java program that involves accessing elements in an
9. array. She wants to make sure that her program handles cases where the
index provided by the user is outside the valid range of the array. Can you
guide Neha in designing the program and implementing error handling for
array index out of bounds?
Input Format:
The first line is the integer that represents the size of the array. B217.3
The second line is the integers separated by space.
The third line is the integer that represents the index at which the user
wants to access the array element.
Output Format:
The output depends on the validity of the index. If the index is out of
OOP with Java(BCS 452), Lab Manual (CS, IV SEM) Page No. 6
Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering
Input Format:
The input consists of a single integer representing the number for which
the square root is to be calculated.
Constraint:
• 0≤n≤10
Input Format:
• The input consists of the number of characters to print (Integer).
Output format:
• The output represents characters alternating between alphabets
('A' to 'Z'), numbers (1 to n) and prints the name of the thread
followed by the character or number being printed.
B217.3
Sample Input and Output:
Enter the number of characters to print:
5
Thread-0: A
Thread-1: 1
Thread-0: B
Thread-1: 2
Thread-0: C
Thread-1: 3
Thread-0: D
Thread-1: 4
Thread-0: E
Thread-1: 5
Note: Output should strictly match with the test cases.
Develop a Java application to implement currency converter (Dollar to
12. INR, EURO to INR, Yen to INR and vice versa), distance converter (meter B217.4
to KM, miles to KM and vice versa), time converter (hours to minutes,
OOP with Java(BCS 452), Lab Manual (CS, IV SEM) Page No. 7
Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering
Note:
1. Create a package for each converter (currency, distance, and time).
2. Implement classes for each converter inside their respective
packages.
3. Use the main class to provide a user interface for selecting the type
of conversion and calling the appropriate converter class.
4. Your output should match the test cases as displayed.
Your task is to create a Java program that helps Rathika determine whether
her abstract file is eligible for submission. The program should read the
content of the abstract from a text file, count the total number of characters
(including spaces), and then provide feedback to Rathika about the
eligibility of her abstract and at the end print the total character count.
Ensure that your program handles situations where the file does not exist B217.4
or if there are any issues with file reading.
Input format:
The input is the file name.
Output format:
The output displays whether the abstract is eligible or not and prints the
total character count. If the file doesn't exist it prints the error message
as File does not exist.
Michael wants to reverse the order of lines in a text file. He needs a Java
15.
program that reads the content of the file and reverses the order of lines. B217.4
Implement the program to assist Michael in achieving this. If the file
OOP with Java(BCS 452), Lab Manual (CS, IV SEM) Page No. 8
Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering
does not exist print the error message saying "Error: Unable to read the
file".
Input Format:
The input consists of a single line containing the name of the input file.
Output Format:
The program should print the contents of the file with the lines reversed.
OOP with Java(BCS 452), Lab Manual (CS, IV SEM) Page No. 9
Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering
INTRODUCTION
The latest Java version contains important enhancements to improve performance, stability and
security of the Java applications that run on your machine. Installing this free update will ensure
that your Java applications continue to run safely and efficiently. The Java Runtime
Environment (JRE) is what you get when you download Java software. The JRE consists of the
Java Virtual Machine (JVM), Java platform core classes, and supporting Java platform libraries.
The JRE is the runtime portion of Java software, which is all you need to run it in your Web
browser. The Java Plug-in software is a component of the Java Runtime Environment (JRE).
The JRE allows applets written in the Java programming language to run inside various
browsers. The Java Plug-in software is not a standalone program and cannot be installed
separately.
The Java Virtual Machine is only one aspect of Java software that is involved in web interaction.
The Java Virtual Machine is built right into your Java software download, and helps run Java
applications. In the Java programming language, all source code is first written in plain text
files ending with the .java extension. Those source files are then compiled into .class files by
the javac compiler. A .class file does not contain code that is native to your processor; it instead
contains bytecodes — the machine language of the Java Virtual Machine (Java VM). The java
launcher tool then runs your application with an instance of the Java Virtual Machine.
OOP with Java(BCS 452), Lab Manual (CS, IV SEM) Page No. 10
Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering
Because the Java VM is available on many different operating systems, the same .class files are
capable of running on Microsoft Windows, the Solaris™ Operating System (Solaris OS),
Linux, or Mac OS. Some virtual machines, such as the Java SE HotSpot at a Glance, perform
additional steps at runtime to give your application a performance boost. This includes various
tasks such as finding performance bottlenecks and recompiling (to native code) frequently used
sections of code.
The Java Platform A platform is the hardware or software environment in which a program
runs. We've already mentioned some of the most popular platforms like Microsoft Windows,
Linux, Solaris OS, and Mac OS. Most platforms can be described as a combination of the
operating system and underlying hardware. The Java platform differs from most other
platforms in that it's a software-only platform that runs on top of other hardware-based
platforms. The Java platform has two components:
OOP with Java(BCS 452), Lab Manual (CS, IV SEM) Page No. 11
Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering
Java Virtual Machine; it's the base for the Java platform and is ported onto various hardware-
based platforms. The API is a large collection of ready-made software components that provide
many useful capabilities. It is grouped into libraries of related classes and interfaces; these
libraries are known as packages.web technology while trying not to let the media confetti
overwhelm good sense and an information- oriented aesthetic. Thanks to enormous advances
in html, Cascading Style Sheets, and the “web standards” philosophy for building sites, this
edition does not contain sections on cross-platform issues or special techniques for making web
sites accessible to people with disabilities.
As a platform-independent environment, the Java platform can be a bit slower than native code.
However, advances in compiler and virtual machine technologies are bringing performance
close to that of native code without threatening portability.
OOP with Java(BCS 452), Lab Manual (CS, IV SEM) Page No. 12
Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering
1. Object Oriented − In Java, everything is an Object. Java can be easily extended since it is
based on the Object model.
2. Platform Independent − Unlike many other programming languages including C and
C++, when Java is compiled, it is not compiled into platform specific machine, rather into
platform independent byte code. This byte code is distributed over the web and interpreted
by the Virtual Machine (JVM) on whichever platform it is being run on.
3. Simple − Java is designed to be easy to learn. If you understand the basic concept of OOP
Java, it would be easy to master.
4. Secure − With Java's secure feature it enables to develop virus-free, tamper-free systems.
Authentication techniques are based on public-key encryption.
5. Architecture-neutral − Java compiler generates an architecture-neutral object file format,
which makes the compiled code executable on many processors, with the presence of Java
runtime system.
6. Portable − Being architecture-neutral and having no implementation dependent aspects of
the specification makes Java portable. Compiler in Java is written in ANSI C with a clean
portability boundary, which is a POSIX subset.
7. Robust − Java makes an effort to eliminate error prone situations by emphasizing mainly
on compile time error checking and runtime checking.
OOP with Java(BCS 452), Lab Manual (CS, IV SEM) Page No. 13
Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering
DONT’S
OOP with Java(BCS 452), Lab Manual (CS, IV SEM) Page No. 14
Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering
1. Know the location of the fire extinguisher and the first aid box and how to use them in case
of an emergency.
technician immediately.
4. Do not plug in external devices without scanning them for computer viruses.
OOP with Java(BCS 452), Lab Manual (CS, IV SEM) Page No. 15
Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering
OOP with Java(BCS 452), Lab Manual (CS, IV SEM) Page No. 16
Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering
Name
Roll No.
Section- Batch
OOP with Java(BCS 452), Lab Manual (CS, IV SEM) Page No. 17
Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering
INDEX
Experiment Date of Date of Faculty
Experiment Name
No. Conduction Submission Signature
OOP with Java(BCS 452), Lab Manual (CS, IV SEM) Page No. 18
Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering
In each lab class, students will be awarded marks out of 5 under each component head,
making it total out of 15 marks.
---------------------------
OOP with Java(BCS 452), Lab Manual (CS, IV SEM) Page No. 19
Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering
EXPERIMENT NO. 1
Aim: Write a Java program that prompts the user for a character, converts it to its ASCII
value, and displays the result.
Input format: The input is the character (alphabet/ digit/ special character).
Output format:The output is the integer that represents the ASCII value.
Note: The code for handling inputs is already been given, your task is to fill in the
required code.
Source Code:
import java.util.Scanner;
public class CharCodeQuest {public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
char magicalChar = scanner.next().charAt(0);
// write your code here..
int c=(int)magicalChar;
System.out.println(c);
}
}
Test Case - 1
User Output
A
65
Test Case - 2
User Output
@
64
OOP with Java(BCS 452), Lab Manual (CS, IV SEM) Page No. 20
Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering
OOP with Java(BCS 452), Lab Manual (CS, IV SEM) Page No. 21
Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering
EXPERIMENT NO. 2
Aim: Write a Java program that prompts the user for a float value and convert the given
number of type float into integer data type.
Output format: The output is the integer after the data type conversion.
Note: The code for handling inputs is already been given, your task is to fill in the
required code.
Source Code :
import java.util.Scanner; public class FloatToInt {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
float floatValue = scanner.nextFloat();
// write your code here..
int c=(int)floatValue;
System.out.println(c);
}
}
2. Discuss the difference between primitive data types and reference data
types.
3. How do you determine the data type of a variable in Java?
Execution Results - All test cases have succeeded!
Test Case - 1
User Output
2.45
2
Test Case - 2
User Output
145.278
145
OOP with Java(BCS 452), Lab Manual (CS, IV SEM) Page No. 22
Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering
OOP with Java(BCS 452), Lab Manual (CS, IV SEM) Page No. 23
Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering
EXPERIMENT NO. 3
Aim: Gopal is developing a Java program that requires reading a person's first name,
middle name, and last name as command-line arguments. The program needs to
concatenate these names with space and print the full name in a single line.
Can you provide the Java code that Gopal can use to achieve this task?
Source Code :
public class FullNameConcatenation{
public static void main(String[] args){
}
Pre lab Questions B217.1
• What are access specifiers in Java, and why are they important?
• List and explain the different access specifiers in Java.
• When would you use each access specifier?
• How do you call a method from within another method in the same class?
Execution Results - All test cases have succeeded!
Test Case - 1
User Output
Mahendra Singh Dhoni
Test Case - 2
User Output
Sachin Ramesh Tendulkar
OOP with Java(BCS 452), Lab Manual (CS, IV SEM) Page No. 24
Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering
EXPERIMENT NO. 4
Aim: Teja is very enthusiastic about writing programs, One day he thought of printing the
4 command line arguments in reverse order.
Source Code:
import java.util.*;
public class ReveresedArguments{
public static void main(String[] args){
//String a1=args[3];
//String a2=args[2];
//String a3=args[1];
//String a4=args[0];
//String a5=a1+a2+a3+a4;
//System.out.println(a5);
System.out.println(args[3]+args[2]+args[1]+args[0]);
}
}
Test Case - 1
User Output
4321
Test Case - 2
User Output
CodeTantraTechSolutionsLimited
OOP with Java(BCS 452), Lab Manual (CS, IV SEM) Page No. 25
Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering
OOP with Java(BCS 452), Lab Manual (CS, IV SEM) Page No. 26
Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering
EXPERIMENT NO. 5
Aim: You are developing a Library Book Management System, and a crucial aspect is
the Book class. This class is intended to represent individual books within the system.
The Book class should have attributes title and publication year, and you need to
implement methods to get and set these attributes. Consider the following scenario:
Attributes:
title: Represents the title of the book.
publicationyear: Represents the year the book was published.
Methods:
getTitle(): Returns the title of the book.
getPublicationYear(): Returns the publication year of the book.
setTitle(String title): Sets the title of the book.
setPublicationYear(int publicationYear): Sets the publication year of the book.
OOP with Java(BCS 452), Lab Manual (CS, IV SEM) Page No. 27
Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering
int getPublicationYear(){
return bookpublicationYear;
}
public static void main(String[] args){
Book libraryBook =new Book();
Scanner scanner= new
Scanner(System.in);System.out.print("Title of
the book: ");
String userEnteredTitle = scanner.nextLine();
libraryBook.setTitle(userEnteredTitle);
// Display details
System.out.println("Details of the Library Book:");
System.out.println("Title: " + libraryBook.getTitle());
System.out.println("Publication Year: " +
libraryBook.getPublicationYear());scanner.close();
}
}
Test Case - 1
User Output
Title of the book:
The Catcher in the Rye
Publication year of the book:
1951
Details of the Library Book:
Title: The Catcher in the Rye
Publication Year: 1951
OOP with Java(BCS 452), Lab Manual (CS, IV SEM) Page No. 28
Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering
Test Case - 2
User Output
Title of the book:
To Kill a Mockingbird
Publication year of the book:
1960
Details of the Library Book:
Title: To Kill a Mockingbird
Publication Year: 1960
OOP with Java(BCS 452), Lab Manual (CS, IV SEM) Page No. 29
Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering
EXPERIMENT NO. 6
Aim: You are developing a program to determine the month of the year based on the
given month number. The months are represented by numbers from 1 to 12, where 1
corresponds to January, 2 to February, and so on. Create a Java program using a switch-
case statement that takes the month number as input and prints the corresponding month
of the year.
Write a Java program to take the month number as input and print the corresponding
month of the year.
Input format:
The program should take an integer representing the month number (1 - 12).
Output format:
Print the corresponding month of the year based on the month number.
OOP with Java(BCS 452), Lab Manual (CS, IV SEM) Page No. 30
Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering
Source Code:
import java.util.Scanner;
public class MonthIdentifier {
switch (choice ) {
case 1:
System.out.println("January");
break;
case 2:
System.out.println("February");
break;
case 3:
System.out.println("March");
break;
case 4:
System.out.println("April");
break;
case 5:
System.out.println("May");
break;
case 6:
System.out.println("June");
break;
case 7:
System.out.println("July");
break;
case 8:
System.out.println("August");
break;
case 9:
System.out.println("September");
break;
case 10:
System.out.println("October");
OOP with Java(BCS 452), Lab Manual (CS, IV SEM) Page No. 31
Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering
break;
case 11:
System.out.println("November");
break;
case 12:
System.out.println("December");
break;
default:
System.out.println("");
}
}
}
Test Case - 1
User Output
1
January
Test Case - 2
User Output
12
December
Test Case - 3
User Output
5
May
OOP with Java(BCS 452), Lab Manual (CS, IV SEM) Page No. 32
Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering
EXPERIMENT NO. 7
Create a class named Citizen that inherits from Person and has the following
characteristics:
• An int variable age.
• A method inputAge() that takes user input for the age.
Note: The main class has been provided to you in the editor. The MainPerson class
creates an instance of
Citizen, takes user input for name and age, and then displays the entered name and age.
The program demonstrates the use of inheritance, where the Citizen class inherits
attributes and methods from the Person class.
Source Code:
import java.util.Scanner;
class Person{
String name;
Scanner input =new
Scanner(System.in);void inputName(){
System.out.print("Enter name: ");
name=input.nextLine();
}
void displayName(){
System.out.println("Name: "+name); } }
class Citizen extends Person{int age;
OOP with Java(BCS 452), Lab Manual (CS, IV SEM) Page No. 33
Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering
void inputAge(){
System.out.print("Enter age: ");
age=input.nextInt();
}
void displayAge(){
System.out.println("Age: "+age);
}
}
public class MainPerson {
public static void main(String[] args) {
Citizen citizen = new Citizen();
citizen.inputName();
citizen.displayName();
citizen.inputAge();
citizen.displayAge();
}
}
Test Case - 1
User Output
Enter name:
John doe
Name: John doe
Enter age:
23
Age: 23
Test Case - 2
User Output
Enter name:
Shreya
Name: Shreya
Enter age:
38
Age: 38
OOP with Java(BCS 452), Lab Manual (CS, IV SEM) Page No. 34
Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering
OOP with Java(BCS 452), Lab Manual (CS, IV SEM) Page No. 35
Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering
EXPERIMENT NO. 8
Note: The main method and the input statements are already provided
OOP with Java(BCS 452), Lab Manual (CS, IV SEM) Page No. 36
Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering
OOP with Java(BCS 452), Lab Manual (CS, IV SEM) Page No. 37
Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering
");radius = scanner.nextDouble();
}
}
Test Case - 1
User Output
Enter the length of the rectangle:
3
Enter the width of the rectangle:
4
Shape details:
Area: 12.0
Enter the radius of the circle:
3
Shape details:
Area: 28.274333882308138
OOP with Java(BCS 452), Lab Manual (CS, IV SEM) Page No. 38
Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering
EXPERIMENT NO. 9
Aim:
Neha is developing a Java program that involves accessing elements in an array. She
wants to make sure that her program handles cases where the index provided by the
user is outside the valid range of the array. Can you guide Neha in designing the
program and implementing error handling for array index out of bounds?
Input Format:
The first line is the integer that represents the size of the array. The second line is the
integers separated by space.
The third line is the integer that represents the index at which the user wants to access
the array element.
Output Format:
The output depends on the validity of the index. If the index is out of bounds, the
program should display "Error: Index out of bounds".
Source Code:
package q28186;
import java.util.Scanner;
OOP with Java(BCS 452), Lab Manual (CS, IV SEM) Page No. 39
Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering
int index=scanner.nextInt();try
{
int element=arr[index];
System.out.println("Element at index " + index + " is: " + element );
} catch ( ArrayIndexOutOfBoundsException e ) {
System.out.println("Error: Index out of bounds");
}
}
}
Test Case - 1
User Output
5
78956
2
Element at index 2 is: 9
Test Case - 2
User Output
6
1 4 5 22 6 2
8
Error: Index out of bounds
OOP with Java(BCS 452), Lab Manual (CS, IV SEM) Page No. 40
Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering
EXPERIMENT NO. 10
Aim:
Rohan is developing a Java program to calculate the square root of a given number. He
wants to ensure that the program gracefully handles cases where the input number is
negative and the number cannot be parsed as an integer. Assist Rohan in designing the
program and implementing the necessary exception handling to achieve this.
Input Format:
The input consists of a single integer representing the number for which the square root
is to be calculated.
Output Format:
The output is a double value(up to 2 decimal points) representing the square root of the
input number.
If the input number is negative, the program should display "Error: Square root of a
negative number is not possible".
Also, if the input number cannot be parsed as an integer, the program should display
"Error: Invalid input".
OOP with Java(BCS 452), Lab Manual (CS, IV SEM) Page No. 41
Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering
squareRoot=Math.sqrt(number);
System.out.printf("%.2f\n",squareRoot);
catch ( NumberFormatException e ) {
System.out.println("Error: Invalid input");
}
catch (IllegalArgumentException e ){
}
}
Test Case - 1
User Output
8
2.83
Test Case - 2
User Output
90L
Error: Invalid input
Test Case - 3
User Output
-9
Error: Square root of a negative number is not possible
OOP with Java(BCS 452), Lab Manual (CS, IV SEM) Page No. 42
Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering
OOP with Java(BCS 452), Lab Manual (CS, IV SEM) Page No. 43
Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering
EXPERIMENT NO. 11
Aim:
Write a Java program to print alternating alphabets and numbers based on user-
defined counts n, ensuring termination after reaching the specified count, and
handling inputs greater than zero.
Constraint:
• 0 ≤ n ≤ 10
Input Format:
• The input consists of the number of characters to print (Integer).
Output format:
• The output represents characters alternating between alphabets ('A' to 'Z'),
numbers (1 to n) and prints the name of the thread followed by the character or
number being printed.
Thread-0: A
Thread-1: 1
Thread-0: B
Thread-1: 2
Thread-0: C
Thread-1: 3
Thread-0: D
Thread-1: 4
Thread-0: E
Thread-1: 5
Note: Output should strictly match with the test cases.
OOP with Java(BCS 452), Lab Manual (CS, IV SEM) Page No. 44
Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering
Source Code:
package q19685;
import java.util.Scanner;
class AlphabetNumberPrinter extends Thread {
private static final Object monitor = new
Object();private static int currentNumber=1;
private static char currentAlphabet= 'A';
private int count;
private boolean isAlphabetThread;
}
else{
System.out.println(Thread.currentThread().getNa
me()+
": "+currentNumber++);
}
monitor.notify();//notify waiting
threadtry{
if(i < count -1){
OOP with Java(BCS 452), Lab Manual (CS, IV SEM) Page No. 45
Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering
monitor.wait();//release monitor and wait
}
}
catch(InterruptedException
e){e.printStackTrace();
}
}
}
}
}
public class PrintAlphabets{
public static void main(String[]
args){int count;
Scanner scanner = new
Scanner(System.in);do{
System.out.println("Enter the number of characters to
print:");count =scanner.nextInt();
if(count < 1){
System.out.println("Please enter a number greater than
0.");
}
}while(count<1);
//Creating and starting Threads
AlphabetNumberPrinter
alphabetThread = new
AlphabetNumberPrinter(count,true);
numberThread.setName("Thread
-1");alphabetThread.start();
numberThread.start();
}
}
1. What are default methods in interfaces, and why were they introduced in Java
8?
2. Discuss the advantages and potential pitfalls of default methods.
OOP with Java(BCS 452), Lab Manual (CS, IV SEM) Page No. 46
Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering
3. Provide examples of interfaces with default methods.
Test Case - 1
User Output
Enter the number of characters to print:
5
Thread-0: A
Thread-1: 1
Thread-0: B
Thread-1: 2
Thread-0: C
Thread-1: 3
Thread-0: D
Thread-1: 4
Thread-0: E
Thread-1: 5
Test Case - 2
User Output
Enter the number of characters to print:
2
Thread-0: A
Thread-0: B
Test Case – 3
User Output
Enter the number of characters to print:
0
Please enter a number greater than 0.
Enter the number of characters to print:
3
Thread-0: A
Thread-1: 1
Thread-0: B
Thread-1: 2
OOP with Java(BCS 452), Lab Manual (CS, IV SEM) Page No. 47
Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering
Thread-0: C
Thread-1: 3
Thread-1: 2
OOP with Java(BCS 452), Lab Manual (CS, IV SEM) Page No. 48
Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering
EXPERIMENT NO. 12
Aim:
Develop a Java application to implement currency converter (Dollar to INR, EURO
to INR, Yen to INR and vice versa), distance converter (meter to KM, miles to KM
and vice versa), time converter (hours to minutes, seconds and vice versa) using
packages.
Note:
1. Create a package for each converter (currency, distance, and time).
2. Implement classes for each converter inside their respective packages.
3. Use the main class to provide a user interface for selecting the type of
conversion and calling the appropriate converter class.
4. Your output should match the test cases as displayed.
Assume the following values for currency converter 1 euro = 89.2 INR
1 yen = 0.67 INR
1 dollar = 74.5 INR
Source Code:
import java.util.Scanner;
import
currency.CurrencyConverter;
import distance.DistanceConverter;
import time.TimeConverter;
OOP with Java(BCS 452), Lab Manual (CS, IV SEM) Page No. 49
Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering
System.out.println("Yen: "+object1.INRtoYen(amount));
break;default:
System.out.println("Invalid choice");
}
}
OOP with Java(BCS 452), Lab Manual (CS, IV SEM) Page No. 50
Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering
OOP with Java(BCS 452), Lab Manual (CS, IV SEM) Page No. 51
Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering
package distance;
import java.math.BigDecimal;
public class DistanceConverter {
public double newDistance;
public BigDecimal MetertoKM(int distance){
BigDecimal numerator = new
BigDecimal(distance);BigDecimal
denominator = new BigDecimal(1000);
BigDecimal result = numerator.divide(denominator);
return result;
}
public double KMtoMeter(int
distance){newDistance=
distance * 1000; return
newDistance;
}
public double MilestoKM(int distance){
newDistance = distance *
1.60934 ;return newDistance;
}
public double KMtoMiles(int distance){
newDistance = distance /
1.60934;return newDistance;
}
}
package time;
public class TimeConverter{
public int newTime;
public int HourstoMinutes(int time){
newTime = time * 60 ;
return newTime;
}
public int MinutestoHours(int time
){newTime= time / 60;
return newTime;
}
public int HourstoSeconds(int
time){newTime = time *
3600;
return newTime;
OOP with Java(BCS 452), Lab Manual (CS, IV SEM) Page No. 52
Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering
}
public int SecondstoHours(int time){newTime = time / 3600 ;
return newTime;
}
Test Case - 1
User Output
Choose the conversion type:
1. Currency
2. Distance
3. Time
1
Choose the currency conversion:
1. Dollar to INR
2. Euro to INR
3. Yen to INR
4. INR to Dollar
5. INR to Euro
6. INR to Yen
1
Enter the amount in Dollar:
30
INR: 2235.0
Test Case - 2
User Output
Choose the conversion type:
1. Currency
2. Distance
3. Time
1
Choose the currency conversion:
1. Dollar to INR
2. Euro to INR
OOP with Java(BCS 452), Lab Manual (CS, IV SEM) Page No. 53
Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering
3. Yen to INR
4. INR to Dollar
5. INR to Euro
6. INR to Yen
20
Invalid choice
Test Case - 3
User Output
Choose the conversion type:
1. Currency
2. Distance
3. Time
2
Choose the distance conversion:
1. Meter to KM
2. KM to Meter
3. Miles to KM
4. KM to Miles
1
Enter the distance in meters:
100
Test Case - 4
KM: 0.1
User Output
Choose the conversion type:
1. Currency
2. Distance
3. Time
2
Choose the distance conversion:
1. Meter to KM
2. KM to Meter
3. Miles to KM
4. KM to Miles
2
Enter the distance in KM:
2
Meters: 2000.0
OOP with Java(BCS 452), Lab Manual (CS, IV SEM) Page No. 54
Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering
Test Case - 5
User Output
Choose the conversion type:
1. Currency
2. Distance
3. Time
2
Choose the distance conversion:
1. Meter to KM
2. KM to Meter
3. Miles to KM
4. KM to Miles
Enter the distance in KM:
65
Miles: 40.38922788223744
Test Case - 6
User Output
Choose the conversion type:
1. Currency
2. Distance
3. Time
3
Choose the time conversion:
1. Hours to Minutes
2. Minutes to Hours
3. Hours to Seconds
4. Seconds to Hours
1
Enter the time in hours:
2
Minutes: 120
OOP with Java(BCS 452), Lab Manual (CS, IV SEM) Page No. 55
Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering
Test Case - 7
User Output
Choose the conversion type:
1. Currency
2. Distance
3. Time
3
Choose the time conversion:
1. Hours to Minutes
2. Minutes to Hours
3. Hours to Seconds
4. Seconds to Hours
2
Enter the time in minutes:
45
Hours: 0
OOP with Java(BCS 452), Lab Manual (CS, IV SEM) Page No. 56
Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering
EXPERIMENT NO. 13
Aim:
Raj is tasked with developing a security authentication system in Java. To enhance user
security, Raj decided to implement a feature that checks if a user's password is a
palindrome. He chooses to use the StringBuilder class from the java.lang package for
efficient string manipulation.
Can you help Raj, design and implement a Java class PalindromeChecker that takes
a user's entered password, checks if it is a palindrome, and provides a secure and user-
friendly response?
Input Format:
The input line reads a string representing the password.
Output Format:
The output line prints a string <password> is a palindrome if it is a palindrome
otherwise it will print
<password> is not a palindrome.
1. What is local variable type inference, and when was it introduced in Java?
2. Discuss the var keyword and its usage for local variable type inference.
3. Provide examples demonstrating the use of local variable type inference.
Source Code:
package q22014;
import java.util.Scanner;class
PalindromeChecker{
public static void main(String[] args)throws
Exception{Scanner scanner = new
Scanner(System.in);
String input = scanner.nextLine();
String new_input=input.toLowerCase();
StringBuilder reversed = new StringBuilder(new_input).reverse();
boolean result = new_input.equals(reversed.toString());
if(result){
System.out.println(input+" is a palindrome");
}
OOP with Java(BCS 452), Lab Manual (CS, IV SEM) Page No. 57
Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering
else{
System.out.println(input+" is not a palindrome");
}
}
Test Case - 1
User Output
level
level is a palindrome
Test Case - 2
User Output
Java
Java is not a palindrome
Test Case - 3
User Output
Radar
Radar is a palindrome
1. What are records in Java, and why were they introduced in Java 14?
2. Describe the characteristics and benefits of using records.
3. Provide examples demonstrating the use of records.
OOP with Java(BCS 452), Lab Manual (CS, IV SEM) Page No. 58
Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering
EXPERIMENT NO. 14
Aim:
Rathika is preparing to submit her project abstract to the university. The university has
imposed a rule stating that the abstract file must not exceed 250 characters, including
spaces. Rathika has finalized her abstract but is uncertain whether it meets the
university's criteria.
Your task is to create a Java program that helps Rathika determine whether her abstract
file is eligible for submission. The program should read the content of the abstract from
a text file, count the total number of characters (including spaces), and then provide
feedback to Rathika about the eligibility of her abstract and at the end print the total
character count.
Ensure that your program handles situations where the file does not exist or if there are
any issues with file reading.
Input format:
The input is the file name.
Output format:
The output displays whether the abstract is eligible or not and prints the total character
count. If the file doesn't exist it prints the error message as File does not exist.
Source Code:
package q28244;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader; import java.io.IOException;import java.util.Scanner;
OOP with Java(BCS 452), Lab Manual (CS, IV SEM) Page No. 59
Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering
1. Describe the Collection interface and its role in the Collection Framework.
2. Discuss the key methods defined by the Collection interface.
file2.txt
Inverters are widely used in the domestic as well as industrial environments to serve
as second line of source in case of power cut form the electricity utility grids. Inverter
is the device that powers the electric appliances in the event of the power failure.
Inverter as the name implies first converts AC to DC for charging the battery and then
inverts DC to AC for powering the electric gadgets.
OOP with Java(BCS 452), Lab Manual (CS, IV SEM) Page No. 60
Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering
file1.txt
file3 .txt
This paper explores a relatively less popular source of clean energy. An application
is proposed for the same, in which a speaker and a transformer are used to convert
noise produced by car horn into electrical energyThis paper explores arelatively less
popular source of clean energy. An application is proposed for the same, in which a
speaker and a transformer are used to convert noise produced by car horn into
electrical energy .
file4.txt
OOP with Java(BCS 452), Lab Manual (CS, IV SEM) Page No. 61
Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering
Test Case - 1
User Output
file1.txt
Eligible
Character count: 218
Test Case - 2
User Output
file2.txt
Not eligible
Character count: 399
Test Case - 3
User Output
files.txt
File does not exist
OOP with Java(BCS 452), Lab Manual (CS, IV SEM) Page No. 62
Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering
EXPERIMENT NO. 15
Aim:
Michael wants to reverse the order of lines in a text file. He needs a Java program that
reads the content of the file and reverses the order of lines. Implement the program to
assist Michael in achieving this. If the file does not exist print the error message saying
"Error: Unable to read the file".
Input Format:
The input consists of a single line containing the name of the input file.
Output Format:
The program should print the contents of the file with the lines reversed.
Source Code:
package q28286;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
OOP with Java(BCS 452), Lab Manual (CS, IV SEM) Page No. 63
Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering
String[] fileText = new String[100];
int count =0;
while((line = fileInput.readLine()) != null){fileText[count]=line;
count++;
}
for(int i=count-1 ; i>= 0; i--){
System.out.println(fileText[i]);
}
fileInput.close();
}
catch(IOException e){
System.out.println("Error: Unable to read the file");
}
}
}
file4.txt
file1.txt
OOP with Java(BCS 452), Lab Manual (CS, IV SEM) Page No. 64
Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering
file2.txt
file3.txt
Test Case - 1
User Output
file1.txt
It contains some text.
This is the content of file 1.
Test Case - 2
User Output
file2.txt
File
Test
A
Is
This
World
Hello
OOP with Java(BCS 452), Lab Manual (CS, IV SEM) Page No. 65
Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering
Test Case - 3
User Output
files.txt
Error: Unable to read the file
OOP with Java(BCS 452), Lab Manual (CS, IV SEM) Page No. 66
Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering
REFERENCES
OOP with Java Lab (BCS 452) Manual (CS, IV SEM) Page No. 67
Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering
AKTU SYLLABUS
Object Oriented Programming with Java Lab (BCS452)
OOP with Java Lab (BCS 452) Manual (CS, IV SEM) Page No. 68