0% found this document useful (0 votes)
9 views

OOP With Java, Lab Manual, 2nd Yr

Uploaded by

priyanka singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

OOP With Java, Lab Manual, 2nd Yr

Uploaded by

priyanka singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 69

RAJ KUMAR GOEL INSTITUTE OF TECHNOLOGY

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

Faculty Name : Dr. Gaganjot Kaur Department : CSE

Course Name : OOP with Java Lab Course Code : BCS452

Year/Sem : 2nd Yr / 4th Semester NBA Code : B217


Email ID : [email protected] Academic Year : 2023-24

Department of Computer Science and Engineering


Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering

VISION OF THE INSTITUTE


To continually develop excellent professionals capable of providing sustainable solutions to
challenging problems in their fields and prove responsible global citizens.

MISSION OF THE INSTITUTE


We wish to serve the nation by becoming a reputed deemed university for providing value
based professional education.

VISION OF THE DEPARTMENT


To be recognized globally for delivering high quality education in the ever changing field of
computer science & engineering, both of value & relevance to the communities we serve.

MISSION OF THE DEPARTMENT


1. To provide quality education in both the theoretical and applied foundations of
Computer Science and train students to effectively apply this education to solve real
world problems.
2. To amplify their potential for lifelong high- q u a l i t y careers and give them a
competitive advantage in the challenging global work environment.
PROGRAM EDUCATIONAL OUTCOMES (PEOs)
PEO 1: Learning: Our graduates to be competent with sound knowledge in field of Computer

Science & Engineering.

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

of Indian and multinational companies.

PEO 3: Innovative: To develop research oriented analytical ability among students to

prepare them for making technical contribution to the society.

PEO 4: Entrepreneur / Contribution: To develop excellent leadership quality among

students which they can use at different levels according to their experience and contribute for

progress and development in the society.

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

PROGRAM OUTCOMES (POs)


Engineering Graduates will be able to:

PO1: Engineering knowledge: Apply the knowledge of mathematics, science, engineering


fundamentals, and an engineering specialization to the solution of complex engineering
problems.

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.

PO3: Design/development of solutions: Design solutions for complex engineering problems


and design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations.

PO4: Conduct investigations of complex problems: Use research-based knowledge and


research methods including design of experiments, analysis and interpretation of data, and
synthesis of the information to provide valid conclusions.

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.

PO7: Environment and sustainability: Understand the impact of the professional


engineering solutions in societal and environmental contexts, and demonstrate the knowledge
of, and need for sustainable development.

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.

PO10: Communication: Communicate effectively on complex engineering activities with

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.

PO11: Project management and finance: Demonstrate k n o w l e d g e and


understanding of the engineering and management principles and apply these to one’s
own work, as a member and leader in a team, to manage projects and in multidisciplinary
environments.

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.

PROGRAM SPECIFIC OUTCOMES (PSOs)


PSO1: The ability to use standard practices and suitable programming environment to
develop software solutions.

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

COURSE OUTCOMES (COs)

B217.1 Develop a simple JAVA program using Eclipse platform.

B217.2 Implement OOPs concepts using basics of JAVA Programming.

B217.3 Handle error in JAVA using Exception Handling.

B217.4 Create JAVA package and construct programming using I/O package.

B217.5 Create a front-end web application using Spring Boot.

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

Expt. Title of Experiment Corresponding


No. CO
1. Write a Java program that prompts the user for a float value and convert
1

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?

Teja is very enthusiastic about writing programs, one day he thought


4.
of printing the 4 command line arguments in reverse order.
What would be the program that works for Teja? B217.1

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.

Here is the mapping between month numbers and months: B217.1


1: January
2: February
3: March
4: April
5: May
You are developing a Library Book Management System, and a
6.
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: 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

setPublicationYear(int publicationYear): Sets the publication year of


the book.
Create a class named Person with the following characteristics:
7. • A String variable name.

• A method inputName() that takes user input for the name.


• A method displayName() that prints the name to the console.

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

