0% found this document useful (0 votes)
2 views32 pages

Core Java Lab Manual-CS271 (2024-25)

The document is a lab manual for Object Oriented Programming using Java at Integral University, outlining the vision, mission, program educational objectives, and specific outcomes for students. It includes a series of programming experiments designed to teach Java concepts such as classes, methods, and exception handling. Additionally, it covers essential Java features, the Java Development Kit (JDK), and data types used in Java programming.

Uploaded by

abhayg
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)
2 views32 pages

Core Java Lab Manual-CS271 (2024-25)

The document is a lab manual for Object Oriented Programming using Java at Integral University, outlining the vision, mission, program educational objectives, and specific outcomes for students. It includes a series of programming experiments designed to teach Java concepts such as classes, methods, and exception handling. Additionally, it covers essential Java features, the Java Development Kit (JDK), and data types used in Java programming.

Uploaded by

abhayg
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/ 32

Department of Computer Science & Engineering

LAB MANUAL

Object Oriented Programming using Java Lab

CS271

INTEGRAL UNIVERSITY LUCKNOW


Dasauli, 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)

To produce graduates who have strong foundation of knowledge and skills in the
PEO1 field of 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
Experiment Objective Page
No. No.
1 Introduction about Java 1-5

2 Create a class named 'Student' with String variable 'name' and integer 6-7
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.
3 Print the average of three numbers entered by user by creating a class 8-9
named 'Average' which has a method to calculate and print the average.
4 Twin Prime are the prime numbers whose difference is 2 such as 10-11
(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. •
show() – which will print the twin prime numbers and will call
the prime() method. • main() – which will call the show() method
5 Write a program to print the area and perimeter of a triangle by creating a 12-14
class named 'Triangle' with a parameterized constructor having the three
sides as its parameters.
6 Write a program to print the volume of a Cube, Cuboid, and Sphere by 15-16
using the concept of Method Overloading. Create a class named ‘Volume’.
7 Write a Java program to calculate the average value of array elements 17
where array elements are {20,30,25,25,- 16,60,-100}
8 Write a Java program for exception handling using a try-catch block 18-19
9 Write a program to display the Fibonacci series from 1 to n using a 20-21
recursive function. Where n is the last range that is to be inputted by the
user.
10 Write a program to perform a single inheritance on two classes. 22-24
11 Write a Java program to perform employee payroll processing using 25-28
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
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.

1
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
▪ 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

2
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)
▪ 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 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

Setting PATH and CLASSPATH environment variables on Microsoft Windows,


Solaris, and Linux are as follows.
Install the Java Development Kit (JDK) software.

After installing the software, the JDK directory will have the structure shown below.
The bin directory contains both the compiler and the launcher.

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\Syste
m32\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 / PH
5
Program 1

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

In object-oriented programming (OOP), classes and objects are fundamental concepts used
to model real-world entities and their behaviors.
Class
 Definition: A class is a blueprint or template for creating objects. It defines the
properties (attributes) and behaviors (methods or functions) that the objects created
from the class will have.
 Structure: A class typically contains:
o Attributes: These are variables that hold data related to the class (e.g., name,
roll_no).
o Methods: These are functions that define the behavior of the objects (e.g.,
methods to display information).

Object
 Definition: An object is an instance of a class. When a class is defined, no memory is
allocated until an object of that class is created. Objects contain actual values and
represent specific instances of the class.
 Characteristics: Each object has its own state (attribute values) and behavior
(methods). Multiple objects can be created from the same class, each with different
attribute values.

6
Program

public class Student


{
String name;
int roll_no;
}
public class TestStudent
{
public static void main(String[] args)
{
Student s = new Student();
s.name = "John";
s.roll_no = 2;
System.out.println("Name is " + s.name + " add roll number is " + s.roll_no);
}
}

7
Program 2

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.

Scanner is a class in Java that belongs to the java.util package. It is primarily used for
obtaining input from various sources, including user input from the console, files, and other
input streams.

