0% found this document useful (0 votes)
4 views31 pages

Core Java Lab Manual-CS270

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)
4 views31 pages

Core Java Lab Manual-CS270

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/ 31

Department of Computer Science & Engineering

LAB MANUAL

Subject Name: - Object Oriented Concepts using JAVA

Subject Code: - CS270

Branch :- CSE

Year :- 2nd

Semester :- 3rd

INTEGRAL UNIVERSITY LUCKNOW


Dsauli, Kursi Road, PO Basha-226026
VISION

To produce highly skilled personnel who are empowered enough to transform the society by their
education, research and innovations.

MISSION

 To offer diverse academic programs at undergraduate, postgraduate, and doctorate levels that are in
line with the current trends in Computer Science and Engineering.
 To provide the state of the art infrastructure for teaching, learning and research.
 To facilitate collaborations with other universities, industry and research labs.

PROGRAM EDUCATIONAL OBJECTIVES (PEO’s)

B Tech: Computer Science & Engineering

To produce graduates who have strong foundation of knowledge and skills in the field of
PEO1 computer science and engineering.

PEO2 To produce graduates who are employable in industries/public sector/research organizations or


work as an entrepreneur.

PEO3 To produce graduates who can provide solutions to challenging problems in their profession by
applying computer engineering theory and practices.

PEO4 To produce graduates who can provide leadership and are effective in multidisciplinary
environment.
PROGRAM SPECIFIC OUTCOMES ( PSO’s)

PSO 1 Ability to understand the principles and working of computer systems. Students have a sound
knowledge about the hardware and software aspects of computer systems.

PSO 2 Ability to design and develop computer programs and understand the structure and development
methodologies of software systems.

PSO 3 Ability to apply their skills in the field of algorithms, networking, web design, cloud computing
and data analytics.
PSO 4 Ability to apply knowledge to provide innovative novel solutions to existing problem and identify
research gaps

Course Objectives

1- Introduce programming paradigms and establish a strong foundation in Java programming


concepts.
2- Familiarize students with the Java environment, including program development, compilation,
and execution.
3- Teach Object-Oriented Programming (OOP) principles such as classes, objects, inheritance, and
polymorphism.
4- Develop skills in exception handling, multithreading, and file handling to build robust
applications.
5- Enable students to work with arrays, strings, and Java I/O operations for efficient data
manipulation.

Course Outcome
After undergoing this laboratory module, the participant should be able to:
1- Demonstrate an understanding of programming paradigms and fundamental Java programming
concepts.
2- Implement Object-Oriented Programming feature of class design, object creation, constructors,
access modifiers and Arrays.
3- Apply inheritance and polymorphism to create modular and reusable JAVA program
4- Perform file handling and input/output operations using Java’s standard I/O streams and file
handling classes.
5- Utilize exception handling techniques for efficient program execution & Develop multithreaded
programs by implementing thread creation, synchronization, and inter-thread communication.
CERTIFICATE

Name of Teacher Signature

Prepared By Mr. Mohammad Ishaque

Date of With Effect From 3th June 2025


Preparation
Review On Date 14th June 2025

verified by Dr. Sheeba Parveen


List of Lab Exercises
Week Objective No Name of the Experiments/Program PageNo.

Week1 Objective-1 Introduction to java programming laboratory 1-5