bounds, the program should display "Error: Index out of bounds".

Rohan is developing a Java program to calculate the square root of a given


10. 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: B217.3


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".
Write a Java program to print alternating alphabets and numbers based on
11. 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.
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

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
Raj is tasked with developing a security authentication system in Java. To
13.
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?
B217.4
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.
Note: Use println() to print the output statements.
Rathika is preparing to submit her project abstract to the university. The
14. 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 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

Java is a high-level programming language originally developed by Sun Microsystems and


released in 1995. Java runs on a variety of platforms, such as Windows, Mac OS, and the various
versions of UNIX. James Gosling initiated the Java language project in June 1991 for use in
one of his many set-top box projects. The language, initially called Oak after an oak tree that
stood outside Gosling's office, also went by the name Green and ended up later being renamed
as Java, from a list of random words.

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:

• The Java Virtual Machine

• The Java Application Programming Interface (API)

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

KEY ADVANTAGES OF JAVA PROGRAMMING

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.

Dr. Gaganjot Kaur, Associate Professor, Dept. of CSE


Dr. Pramod Kumar Sagar, Associate Professor, Dept. of CSE
Mr. Mandeep Singh, Assistant Professor, Dept. of CSE
Mr. Prakash Joshi, Assistant Professor, Dept of CSE

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

DO’S AND DONT’S


DO’s

1. Conform to the academic discipline of the department.


2. Enter your credentials in the laboratory attendance register.
3. Read and understand how to carry out an activity thoroughly before coming to the
laboratory.
4. Ensure the uniqueness with respect to the methodology adopted for carrying out
the experiments.
5. Shut down the machine once you are done using it.

DONT’S

1. Eatables are not allowed in the laboratory.


2. Usage of mobile phones is strictly prohibited.
3. Do not open the system unit casing.
4. Do not remove anything from the computer laboratory without permission.
5. Do not touch, connect or disconnect any plug or cable without your
faculty/laboratory technician’s permission.

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

GENERAL SAFETY INSTRUCTIONS

1. Know the location of the fire extinguisher and the first aid box and how to use them in case

of an emergency.

2. Report fire or accidents to your faculty /laboratory technician immediately.

3. Report any broken plugs or exposed electrical wires to your faculty/laboratory

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

GUIDELINES FOR LABORTORY RECORD PREPARATION


While preparing the lab records, the student is required to adhere to the following guidelines:

Contents to be included in Lab Records:


1. Cover page
2. Vision
3. Mission
4. PEOs
5. POs
6. PSOs
7. COs
8. CO-PO-PSO mapping
9. Index
10. Experiments
➢ Aim
➢ Source code
➢ Input-Output

A separate copy needs to be maintained for pre-lab written work.


The student is required to make the Lab File as per the format given on the next two pages.

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

Raj Kumar Goel Institute of Technology, Ghaziabad

Object Oriented Programming Lab with JAVA (BCS 452)

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

GUIDELINES FOR ASSESSMENT


Students are provided with the details of the experiment (Aim, pre-experimental questions,
procedure etc.) to be conducted in next lab and are expected to come prepared for each lab
class.
Faculty ensures that students have completed the required pre-experiment questions and they
complete the in-lab programming assignment(s) before the end of class. Given that the lab
programs are meant to be formative in nature, students can ask faculty for help before and
during the lab class.
Students’ performance will be assessed in each lab based on the following Lab Assessment
Components:
Assessment Criteria-1: Performance (Max. marks = 5)

Assessment Criteria-2: VIVA (Max. marks = 5)

Assessment Criteria-3: Record (Max. marks = 5)

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);
}
}

Pre lab Questions B217.1

1. What is a class in Java, and why is it used?


2. How do you define a class in Java?
3. Explain the concept of encapsulation in the context of Java classes.
4. What is a constructor, and what is its purpose in Java?
Execution Results: All test cases have succeeded!

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

Post lab Questions B217.1

1. Differentiate between a default constructor and a parameterized constructor.