Key Features of the Scanner Class


1. Reading Input: The Scanner class provides methods to read different types of data
such as int, double, String, etc.
2. Flexibility: It can parse primitive types and strings using regular expressions.
3. Convenience: It simplifies the process of reading user input compared to older
methods like BufferedReader.

Syntax- Scanner in = new Scanner(System.in);

In the context of OOP in Java, a method is a block of code that performs a specific task.
Methods are associated with classes and define the behaviors of the objects created from
those classes.
Key Features of Methods
1. Encapsulation: Methods help encapsulate the behavior of an object. You can think of
methods as the functions that operate on the data contained in the object.
2. Reusability: Methods allow code reuse. Once a method is defined, it can be called
multiple times, reducing code duplication.
3. Parameters and Return Types:
o Methods can take parameters (inputs) and can return a value.
o They can also be void, meaning they do not return a value.

8
Program

import java.util.Scanner;
class Average {
// Method to calculate and print the average
void calculateAverage(double num1, double num2, double num3) {
double average = (num1 + num2 + num3) / 3;
System.out.println("The average of the three numbers is: " + average);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Creating an object of the Average class
Average avgCalculator = new Average();
// Prompting user for input
System.out.print("Enter first number: ");
double num1 = scanner.nextDouble();
System.out.print("Enter second number: ");
double num2 = scanner.nextDouble();
System.out.print("Enter third number: ");
double num3 = scanner.nextDouble();
// Calling the method to calculate and print the average
avgCalculator.calculateAverage(num1, num2, num3);
// Closing the scanner
scanner.close();
}
}

9
Program 3

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. • show() – which will print the
twin prime numbers and will call the prime() method. • main() – which will call the
show() method .

Twin Prime are the prime numbers whose difference is 2 such as (3, 5), (5, 7), (11, 13).

prime() – method which will check whether the number is prime or not.
It returns false for numbers less than or equal to 1.
For other numbers, it checks divisibility from 2 to the square root of num. If num is divisible
by any of these, it returns false.

show() – which will print the twin prime numbers and will call the prime() method .
This method takes the upper limit n as input.
It iterates through numbers from 2 to n−2n-2n−2 and checks if both i and i + 2 are prime
using the prime() method.
If both are prime, it prints them as a twin prime pair.

main() – which will call the show() method .


It prompts the user for the upper limit n, creates an instance of the TwinPrime class, and calls
the show() method to find and display the twin primes.

10
Program

import java.util.Scanner;
class TwinPrime {
// Method to check if a number is prime
boolean prime(int num) {
if (num <= 1) return false; // 0 and 1 are not prime
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
return false; // Not prime
}
}
return true; // Prime
}
// Method to print twin prime numbers
void show(int n) {
for (int i = 2; i <= n - 2; i++) {
if (prime(i) && prime(i + 2)) {
System.out.println("(" + i + ", " + (i + 2) + ")");
}
}
}
// Main method
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
TwinPrime twinPrime = new TwinPrime();
System.out.print("Enter the range (n): ");
int n = scanner.nextInt(); // Input the upper limit
System.out.println("Twin prime numbers from 1 to " + n + ":");
twinPrime.show(n); // Call the show method to display twin primes
scanner.close(); // Close the scanner
}
}

11
Program 4

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.

A constructor in Java is a special method that is called when an object of a class is created. It
is used to initialize the object's attributes and to perform any setup steps required for the
object. Constructors have the same name as the class and do not have a return type, not even
void.

Types of Constructors

1. Default Constructor: A constructor that does not take any parameters. If no


constructor is defined, Java provides a default constructor automatically.

2. Parameterized Constructor: A constructor that takes arguments to initialize the


object with specific values.The constructor initializes the instance variables with the
values provided as parameters.

12
Program
class Triangle {
// Instance variables for the three sides of the 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 calculatePerimeter() {
return side1 + side2 + side3;
}

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