1.1 Java program to display Hello java message 6
1.2 Create a class named 'Student' with String variable 'name' and 7
integer variable 'roll_no'. Assign the value of roll_no as '2' and that
of name as "John" by creating an object of the class Student
Week2 Objective-2 Print the average of three numbers entered by user by creating 8
class named 'Average' which has a method to calculate and
print the average.
Week3 Objective-3 Twin Prime are the prime numbers whose difference is 2 such as 9
(3, 5), (5, 7), (11, 13). Write a program to display all twin prime
numbers from 1 to n. Where n is the last range that is to be
inputted by the user. Methods to be created are:
•prime() – method which will check whether the number is prime
or not.
• main() – which will call the prime() method
Week4 Objective-4 Write a program to print the area and perimeter of a triangle by 11
creating a class named 'Triangle' with a Parameterized constructor
having the three sides as its parameters.
Week5 Objective-5 Write a program to display the Fibonacci series from 1 to n using a 13
recursive function. Where n is the last range that is to be inputted
by the user
Week6 Objective-6 Write a Java program to calculate the average value of array 14
elements where array elements are {20,30,25,25,- 16,60,-100}.
Week7 Objective-7 Write a program to print the volume of a Cube, Cuboid, and Sphere 16
by using the concept of Method Overloading. Create a class named
‘Volume’.
Week8 Objective-8 Write a program to perform a single inheritance on two classes and 18
also incorporating the concept of method overriding.
Week9 Objective-9 Write a Java program to perform employee payroll processing 20
using packages. Create a package Employee. In the package create
2 files:
1. Emp.java: Declare the variables name, empid, category, bpay,
hra, da, npay, pf, grosspay, incometax, and allowance. Calculate
the values in methods.
2. Emppay.java: Create an object e to call the methods to perform
and print values. The salary is calculated according to the following
rules:
Salary = Basic pay+HRA+DA
HRA = 30% of basic pay
DA = 40% of basic pay
Week10 Objective-10 Write a Java program that implements a Library Management 23
System with the following features:
 Object-Oriented Programming (OOP): Create a Book class
with attributes title and author, Implement a
Library class that manages a collection of books.
 File Handling: Implement methods in the Library class to
save and load books using serialization.
 Exception Handling: Handle exceptions in file operations
using try-catch blocks.
 Multithreading: Implement a background task using
multithreading that runs parallel to user operations.
 User Interaction: Provide a menu-driven interface where
users can:
o Add a book (by entering title and author).
o View the list of books.
o Save the book list to a file.
o Load the book list from a file.
o Exit the program
Introduction to JAVA Programming Laboratory

JAVA: 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.

Laboratory Objective
Upon successful completion of this Lab the student will be able to:

1. Understand the concept of OOP as well as the purpose and usage principles of
inheritance, polymorphism, encapsulation and method overloading.
2. Understand fundamentals of programming such as variables, conditional and iterative
execution, methods, etc.
3. Identify classes, objects, members of a class and the relationships among them needed
for a specific problem.
4. Understand fundamentals of object-oriented programming in Java, including defining
classes, invoking methods, using class libraries, etc.
5. Create Java application programs using sound OOP practices (e.g., interfaces and APIs)
and proper program structuring (e.g., by using access control identifies, automatic
documentation through comments, error exception handling)
6. Have the ability to write a computer program to solve specified problems.
7. Develop programs using the Java Collection API as well as the Java standard class
library.
8. Use the Java SDK environment to create, debug and run simple Java programs

Overview of Java

Java Is Important to the Internet, The Internet helped catapult Java to the forefront of
programming, and Java, in turn, has had a profound effect on the Internet. The reason for this is
quite simple: Java expands the universe of objects that can move about freely in cyberspace. In a
network, two very broad categories of objects are transmitted between the server and our
personal computer: passive information and dynamic, active programs.

Java can be used to create two types of programs: applications and applets. An application is a
program that runs on your computer, under the operating system of that computer. An applet is
an application designed to be transmitted over the Internet and executed by a Java- compatible
Web browser.

Features of JAVA

▪ Simple
▪ Secure
▪ Portable

1
▪ Object-oriented
▪ Robust
▪ Multithreaded
▪ Architecture-neutral
▪ Interpreted
▪ High performance
▪ Distributed
▪ Dynamic

JDK