2. How can you overload constructors in Java?
3. Define a method in Java and explain its components.
4. Discuss the difference between instance methods and static methods.

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.

Input format: The input is the floating point value.

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);
}
}

Pre lab Questions B217.1


1. List and explain the primitive data types in Java.

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

Post lab Questions B217.1

1. Explain the concept of variables in Java.


2. Discuss the scope and lifetime of variables in Java.
3. What are instance variables, and how are they different from local
variables?

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?

Note: use println() to print the output.

Source Code :
public class FullNameConcatenation{
public static void main(String[] args){

String first = args[0];String middle=args[1]; String last=args[2];


String name=first+" "+middle+" "+last;System.out.println(name);

}
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

Post lab Questions B217.1


1. What is the significance of the static keyword in Java?
2. Explain static variables and static methods with examples.
3. Discuss the difference between static and instance members.

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.

What would be the program that works for Teja?

Note: Use println() to print output.

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]);
}
}

Pre lab Questions B217.1

1. What does the final keyword signify in Java?


2. How is a final variable different from a final method?
3. When would you use final members in your Java code?

Execution Results - All test cases have succeeded!

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

Post lab Questions B217.1

1. Explain the if-else statement and its purpose.


2. Discuss the switch statement and when it is preferable over if-else statements.
3. What is an array in Java, and how is it useful?
4. How do you declare and initialize arrays in Java?
5. Discuss the String class in Java and some common string manipulation methods.

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.

Pre lab Questions B217.2


• What is an exception in Java, and why is exception handling important in
programming?
• Explain the concept of exceptional situations and how they disrupt the normal
flow of a program.
• How does exception handling help in maintaining the robustness of a Java
program?
Source Code:
import java.util.Scanner;
public class Book {
// write your code here..
String bookTitle;
int bookpublicationYear;
void setTitle(String title){
bookTitle=title;
}
void setPublicationYear(int
publicationYear){
bookpublicationYear=publicationYear;
}
String getTitle(){
return bookTitle;
}

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);

System.out.print("Publication year of the book: ");


int userEnteredYear = scanner.nextInt();
libraryBook.setPublicationYear(userEnteredYear);

// 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();
}
}

Execution Results - All test cases have succeeded!

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

Post lab Questions B217.1


1. Differentiate between exceptions and errors in Java.
2. Provide examples of common exceptions and errors encountered in Java
programming.
3. Describe the categories of exceptions in Java.
4. Provide examples of checked and unchecked exceptions.
5. Discuss the significance of runtime exceptions and how they differ from checked
exceptions.

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.

Here is the mapping between month numbers and months:


1: January
2: February
3: March
4: April
5: May
6: June
7: July
8: August
9: September
10: October
11: November
12: December

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.

Pre lab Questions B217.1


1. Describe the different types of operators available in Java.
2. Provide examples of arithmetic, relational, logical, and assignment
operators.
3. Discuss the order of precedence of operators in Java.
4. What is control flow, and why is it important in programming?

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 {

public static void main(String[] args) {


Scanner input = new
Scanner(System.in);int choice =
input.nextInt();
// write your code here...

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("");

}
}
}

Execution Results - All test cases have succeeded!

Test Case - 1
User Output
1
January

Test Case - 2
User Output
12
December

Test Case - 3
User Output
5
May

Post lab Questions B217.1


1. Explain the if-else statement and its purpose.
2. Discuss the switch statement and when it is preferable over if-else statements.
3. What is an array in Java, and how is it useful?
4. How do you declare and initialize arrays in Java?

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

Aim: Create a class named Person with the following characteristics:


• A String variable name.

• A method inputName() that takes user input for the name.


• A method displayName() that prints the name to the console.

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.

• 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.

Pre lab Questions B217.2


1. Explain how exception handling affects the control flow of a Java program.
2. Discuss the propagation of exceptions through method calls.
3. Describe the mechanism of exception propagation in nested method calls.
4. What happens when an exception occurs during program execution?
5. Describe the default behavior of the JVM when an uncaught exception occurs.

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();
}
}