public double calculateArea() {
double semiPerimeter = calculatePerimeter() / 2; // Semi-perimeter
return Math.sqrt(semiPerimeter * (semiPerimeter - side1) *
(semiPerimeter - side2) * (semiPerimeter - side3));
}

// Method to display area and perimeter


public void display() {
System.out.printf("Perimeter of the triangle: %.2f\n", calculatePerimeter());
System.out.printf("Area of the triangle: %.2f\n", calculateArea());
}

// Main method to run the program

13
public static void main(String[] args) {
// Example sides of the triangle
Triangle triangle = new Triangle(3, 4, 5);

// Display the area and perimeter


triangle.display();
}
}

14
Program 5

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’

Method Overloading is a feature in Java that allows a class to have more than one method
with the same name, provided that the methods have different parameter lists. This means
that methods can differ in the number of parameters, types of parameters, or both.

Key Characteristics of Method Overloading

1. Same Method Name: All overloaded methods must have the same name.

2. Different Parameters: Methods must differ in their parameter lists. This can be
achieved by:
o Changing the number of parameters.
o Changing the types of parameters.
o Changing the order of parameters.

3. Return Type: The return type of the overloaded methods can be the same or different.
However, the return type alone cannot be used to distinguish between overloaded
methods.

4. Compile-time Polymorphism: Method overloading is an example of compile-time


polymorphism, where the method to be executed is determined at compile time based
on the method signature.

15
Program

class Volume
{
// Method to calculate the volume of a cube
double calculateVolume(int side)
{
return side * side * side; // Volume = side^3
}

// Method to calculate the volume of a cuboid


double calculateVolume(double length, double width, double height) {
return length * width * height; // Volume = length * width * height
}

// Method to calculate the volume of a sphere


double calculateVolume(double radius, boolean isSphere) {
return (4.0 / 3.0) * Math.PI * radius * radius * radius; // Volume = (4/3) * π * radius^3
}

// Method to display the volume


void displayVolume() {
// Cube
double cubeVolume = calculateVolume(5); // Example: side = 5
System.out.printf("Volume of the Cube: %.2f\n", cubeVolume);

// Cuboid
double cuboidVolume = calculateVolume(4, 5, 6); // Example: length = 4, width = 5,
height = 6
System.out.printf("Volume of the Cuboid: %.2f\n", cuboidVolume);

// Sphere
double sphereVolume = calculateVolume(3, true); // Example: radius = 3
System.out.printf("Volume of the Sphere: %.2f\n", sphereVolume);
}

// Main method
public static void main(String[] args) {
Volume volumeCalculator = new Volume();
volumeCalculator.displayVolume(); // Display the volumes
}
}

16
Program 6

Write a Java program to calculate the average value of array elements where array
elements are {20,30,25,25,- 16,60,-100}

An array in Java is a data structure that can hold a fixed number of values of a single type.
The size of an array is determined when it is created and cannot be changed. Arrays are used
to store multiple values in a single variable instead of declaring separate variables for each
value.

Key Features of Arrays


1. Fixed Size: Once an array is created, its size cannot be changed.
2. Homogeneous Elements: All elements in an array must be of the same data type.
3. Zero-based Indexing: Array indices start from 0, so the first element is accessed with
index 0, the second with index 1, and so on.
4. Contiguous Memory Location: Elements of an array are stored in contiguous
memory locations.

Program

public class AverageCalculator {


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

// Calculate the average


double average = calculateAverage(numbers);

// Display the result


System.out.printf("The average value of the array elements is: %.2f\n", average);
}

// Method to calculate the average of array elements


public static double calculateAverage(int[] arr) {
double sum = 0; // Variable to store the sum of elements
for (int num : arr) {
sum += num; // Add each element to the sum
}
return sum / arr.length; // Return the average
}
}

17
Program 7

Write a Java program for exception handling using a try-catch block