The Java Development Kit (JDK) is an implementation of either one of the Java SE, Java EE or
Java ME platforms. The JDK includes a private JVM and a few other resources to finish the
development of a Java Application.
The JDK has as its primary components a collection of programming tools, including:
▪ appletviewer – this tool can be used to run and debug Java applets without a web
browser
▪ apt – the annotation-processing tool.
▪ extcheck – a utility that detects JAR file conflicts
▪ idlj – the IDL-to-Java compiler. This utility generates Java bindings from a given Java
IDL file.
▪ jabswitch – the Java Access Bridge. Exposes assistive technologies on Microsoft
Windows systems.
▪ java – the loader for Java applications. This tool is an interpreter and can interpret the
class files generated by the javac compiler. Now a single launcher is used for both
development and deployment. The old deployment launcher, jre, no longer comes with
Sun JDK, and instead it has been replaced by this new java loader.
▪ javac – the Java compiler, which converts source code into Java bytecode
▪ javadoc – the documentation generator, which automatically generates documentation
from source code comments
▪ jar – the archiver, which packages related class libraries into a single JAR file. This
tool also helps manage JAR files.
▪ javafxpackager – tool to package and sign JavaFX applications
▪ jarsigner – the jar signing and verification tool
▪ javah – the C header and stub generator, used to write native methods
▪ javap – the class file disassembler
▪ javaws – the Java Web Start launcher for JNLP applications
▪ JConsole – Java Monitoring and Management Console
▪ jdb – the debugger
▪ jhat – Java Heap Analysis Tool (experimental)
▪ jinfo – This utility gets configuration information from a running Java process or
crash dump. (experimental)
▪ jmap – This utility outputs the memory map for Java and can print shared object
memory maps or heap memory details of a given process or core dump.
(experimental)
▪ jmc – Java Mission Control
▪ jps – Java Virtual Machine Process Status Tool lists the instrumented HotSpot Java
Virtual Machines (JVMs) on the target system. (experimental)
▪ jrunscript – Java command-line script shell.
▪ jstack – utility that prints Java stack traces of Java threads (experimental)
▪ jstat – Java Virtual Machine statistics monitoring tool (experimental)
2
▪ jstatd – jstat daemon (experimental)
▪ keytool – tool for manipulating the keystore
▪ pack200 – JAR compression tool
▪ policytool – the policy creation and management tool, which can determine policy for a
Java runtime, specifying which permissions are available for code from various sources
▪ VisualVM – visual tool integrating several command-line JDK tools and lightweight
performance and memory profiling capabilities
▪ wsimport – generates portable JAX-WS artifacts for invoking a web service.
▪ xjc – Part of the Java API for XML Binding (JAXB) API. It accepts an XML schema
and generates Java classes.

3
Data Types used in JDK

Each row contains the data type and size and range of the data type. The list of available
data types in Java is shown in table below

Name Width(bit) Range


byte 8 –128 to 127
short 16 –32,768 to 32,767
int 32 –2,147,483,648 to 2,147,483,647
long 64 –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
float 32 1.4e−045 to 3.4e+038
double 64 4.9e–324 to 1.8e+308
Char 2 0 to 65,536
Boolean 1 True or false

PATH and CLASSPATH

 Purpose: The PATH environment variable in Windows tells the operating system where to look for
executable files. When you type a command in the command prompt (e.g., java, javac), the system
searches the directories listed in PATH to find the appropriate executable.
 For Java: The PATH variable needs to include the directory where the Java executable files ( java,
javac, etc.) are located. This is typically the bin folder inside the JDK installation directory.
 How to Set:
1. Right-click "This PC" (or "My Computer") and click "Properties."
2. Click "Advanced system settings" and then "Environment Variables."
3. Under "System Variables," find Path and click "Edit."
4. Add the path to the bin directory of your JDK installation, such as C:\Program
Files\Java\jdk-<version>\bin.
 Effect: Once set, you can run Java commands from any directory in the command prompt without
needing to navigate to the bin folder.

CLASSPATH in Java (Windows OS)

 Purpose: The CLASSPATH environment variable tells the Java runtime where to look for class files
and JAR files when running or compiling Java programs. By default, Java looks in the current
directory (.) if CLASSPATH is not set.
 How to Set:
1. Go to "Environment Variables" as above.
2. Under "System Variables," click "New" and create a variable called CLASSPATH.
3. Set its value to the path where your .class files are located, or the location of any JAR files
you want to include (e.g., C:\myproject\classes).
 Effect: This ensures that the Java runtime can find your class files or libraries when executing Java