Execution Results - All test cases have succeeded!

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

Post lab Questions B217.2


1. How can you customize the handling of exceptions to prevent program
termination?
2. Explain the purpose of the try-catch-finally blocks in Java exception handling.
3. Describe the syntax and usage of the try, catch, and finally blocks.
4. Discuss the role of the throw and throws keywords in exception handling.

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

Aim: Create an abstract class called Shape


• 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 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

Pre lab Questions B217.2


1. Provide examples of built-in exceptions in Java.
2. Discuss the process of creating custom (user-defined) exceptions in Java.
3. Explain when it is appropriate to use built-in exceptions versus creating custom
exceptions.
4. Define checked and unchecked exceptions in Java.
5. Discuss the difference between checked and unchecked exceptions in terms of
handling requirements.
Source Code:
import java.util.Scanner;
abstract class Shape {

// write your code here


double length,radius,width,area;
double calculateArea(){
return area;
}
}
class Rectangle extends Shape {

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

// write your code here


void
displayDetails(){
double rectangleArea = calculateArea();
System.out.println("Shape details:");
System.out.println("Area: "+rectangleArea);
}
@Override
double calculateArea() {

// write your code here


area= length * width;
return area;
}

void inputDetails(Scanner scanner) {


System.out.print("Enter the length of the rectangle:
");length = scanner.nextDouble();
System.out.print("Enter the width of the rectangle:
");width = scanner.nextDouble();
}
}

class Circle extends Shape {


// write your code here
void displayDetails(){
double circleArea=calculateArea();
System.out.println("Shape details:");
System.out.println("Area: "+circleArea);
}
@Override
double calculateArea() {

// write your code here


area= Math.PI * radius * radius;
return area;
}

void inputDetails(Scanner scanner) {


System.out.print("Enter the radius of the circle:

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();
}
}

public class Main {


Rectangle rectangle = new
Rectangle();
rectangle.inputDetails(scanner);
rectangle.displayDetails();
Circle circle = new Circle();
circle.inputDetails(scanner);
circle.displayDetails();
scanner.close();
}
}

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

Post lab Questions B217.2


1. Provide examples of scenarios where you would use checked and
unchecked exceptions.
2. What is a thread in the context of Java programming?
3. Explain the difference between a process and a thread.
4. Discuss the advantages of using threads in Java applications.

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".

Pre lab Questions B217.2


1. Describe the different states in the life cycle of a thread in Java.
2. Explain the transition between each state in the thread life cycle.
3. Discuss the significance of each state in the execution of a Java program.

Source Code:
package q28186;
import java.util.Scanner;

public class ArrayIndexHandler {


public static void main(String[] args) {

// write the code...


//initialise and declare array
Scanner scanner = new
Scanner(System.in);int size=
scanner.nextInt();
int[] arr =new int[size];
for(int i=0;i<size;i++){
arr[i]=scanner.nextInt();
}

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");
}
}
}

Execution Results - All test cases have succeeded!

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

Post lab Questions B217.2


1. What are the different ways to create a thread in Java?
2. Discuss the advantages and disadvantages of extending the Thread class versus
implementing the Runnable interface.
3. Provide examples of creating threads using both approaches.

4. Explain the concept of thread priority in Java.


5. Discuss the range of thread priorities and their default values.

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".

Pre lab Questions B217.3


1. What is a functional interface in Java?
2. Why are functional interfaces important for lambda expressions?
3. Provide examples of built-in functional interfaces in Java.
4. Explain the concept of lambda expressions in Java.
Source Code:
package q28307;
import java.util.Scanner;
public class SquareRootCalculator {
public static void main(String[] args) {

// write the code..


double squareRoot;
Scanner scanner =new Scanner(System.in);
try {
String input=scanner.nextLine();
int number =Integer.parseInt(input);
if(number < 0){
throw new IllegalArgumentException();

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 ){

System.out.println("Error: Square root of a negative number is not


possible");
}

}
}

Execution Results - All test cases have succeeded!

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

Post lab Questions B217.3


1. How do lambda expressions improve code readability and conciseness?
2. Provide examples of using lambda expressions in Java.
3. What are method references, and how do they relate to lambda
expressions?
4. Describe the different types of method references in Java.
5. Provide examples demonstrating the use of method references.

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.

Sample Input and Output:

Enter the number of characters to print:

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

Pre lab Questions B217.3


1. What is the Stream API in Java, and what are its benefits?
2. Explain the difference between intermediate and terminal operations in
the Stream API.
3. Provide examples of common operations performed using the Stream
API.

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;

public AlphabetNumberPrinter(int count , boolean


isAlphabetThread){this.count = count;
this.isAlphabetThread = isAlphabetThread;
}
@Override
public void run(){
synchronized(monitor){
for(int i= 0; i< count ; i++){
if(isAlphabetThread){
System.out.println(Thread.currentThread().getNa
me()+
": "+currentAlphabet++);

}
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();
}
}

Post lab Questions B217.3

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.

Execution Results - All test cases have succeeded!

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

Pre lab Questions B217.3


1. Explain the concept of static methods in interfaces.
2. Describe when and why static methods are used in interfaces.
3. Provide examples demonstrating the use of static methods in interfaces.

Source Code:
import java.util.Scanner;
import
currency.CurrencyConverter;
import distance.DistanceConverter;
import time.TimeConverter;

public class ConverterApp {


public static void main(String[] args){ int amount,choice,distance,time;
Scanner scanner = new Scanner(System.in);
System.out.println("Choose the conversion type:");System.out.println("1.
Currency");
System.out.println("2. Distance");
System.out.println("3. Time");int input = scanner.nextInt();
if (input == 1){
CurrencyConverter object1 = new CurrencyConverter();
System.out.println("Choose the currency conversion:");
System.out.println("1. Dollar to INR");

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("2. Euro to INR");


System.out.println("3. Yen to INR");
System.out.println("4. INR to Dollar");
System.out.println("5. INR to Euro");
System.out.println("6. INR to Yen");choice =
scanner.nextInt();
switch(choice){
case 1:
System.out.println("Enter the amount in Dollar:");amount =
scanner.nextInt();
System.out.println("INR:"+object1.DollartoINR(amount));
break;
case 2:
System.out.println("Enter the amount in Euro:");amount =
scanner.nextInt();
System.out.println("INR:"+object1.EurotoINR(amount));
break;
case 3:
System.out.println("Enter the amount in Yen:");amount =
scanner.nextInt();
System.out.println("INR:"+object1.YentoINR(amount));
break;
case 4:
System.out.println("Enter the amount in INR:");amount =
scanner.nextInt();
System.out.println("Dollar:"+object1.INRtoDollar(amount));
break;
case 5:
System.out.println("Enter the amount in INR:");amount =
scanner.nextInt();
System.out.println("Euro:"+object1.INRtoEuro(amount));
break;
amount = scanner.nextInt();

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

else if (input == 2){


DistanceConverter object2 = new DistanceConverter();
System.out.println("Choose the distance conversion:");
System.out.println("1. Meter to KM");
System.out.println("2. KM to Meter");
System.out.println("3. Miles to KM");
System.out.println("4. KM to Miles"); choice =
scanner.nextInt();
switch(choice){
case 1:
System.out.println("Enter the distance in meters:");distance =
scanner.nextInt();
System.out.println("KM:"+object2.MetertoKM(distance));
break;
case 2:
System.out.println("Enter the distance in KM:");distance =
scanner.nextInt();
System.out.println("Meters:"+object2.KMtoMeter(distance));
break;
case 3:
System.out.println("Enter the distance in miles:");distance =
scanner.nextInt();
System.out.println("KM:"+object2.MilestoKM(distance));
break;
case 4:
System.out.println("Enter the distance in KM:");distance =
scanner.nextInt();
System.out.println("Miles:"+object2.KMtoMiles(distance));
break;default:
System.out.println("Invalid choice");
}
}
else if (input == 3){
TimeConverter object3 = new TimeConverter();
System.out.println("Choose the time conversion:"); System.out.println("1.
Hours to Minutes");
System.out.println("2. Minutes to Hours");
System.out.println("3. Hours to Seconds"); System.out.println("4.
Seconds to Hours");choice = scanner.nextInt();

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;
}

Execution Results - All test cases have succeeded!

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.

Note: Use println() to print the output statements.

Pre lab Questions B217.3

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");
}
}

Execution Results - All test cases have succeeded!

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

Post lab Questions B217.3

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.

Pre lab Questions B217.4

• What is a collection in Java, and why is it used?


• Explain the difference between collections and arrays.
• Discuss the advantages of using collections over arrays in Java.

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;

public class AbstractChecker {


// write the code..
public static void main(String[] args) throws IOException{Scanner scanner =
new Scanner(System.in);
String fileName = scanner.nextLine();
try{

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

FileReader file = new FileReader(fileName);


BufferedReader fileInput = new
BufferedReader(file);String line;
StringBuilder text = new StringBuilder();
while((line = fileInput.readLine()) != null){
text.append(line) ;
}
if(text.length() < 250){
System.out.println("Eligible");
}
else{
System.out.println("Not eligible");
}
System.out.println("Character count: "+ text.length());
fileInput.close();
}
catch(FileNotFoundException e){
System.out.println("File does not exist");
}

Post lab Questions B217.4

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

Execution Results - All test cases have succeeded!

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.

Pre lab Questions B217.5


1. What is a build system, and why is it important in Spring Boot development?
2. Compare and contrast Maven and Gradle as build systems for Spring Boot projects.
3. Discuss the advantages and disadvantages of each build system.

Source Code:
package q28286;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;

public class ReverseFileContent {

// write your code here..


public static void main(String[] args) throws
IOException{Scanner scanner = new
Scanner(System.in);
String fileName = scanner.nextLine();
try{
FileReader file = new FileReader(fileName);

BufferedReader fileInput = new


BufferedReader(file);String line;

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

Execution Results - All test cases have succeeded!

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

Post lab Questions B217.5


1. Define RESTful web services and their characteristics.
2. Discuss the principles of REST and how they are applied in building web
services.
3. Describe the benefits of using RESTful architecture for web services

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

1. https://www.javatpoint.com/.Herbert Schildt,"Java The complete reference",McGraw


Hill Education
2. Craig Walls,“Spring Boot in Action”Manning Publication
3. Steven Holzner,“Java Black Book”,Dream tech.
4. Balagurusamy E,“Programming in Java”,McGraw Hill
5. Java: A Beginner’s Guide by Herbert Schildt,Oracle Press
6. Greg L. Turnquist, “Learning SpringBoot2.0-Second Edition”,Packt Publication
7. AJ Henley Jr(Author),Dave Wolf, “Introduction to Java Spring Boot:Learning by
Coding”, Independently Published

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)

List of Experiments (Indicative & not limited to)


1. Use Java compiler and eclipse platform to write and execute java program.
2. Creating simple java programs using command line arguments
3. Understand OOP concepts and basics of Java programming.
4. Create Java programs using inheritance and polymorphism.
5. Implement error-handling techniques using exception handling and multithreading.
6. Create java program with the use of java packages.
7. Construct java program using Java I/O package.
8. Create industry oriented application using Spring Framework.
9. Test RESTful web services using Spring Boot.
10. Test Front end web application with Spring Boot

Note: The Instructor may add/delete/modify/tune experiments, wherever he/she feels in a


justified manner It is also suggested that open source tools should be preferred to conduct the
lab ( Java , JSP , BootstrapFirebug , WampServer , MongoDB, etc)

OOP with Java Lab (BCS 452) Manual (CS, IV SEM) Page No. 68

You might also like