Exception handling in Java is a mechanism that allows a program to deal with runtime
errors in a controlled way. Instead of crashing when an error occurs, Java provides a
framework to catch exceptions, allowing the program to continue executing or
terminate gracefully.

Key Concepts of Exception Handling


1. Exception: An event that disrupts the normal flow of the program. Examples include
division by zero, accessing an out-of-bounds index in an array, or trying to open a file
that doesn't exist.
2. Checked vs. Unchecked Exceptions:
o Checked Exceptions: These are exceptions that the compiler checks at compile
time. Examples include IOException, SQLException, etc. They must be either
caught or declared in the method signature.
o Unchecked Exceptions: These occur at runtime and are not checked by the
compiler. Examples include ArithmeticException, NullPointerException, etc.
3. Try-Catch Block: The basic structure for handling exceptions. Code that might throw
an exception is placed in the try block, and the handling code is placed in the catch
block.
4. Finally Block: This block follows the try and catch blocks and executes regardless of
whether an exception was thrown. It's typically used for cleanup tasks (e.g., closing
resources).
5. Throw and Throws:
o throw: Used to explicitly throw an exception.
o throws: Used in a method declaration to indicate that the method can throw
certain exceptions.

18
Program
import java.util.InputMismatchException;
import java.util.Scanner;

public class ExceptionHandlingExample {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

try {
System.out.print("Enter the first number: ");
int num1 = scanner.nextInt();

System.out.print("Enter the second number: ");


int num2 = scanner.nextInt();

// Attempt to divide num1 by num2


int result = num1 / num2;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
// Handle division by zero
System.out.println("Error: Cannot divide by zero.");
} catch (InputMismatchException e) {
// Handle invalid input
System.out.println("Error: Please enter valid integers.");
} finally {
// Close the scanner
scanner.close();
System.out.println("Scanner closed.");
}
}
}

19
Program 8

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

The Fibonacci series is a sequence of numbers where each number (after the first two) is the
sum of the two preceding ones. The series typically starts with 0 and 1, although some
variations start with 1 and 1. The Fibonacci sequence can be expressed mathematically as
follows:

 F(0)=0F(0) = 0F(0)=0
 F(1)=1F(1) = 1F(1)=1
 F(n)=F(n−1)+F(n−2)F(n) = F(n-1) + F(n-2)F(n)=F(n−1)+F(n−2) for n>1n > 1n>1

A recursive function is a function that calls itself in order to solve a problem. This
technique is useful for breaking down complex problems into simpler subproblems. In
recursion, there are typically two components:

1. Base Case: This stops the recursion and prevents an infinite loop. It returns a value
without making any further recursive calls.
2. Recursive Case: This calls the function itself with a modified argument, moving
towards the base case.

20
Program

import java.util.Scanner;

public class FibonacciSeries {

// Recursive method to calculate Fibonacci


public static int fibonacci(int n) {
if (n <= 1) {
return n; // Base case
}
return fibonacci(n - 1) + fibonacci(n - 2); // Recursive call
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// User input for the last range


System.out.print("Enter the last range (n): ");
int n = scanner.nextInt();

System.out.println("Fibonacci Series from 1 to " + n + ":");


for (int i = 1; i <= n; i++) {
System.out.print(fibonacci(i) + " "); // Print Fibonacci number
}

// Close the scanner


scanner.close();
}
}

21
Program 9

Write a program in Java to perform a single inheritance on two classes.

Inheritance is a fundamental concept in object-oriented programming (OOP) that allows


one class to inherit the properties and methods of another class. It promotes code reusability
and establishes a relationship between classes.

Key Concepts of Inheritance:

Base Class (Parent Class or Superclass):


The class whose properties and methods are inherited by another class.

Derived Class (Child Class or Subclass):


The class that inherits from the base class. It can add new properties and methods or override
existing ones.

Single Inheritance:
A derived class inherits from only one base class.