programs. You can also add multiple directories or JAR files, separated by semicolons ( ;).

4
Update the PATH Environment Variable (Microsoft Windows)
We can run Java applications just fine without setting the PATH environment variable. Or, we
can optionally set it as a convenience.
Set the PATH environment variable if we want to be able to conveniently run the executables
(javac.exe, java.exe, javadoc.exe, and so on) from any directory without having to type the full
path of the command. If we do not set the PATH variable, we need to specify the full path to the
executable every time we run it, such as:
C:\Java\jdk1.7.0\bin\javac MyClass.java
The PATH environment variable is a series of directories separated by semicolons (;). Microsoft
Windows looks for programs in the PATH directories in order, from left to right. We should
have only one bin directory for the JDK in the path at a time (those following the first are
ignored), so if one is already present, we can update that particular entry.
The following is an example of a PATH environment variable:
C:\Java\jdk1.7.0\bin;C:\Windows\System32\;C:\Windows\;C:\Windows\System32\Wbem
It is useful to set the PATH environment variable permanently so it will persist after rebooting.
To make a permanent change to the PATH variable, use the System icon in the Control Panel.
The precise procedure varies depending on the version of Windows:
Windows XP
1. Select Start, select Control Panel. double click System, and select the Advanced
tab.
2. Click Environment Variables. In the section System Variables, find the PATH
environment variable and select it. Click Edit. If the PATH environment variable does
not exist, click New.
3. In the Edit System Variable (or New System Variable) window, specify the value of
the PATH environment variable. Click OK. Close all remaining windows by clicking
OK.

Suggested Reading:
1. Herbert Scheldt, ―The Complete Reference Java, 7th Edition, Tata McGraw Hill,
2006.
2. James M Slack, Programming and Problem Solving with JAVA, Thomson Learning,
2002.
3. C Thomas Wu, An Introduction to Object Oriented Programming with Java 5th
Edition, McGraw Hill Publishing, 2010.
H. M. Dietel and P. J. Dietel, Java How to Program, Sixth Edition, Pearson Education /
PHI

5
Experiment No 1.1

OBJECTIVE
Java program to display Hello java message

Class Declaration:

 class Simple: This defines a class named Simple. In Java, all code must be inside a class.

main Method:

 public static void main(String args[]): This is the entry point for the program. The main method is
where execution starts when you run the Java program.
 public: The method is public, meaning it can be called from anywhere.
 static: The method is static, meaning it belongs to the class itself, not an instance of the class.
 void: This means the method does not return any value.
 String args[]: This is a parameter that can hold command-line arguments, although it isn't
used in this particular program.

class Simple
{

public static void main(String args[])


{
System.out.println("Hello Java");
}
}

Compile the program using the following command:

To compile:
javac Simple.java

To execute:
java Simple

Output:
Hello Java

6
Experiment No 1.2

OBJECTIVE
Create a class named 'Student' with String variable 'name' and integer
variable 'roll_no'. Assign the value of roll_no as '2' and that of name as
"John" by creating an object of the class Student.

public class Student


{
public void identity(String x, int y)
{
String name = x;
int roll_no = y;
System.out.println("Name = "+ name);
System.out.println("Roll no. = " + roll_no);
}
public void main()
{
Student st = new Student();
st.identity("John", 2);
}
}

To compile:
javac Student.java

To execute:
java Student

Output:
Name = John
Roll no = 2

7
Experiment No 2

OBJECTIVE
Print the average of three numbers entered by user by creating a class named
‘Average' which has a method to calculate and print the average.

import java.util.Scanner;
public class Test
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print("Enter the first number: ");
double num1 = scan.nextDouble();
System.out.print("Enter the second number: ");
double num2 = scan.nextDouble();
System.out.print("Enter the third number: ");
double num3 = scan.nextDouble();
scan.close();
System.out.print("The average of entered numbers is:" + avr(num1, num2, num3) );
}

public static double avr(double a, double b, double c)


{
return (a + b + c) / 3;
}
}

To compile:
javac Test.java
To execute:
java Test
Input:
Enter the first number: 10
Enter the second number: 20
Enter the third number: 30
Output:
The average of entered numbers is: 20.0

8
Experiment No 3

OBJECTIVE
Twin Prime are the prime numbers whose difference is 2 such as (3, 5), (5, 7), (11, 13).
Write a program to display all twin prime numbers from 1 to n. Where n is the last
range that is to be inputted by the user. Methods to be created are:
• prime() – method which will check whether the number is prime or not.
• main() – which will call the prime() method.

The Twin Prime numbers are the two Prime numbers having a difference of 2 between both of them. A
prime having a prime gap of two is referred to as a twin prime. The twin prime term is used for a pair of
twin primes. The twin primes are also known as prime pair or prime twin.
The pair (2, 3) is generally not considered as a pair of twin prime because 2 is the only even prime, and the
pair is the only pair of prime numbers that differ from one.

Let's take some examples of Twin Prime numbers.


The pair (3, 5) is a pair of Twin Primes numbers because the difference between both the numbers is 2.
The pair (3, 7) is not a pair of Twin Primes number because the difference of both the numbers is not 2.
The pair (71, 73) is a pair of Twin Primes numbers because the difference between both the numbers is 2.

import java.util.Scanner;
class Test
{
static boolean isPrime(int n)
{
int i;
for(i=2;i<n;i++)
{
if(n%i==0)
{
return false;
}
}
return true;
}
public static void main(String[] args)
{
int i,low,upr;
Scanner sc=new Scanner(System.in);
System.out.println("Enter lower limit : ");
low=sc.nextInt();
System.out.println("Enter upper limit : ");
upr=sc.nextInt();
System.out.println("Twin prime number are : ");
for(i=low;i<=upr-2;i++)
{
if(isPrime(i) && isPrime(i+2))

9
System.out.println(i+" "+(i+2));
}
}
}

Input
Enter lower limit :
10
Enter upper limit :
50
Output
Twin prime number are :
11 13
17 19
29 31
41 43

10
Experiment No 4

OBJECTIVE
Write a program to print the area and perimeter of a triangle by creating a class
named 'Triangle' with a Parameterized constructor having the three sides as its
parameters.

Problem Description
Constructors are used to assign initial values to instance variables of the class. A default constructor with
no arguments will be called automatically by the Java Virtual Machine (JVM). Constructor is always
called by new operator. Constructors are declared just like as we declare methods, except that the
constructor doesn‘t have any return type. Constructor can be overloaded provided they should have
different arguments because JVM differentiates constructors on the basis of arguments passed in the
constructor.

public class Triangle {


private double side1;
private double side2;
private double side3;

// Parameterized constructor
public Triangle(double side1, double side2, double side3) {
this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
}

// Method to calculate the perimeter


public double getPerimeter() {
return side1 + side2 + side3;
}

// Method to calculate the area using Heron's formula


public double getArea() {
double s = getPerimeter() / 2.0;
return Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));
}

// Method to display the area and perimeter


public void display() {
System.out.println("Perimeter of triangle: " + getPerimeter());
System.out.println("Area of triangle: " + getArea());
}

// Main method to test the Triangle class


public static void main(String[] args) {
// Create a triangle with sides 3, 4, and 5
Triangle t = new Triangle(3, 4, 5);

11
t.display();
}
}

Output (for sides 3, 4, 5):


Perimeter of triangle: 12.0
Area of triangle: 6.0

12
Experiment No 5

OBJECTIVE
Write a program to display the Fibonacci series from 1 to n using a
recursive function. Where n is the last range that is to be inputted by the
user.

 In fibonacci series, next number is the sum of previous two numbers for example 0, 1, 1, 2, 3, 5, 8,
13, 21, 34, 55 etc. The first two numbers of fibonacci series are 0 and 1.

import java.io.*;