Method Overriding:
A derived class can provide a specific implementation of a method that is already defined in
its base class.

22
Program
// Base class
class Animal
{
String name;
// Constructor
public Animal(String name)
{
this.name = name;
}
// Method
public String speak() {
return "I am an animal.";
}
}

// Derived class
class Dog extends Animal {
String breed;

// Constructor
public Dog(String name, String breed) {
super(name); // Call the constructor of the base class
this.breed = breed;
}

// Overridden method
@Override
public String speak() {
return "Woof! I am a dog.";
}
}

23
// Main class to test the functionality
public class Main {
public static void main(String[] args)
{
Animal myAnimal = new Animal("Generic Animal");
System.out.println(myAnimal.name); // Output: Generic Animal
System.out.println(myAnimal.speak()); // Output: I am an animal.

Dog myDog = new Dog("Buddy", "Golden Retriever");


System.out.println(myDog.name); // Output: Buddy
System.out.println(myDog.breed); // Output: Golden Retriever
System.out.println(myDog.speak()); // Output: Woof! I am a dog.
}
}

24
Program 10

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

In Java, packages are a way to group related classes and interfaces together

Tpes of Packages

1. Built-in Packages:
o Java comes with several built-in packages, such as:
 java.lang: Contains fundamental classes like String, Math, etc.
 java.util: Contains utility classes like collections, date and time classes,
etc.
 java.io: Contains classes for input and output operations.

2. User-defined Packages:
o Developers can create their own packages to group related classes and
interfaces.

25
Program

We'll create a package called Employee with two classes:


Emp for employee details and payroll calculations, and Emppay for creating an object to
perform calculations and print the values.

Step 1: Create the Package

First, create a directory structure for your package. You can name the root directory as
Employee. Inside this directory, you will create two Java files:

Employee/
Emp.java and Emppay.java.

File 1: Emp.java

package Employee;

public class Emp {


// Variables
private String name;
private int empId;
private String category;
private double bpay; // Basic Pay
private double hra; // House Rent Allowance
private double da; // Dearness Allowance
private double npay; // Net Pay
private double pf; // Provident Fund
private double grossPay;
private double incomeTax; // Income Tax
private double allowance;

// Constructor

public Emp(String name, int empId, String category, double bpay) {


this.name = name;
this.empId = empId;
this.category = category;

26
this.bpay = bpay;
calculatePay();
}

// Method to calculate pays

private void calculatePay() {


hra = 0.30 * bpay; // 30% of basic pay
da = 0.40 * bpay; // 40% of basic pay
grossPay = bpay + hra + da;
pf = 0.12 * grossPay; // Assuming PF is 12% of gross pay
incomeTax = 0.10 * (grossPay - pf); // Assuming 10% income tax on remaining
npay = grossPay - pf - incomeTax; // Net Pay after PF and tax
}

// Method to display employee details and payroll

public void displayPayroll() {


System.out.println("Employee Name: " + name);
System.out.println("Employee ID: " + empId);
System.out.println("Category: " + category);
System.out.printf("Basic Pay: %.2f\n", bpay);
System.out.printf("HRA: %.2f\n", hra);
System.out.printf("DA: %.2f\n", da);
System.out.printf("Gross Pay: %.2f\n", grossPay);
System.out.printf("PF: %.2f\n", pf);
System.out.printf("Income Tax: %.2f\n", incomeTax);
System.out.printf("Net Pay: %.2f\n", npay);
}
}

File 2: Emppay.java

package Employee;

public class Emppay {


public static void main(String[] args)
{
// Creating an employee object
Emp e = new Emp("John Doe", 101, "Developer", 50000);

27
// Displaying payroll information
e.displayPayroll();
}
}

Step 2: Compile and Run the Program

1. Navigate to the directory containing the Employee package.


2. Compile the Java files:
javac Employee/*.java
3. Run the Emppay class:
java Employee.Emppay

28

You might also like