class Test
{

// Function to print the fibonacci series


static int fib(int n)
{
// Base Case
if (n <= 1)
return n;

// Recursive call
return fib(n - 1) + fib(n - 2);
}

// Driver Code
public static void main(String args[])
{
// Given Number N
int N = 10;

// Print the first N numbers


for (int i = 0; i < N; i++)
{

System.out.print(fib(i) + " ");


}
}
}

Output

0 1 1 2 3 5 8 13 21 34

13
Experiment No 6

OBJECTIVE

Write a Java program to calculate the average value of array elements where
array elements are {20,30,25,25,- 16,60,-100}.
Java Arrays:
Normally, an array is a collection of similar type of elements which has contiguous memory location.

Java array is an object which contains elements of a similar data type. Additionally, The elements of an
array are stored in a contiguous memory location. It is a data structure where we store similar elements. We
can store only a fixed set of elements in a Java array.

Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element is stored on
1st index and so on.

Unlike C/C++, we can get the length of the array using the length member. In C/C++, we need to use the
sizeof operator.

In Java, array is an object of a dynamically generated class. Java array inherits the Object class, and
implements the Serializable as well as Cloneable interfaces. We can store primitive values or objects in an
array in Java. Like C/C++, we can also create single dimentional or multidimentional arrays in Java.

Advantages

o Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
o Random access: We can get any data located at an index position.

Disadvantages

o Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at
runtime. To solve this problem, collection framework is used in Java which grows automatically.

Types of Array in java

There are two types of array.

 Single Dimensional Array


 Multidimensional Array

Single Dimensional Array in Java

Syntax to Declare an Array in Java

1-dataType[] arr; (or)


2-dataType []arr; (or)
3-dataType arr[];

14
Instantiation of an Array in Java

datatype[] arrayRefVar=new datatype[size];

public class AverageArray


{
public static void main(String[] args)
{
// Define the array
int[] numbers = {20, 30, 25, 25, -16, 60, -100};

int sum = 0;
for (int num : numbers) {
sum += num;
}

// Calculate average
double average = (double) sum / numbers.length;

// Print result
System.out.println("Average value of the array elements is: " + average);
}
}

Output:

Average value of the array elements is: 6.285714285714286

15
Experiment No 7

OBJECTIVE
Write a program to print the volume of a Cube, Cuboid, and Sphere by using the
concept of Method Overloading. Create a class named ‘Volume’.

Problem Description
In Java it is possible to define two or more methods within the same class that share the same name, as long
as their parameter declarations are different. When this is the case, the methods are said to be overloaded,
and the process is referred to as method overloading. Method overloading is one of the ways that Java
implements polymorphism.

public class Volume {

// Method to calculate volume of a cube


public double calculateVolume(double side) {
return side * side * side;
}

// Method to calculate volume of a cuboid


public double calculateVolume(double length, double breadth, double height) {
return length * breadth * height;
}

// Method to calculate volume of a sphere


public double calculateVolume(float radius) {
return (4.0 / 3.0) * Math.PI * radius * radius * radius;
}

public static void main(String[] args) {


Volume v = new Volume();

// Cube with side 5


double cubeVolume = v.calculateVolume(5.0);
System.out.println("Volume of Cube: " + cubeVolume);

// Cuboid with length=5, breadth=4, height=3


double cuboidVolume = v.calculateVolume(5.0, 4.0, 3.0);
System.out.println("Volume of Cuboid: " + cuboidVolume);

// Sphere with radius=6


double sphereVolume = v.calculateVolume(6.0f);
System.out.println("Volume of Sphere: " + sphereVolume);

16
}
}

Output

Volume of Cube: 125.0


Volume of Cuboid: 60.0
Volume of Sphere: 904.7786842338603

17
Experiment No 8

OBJECTIVE
Write a program to perform a single inheritance on two classes and also incorporating the
concept of method overriding.

Problem Description
Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at
run time, rather than compile time. Dynamic method dispatch is important because this is how Java
implements run-time polymorphism. Let's begin by restating an important principle: a superclass
reference variable can refer to a subclass object.
Java uses this fact to resolve calls to overridden methods at run time. Here is how. When an
overridden method is called through a superclass reference, Java determines which version of that
method to execute based upon the type of the object being referred to at the time the call occurs. Thus,
this determination is made at run time. When different types of objects are referred to, different
versions of an overridden method will be called.

// Parent class
class Animal {
// Method to be overridden
public void sound() {
System.out.println("Animal makes a sound");
}

public void eat() {


System.out.println("Animal eats food");
}
}

// Child class inheriting from Animal


class Dog extends Animal {
// Overriding the sound() method
@Override
public void sound() {
System.out.println("Dog barks");
}

// You can add extra methods specific to Dog


public void breedInfo() {
System.out.println("Breed: Labrador");
}
}

// Main class
18
public class Main {
public static void main(String[] args) {
// Create object of Dog class
Dog dog = new Dog();

// Call overridden method


dog.sound(); // Will call Dog's version

// Call inherited method


dog.eat(); // Inherited from Animal

// Call Dog-specific method


dog.breedInfo();
}
}

Output:
Dog barks
Animal eats food
Breed: Labrador

19
Experiment No 9

OBJECTIVE
Write a Java program to perform employee payroll processing using
packages. Create a package Employee. In the package create 2 files:
1. Emp.java: Declare the variables name, empid, category, bpay, hra, da, npay, pf,
grosspay, incometax, and allowance. Calculate the values in methods.
2. Emppay.java.: Create an object e to call the methods to perform and print values.
The salary is calculated according to the following rules:
Salary = Basic pay+HRA+DA
HRA = 30% of basic pay
DA = 40% of basic pay

Problem Description
 Package is a collection of related classes and interfaces as a single unit.
 Package is a folder contains .class files.
 It is an Encapsulation mechanism to group related classes and interfaces into a single
unit.
 It provides security to the classes and interfaces. So that outside person cannot access
directly.

The packages are divided into two types


1) Predefined packages
2) User defined packages

Predefined packages:-
The java predefined packages are introduced by sun peoples these packages contains predefined
classes and interfaces.

Ex:- java.lang
Java.io
Java.awt
Java.util
Java.net………………………..etc

User defined packages:-


1- The packages which are declared by the user are called user defined packages.
2-We can declare a package with the help of package keyword.

Syntax :- package package_name;

20
1. Emp.java

This file declares variables and contains methods to calculate HRA, DA, Salary,
etc.

package Employee;

public class Emp {


public String name;
public int empid;
public String category;
public double bpay; // Basic Pay
public double hra; // House Rent Allowance
public double da; // Dearness Allowance
public double pf; // Provident Fund
public double allowance; // Any additional allowance
public double grosspay; // Gross Pay before deductions
public double incometax; // Income Tax
public double npay; // Net Pay after deductions

// Constructor to initialize employee details


public Emp(String name, int empid, String category, double bpay, double allowance, double incometax) {
this.name = name;
this.empid = empid;
this.category = category;
this.bpay = bpay;
this.allowance = allowance;
this.incometax = incometax;
}

// Method to calculate payroll components


public void calculateSalary() {
hra = 0.30 * bpay;
da = 0.40 * bpay;
pf = 0.12 * bpay; // Assuming 12% PF
grosspay = bpay + hra + da + allowance;
npay = grosspay - (pf + incometax);
}

// Method to display all payroll details


public void display() {
System.out.println("========== Employee Payroll Details ==========");
System.out.println("Name : " + name);
System.out.println("Employee ID : " + empid);
System.out.println("Category : " + category);
System.out.println("Basic Pay : " + bpay);
System.out.println("HRA (30%) : " + hra);
System.out.println("DA (40%) : " + da);
System.out.println("Allowance : " + allowance);
System.out.println("PF (12%) : " + pf);
System.out.println("Income Tax : " + incometax);

21
System.out.println("Gross Pay : " + grosspay);
System.out.println("Net Pay : " + npay);
System.out.println("==============================================");
}
}

2. Emppay.java

This is the main class which creates an employee object and calls the methods.

package Employee;

public class Emppay {


public static void main(String[] args) {
// Create an employee object
Emp e = new Emp("Alice Johnson", 101, "Full-time", 30000, 2000, 1500);

// Perform salary calculation


e.calculateSalary();

// Display payroll
e.display();
}
}

Output:

========== Employee Payroll Details ==========


Name : Alice Johnson
Employee ID : 101
Category : Full-time
Basic Pay : 30000.0
HRA (30%) : 9000.0
DA (40%) : 12000.0
Allowance : 2000.0
PF (12%) : 3600.0
Income Tax : 1500.0
Gross Pay : 53000.0
Net Pay : 47900.0
==============================================

22
Experiment No 10

OBJECTIVE
Write a Java program that implements a Library Management System with
the following features:

 Object-Oriented Programming (OOP): Create a Book class with attributes title and author,
Implement a Library class that manages a collection of books.
 File Handling: Implement methods in the Library class to save and load books using serialization.
 Exception Handling: Handle exceptions in file operations using try-catch blocks.
 Multithreading: Implement a background task using multithreading that runs parallel to user
operations.
 User Interaction: Provide a menu-driven interface where users can:
o Add a book (by entering title and author).
o View the list of books.
o Save the book list to a file.
o Load the book list from a file.
o Exit the program

import java.io.*;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;

class Book implements Serializable {


private String title;
private String author;

public Book(String title, String author) {


this.title = title;
this.author = author;
}

public String toString() {


return "Title: " + title + ", Author: " + author;
}
}

class Library {
private List<Book> books;

public Library() {
books = new CopyOnWriteArrayList<>();
}

public void addBook(String title, String author) {


books.add(new Book(title, author));

23
System.out.println("Book added successfully.");
}

public void viewBooks() {


if (books.isEmpty()) {
System.out.println("No books in the library.");
} else {
System.out.println("Library contains:");
for (Book book : books) {
System.out.println(" - " + book);
}
}
}

public void saveToFile(String filename) {


try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(filename))) {
out.writeObject(books);
System.out.println("Books saved to file.");
} catch (IOException e) {
System.out.println("Error saving to file: " + e.getMessage());
}
}

public void loadFromFile(String filename) {


try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(filename))) {
books = (List<Book>) in.readObject();
System.out.println("Books loaded from file.");
} catch (IOException | ClassNotFoundException e) {
System.out.println("Error loading from file: " + e.getMessage());
}
}
}

class BackgroundTask extends Thread {


public void run() {
while (true) {
try {
Thread.sleep(10000); // Runs every 10 seconds
System.out.println("[BackgroundTask] Reminder: Don't forget to save your library!");
} catch (InterruptedException e) {
System.out.println("[BackgroundTask] Interrupted.");
}
}
}
}

public class LibraryManagementSystem {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Library library = new Library();
BackgroundTask backgroundTask = new BackgroundTask();
backgroundTask.setDaemon(true); // Daemon so it stops when main ends

24
backgroundTask.start();

while (true) {
System.out.println("\n--- Library Menu ---");
System.out.println("1. Add a book");
System.out.println("2. View books");
System.out.println("3. Save books to file");
System.out.println("4. Load books from file");
System.out.println("5. Exit");
System.out.print("Choose an option (1-5): ");

String choice = scanner.nextLine();


switch (choice) {
case "1":
System.out.print("Enter title: ");
String title = scanner.nextLine();
System.out.print("Enter author: ");
String author = scanner.nextLine();
library.addBook(title, author);
break;

case "2":
library.viewBooks();
break;

case "3":
library.saveToFile("library.ser");
break;

case "4":
library.loadFromFile("library.ser");
break;

case "5":
System.out.println("Exiting program. Goodbye!");
return;

default:
System.out.println("Invalid choice. Please try again.");
}
}
}
}

Save the code in a file named LibraryManagementSystem.java

Compile:
javac LibraryManagementSystem.java

Run:
java LibraryManagementSystem

25

You might also like