Introduction To Java LAB MANUAL
Introduction To Java LAB MANUAL
Solution :
Method overloading
Polymorphism in Java is a core concept of Object-Oriented Programming (OOP) that allows a single
action to be performed in different ways.
In Java, it typically involves a superclass reference variable referring to a subclass object, enabling flexibility
and code reusability.
Types of Polymorphism
Method Overloading: Occurs when multiple methods inthe same class have thesame name but different
•Note: Java also has internaloperator overloading(e.g., the+operator for both addition and string
This is resolved by the Java Virtual Machine (JVM) at runtime through a process called
MethodOverriding:whenamethodorfunctiondeclaredinderivedclasswhichhasthesamenameandtype
signatureasmethoddeclaredinbasedclass,thenthemethodinthederivedclasssettooverrideamethodinthe
Pseudo Code:
TART
S
1. Create SalaryCalculator class
2. Overload calculateSalary() for three cases with appropriate parameters:
● basicSalary only
● basicSalary + bonus
● basicSalary + bonus + allowance
3. Create a class for the main
4. In main():
Declare three variables
Create an object of the class
Take input for Case1
• Call the appropriate function
• Print formatted results for Case1
Take input for Case2
• Call the appropriate function
• Print formatted results for Case2
Take input for Case3
• Call the appropriate function
• Print formatted results for Case3
STOP
Java Code:
class Salary Calculator {
// Case 1: Regular Employee - Basic Salary only
double calculateSalary(double basicSalary) {
return basicSalary;
}
// Case 3: Employee with Bonus and Allowance - Basic Salary + Bonus + Allowance
double calculateSalary(double basicSalary, double bonus, double allowance) {
return basicSalary + bonus + allowance;
}
Inheritance in Java
Inheritance in Java is a core principle of Object-Oriented Programming (OOP) that allows a new class
(subclassorchildclass)toinheritproperties(fields)andbehaviors(methods)fromanexistingclass(superclass
or parent class).
Pseudo Code:
START
Create a base class Person
Java Code:
Student(String name, int age, String address, String rollNumber, String course) {
super(name, age, address); // Calling parent constructor
[Link] = rollNumber;
[Link] = course;
}
@Override
void displayDetails() {
[Link]("--- Student Details ---");
[Link](); // Calling parent display method
[Link]("Roll Number: " + rollNumber);
[Link]("Course: " + course);
[Link]();
}
}
Faculty(String name, int age, String address, String employeeId, String department) {
super(name, age, address); // Calling parent constructor
[Link] = employeeId;
[Link] = department;
}
@Override
void displayDetails() {
[Link]("--- Faculty Details ---");
[Link](); // Calling parent display method
[Link]("Employee ID: " + employeeId);
[Link]("Department: " + department);
[Link]();
}
}
While Java does not support multiple inheritance with classes, it achieves multiple inheritance of type and
behavior (since Java 8) through theuseofinterfaces.AsingleJavaclasscanimplementmultipleinterfaces,
allowing it to act as multiple different types and adhere to multiple contracts.
How It Works
Java restricts class inheritance to a single parent class to avoid complexity and ambiguity issues like the
"diamond problem". Interfaces resolve this problem because traditionally they only contained method
Theclassthatimplementstheinterfacesisresponsibleforprovidingtheconcreteimplementationforallabstract
Interface in Java
An Interface in Java is an abstract type that defines a set of methods a class must implement.
• Aninterfaceactsasacontractthatspecifieswhataclassshoulddo,butnothowitshoulddoit.Itisusedto
achieve abstraction andmultiple inheritancein Java.
• A class that implements an interface must implement all the methods of the interface. Only variables are
public static final by default.
se a Class when:
U
• Use a class when you need to represent a real-world entity with attributes (fields) and behaviors (methods).
• Use a class when you need to create objects that hold state and perform actions
• Classes are used for defining templates for objects with specific functionality and properties.
Use an Interface when:
• Use an interface when you need to define a contract for behavior that multiple classes can implement.
• Interface is ideal for achieving abstraction and multiple inheritance.
Implementation:To implement an interface, we usethe keywordimplements
Syntax
[access_modifier] interface InterfaceName {
// declare constants (implicitly public static final)
int CONSTANT_NAME = 10;
Java code
// The class OnlineCourse implements both interfaces, achieving a form of multiple inheritance
class OnlineCourse implements VideoContent, Assessment {
private String courseTitle;
// Invoke methods from both interfaces using the OnlineCourse object
[Link]();
[Link]();
Thread Lifecycle
A thread goes through several states during its lifetime, managed by the JVM:
•New: The thread has been created but not yet started.
•Runnable: The thread is ready to run and is waitingfor CPU time from the thread scheduler.
•Blocked/Waiting/Timed Waiting: The thread is temporarilyinactive, waiting for a resource (like a lock) or
Multithreading
Multithreading in Java is a feature that allows multiple threads of executiontorunconcurrentlywithina
single program, maximizing CPU utilization and improving performance. Threads are lightweight
sub-processes that share the samememoryspace,enablingefficientcommunicationandallowingapplications
to remain responsive while performing background tasks.
Creating Threads
ExtendingtheThreadclass:AclasscaninheritfromtheThreadclassandoverrideitsrun()methodtodefine
thetaskthethreadwillexecute.Aninstanceisthencreatedandstartedusingthestart()method,whichcallsthe
run() method in a new thread.
Implementing the Runnable interface: This approach is often preferred as Java does not support multiple
inheritance,soimplementingRunnableallowstheclasstoextendanotherclassifneeded.Therun()methodis
implemented, and aThreadobject is instantiated withtheRunnableinstance and started with start().
When multiple threads access shared data, issues likerace conditionsand data inconsistency can arise.Java
• synchronizedKeyword: Ensures that only one threadcan execute a synchronized method or block of code on
•volatile Keyword: Ensures that changes to a variableare immediately visible to all threads by reading its
•wait(), notify(), notifyAll(): These methods (partof theObjectclass) enable inter-thread communication
within synchronized blocks, allowing threads to coordinate actions and signal each other when conditions are
met.
Example:
[Link]("Thread is running...");
}
}
}
Note:
To prevent race conditions and ensure thread-safe processing of the random numbers, synchronization is
required (e.g., using shared variables, semaphores, or a thread-safe queue). The generator thread notifies the
appropriate consumer thread to process the new data immediately after generation.
Java Code:
import [Link];
// Shared class for communication
class SharedData {
int n;
boolean isEven;
boolean isSet = false;
his program simulates a simple university system that manages student records and
T
demonstrates how different types of exceptions are handled in Java.
1. Input Handling
The program takes student name and marks from the user.
Marks are entered as a string and converted into an integer.
If conversion fails, a NumberFormatException is handled.
2. Custom Exception (InvalidGradeException)
A user-defined exception is created.
It is thrown when marks are outside the valid range (0–100).
This ensures data integrity.
3. Storing Data
Student objects are stored in an array.
Each object contains:
o Name
o Marks
4. Average Calculation
The program calculates the average marks.
If no valid students exist, division by zero may occur.
This is handled using ArithmeticException.
5. Array Access
The program intentionally accesses an invalid index.
This demonstrates handling of ArrayIndexOutOfBoundsException.
6. Null Handling
If any student object is null, accessing its fields causes a NullPointerException.
This is caught and handled safely.
7. File Handling
Algorithm
tep-by-step procedure:
S
1. Start
2. Create a Student class with:
Name
marks
3. Define a custom exception:
InvalidGradeException
4. Create an array to store student objects.
5. Repeat for each student:
Input student name
Input marks as string
Convert string to integer
If invalid → handle NumberFormatException
Check marks range:
If not between 0–100 → throw InvalidGradeException
Store student object in array
6. Initialize variables:
sum = 0
count = 0
7. Traverse student array:
If student is not null:
Add marks to sum
Increment count
8. Calculate average:
average = sum / count
Handle ArithmeticException (if count = 0)
9. Access an invalid index in array:
Handle ArrayIndexOutOfBoundsException
10. Access student object:
Handle NullPointerException
11. Write student data to file:
Open file
Write each student's details
Close file
Handle IOException
12. End program
ode:
C
import [Link].*;
import [Link].*;
// Custom Exception
class InvalidGradeException extends Exception {
public InvalidGradeException(String message) {
super(message);
}
}
// Student Class
class Student {
String name;
int marks;
Student(String name, int marks) {
[Link] = name;
[Link] = marks;
}
}
public class UniversitySystem {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
Student[] students = new Student[3];
try {
// Input student data
for (int i = 0; i < [Link]; i++) {
[Link]("Enter student name: ");
String name = [Link]();
[Link]("Enter marks: ");
String input = [Link]();
int marks;
// Handle NumberFormatException
try {
marks = [Link](input);
} catch (NumberFormatException e) {
[Link]("Invalid number format! Setting marks to 0.");
marks = 0;
}
// Validate marks (Custom Exception)
if (marks < 0 || marks > 100) {
throw new InvalidGradeException("Marks should be between 0 and 100.");
}
students[i] = new Student(name, marks);
}
lternate Version :
A
import [Link].*;
import [Link].*;
// Custom Exception
class InvalidGradeException extends Exception {
public InvalidGradeException(String msg) {
super(msg);
}
}
// Student Class
class Student {
String name;
int marks;
Student(String name, int marks) {
[Link] = name;
[Link] = marks;
}
}
public class UniversitySystemAlt {
// Method to read student data
public static Student readStudent(Scanner sc) {
try {
[Link]("Enter name: ");
String name = [Link]();
[Link]("Enter marks: ");
int marks = [Link]([Link]());
if (marks < 0 || marks > 100) {
throw new InvalidGradeException("Marks must be 0–100");
}
return new Student(name, marks);
} catch (NumberFormatException e) {
[Link]("Invalid number! Default marks = 0");
return new Student("Unknown", 0);
} catch (InvalidGradeException e) {
[Link]([Link]());
return new Student("Invalid", 0);
}
}
// Method to calculate average
public static double calculateAverage(List<Student> list) {
int sum = 0;
for (Student s : list) {
if (s == null) {
riteajavaprogramtocreateanabstractclassnamedshapethatcontainsanemptymethodnamednumberof
W
sides().Providethreeclassesnamedtrapezoid,triangleandHexagonsuchthateachoneoftheclassesextends
the class shape. Each one of the class contains onlythemethodnumberofsides()thatshowsthenumberof
sides in the given geometrical figures.
ey Concept
K
Abstract class = blueprint
Subclasses = provide actual implementation
Achieves runtime polymorphism
lgorithm
A
Step-by-step:
1. Start
2. Create an abstract class Shape
Declare abstract method numberOfSides()
3. Create class Trapezoid extending Shape
Define numberOfSides() → print "4 sides"
4. Create class Triangle extending Shape
Define numberOfSides() → print "3 sides"
5. Create class Hexagon extending Shape
Define numberOfSides() → print "6 sides"
6. In main() method:
Create objects of all three classes
Call numberOfSides() using each object
7. End
ode:
C
abstract class Shape {
// Abstract method
abstract void numberOfSides();
}
// Trapezoid Class
class Trapezoid extends Shape {
void numberOfSides() {
[Link]("Trapezoid has 4 sides");
}
}
// Triangle Class
class Triangle extends Shape {
void numberOfSides() {
[Link]("Triangle has 3 sides");
}
}
// Hexagon Class
class Hexagon extends Shape {
void numberOfSides() {
[Link]("Hexagon has 6 sides");
}
}
// Main Class
public class AbstractDemo {
public static void main(String[] args) {
Shape s1 = new Trapezoid();
Shape s2 = new Triangle();
Shape s3 = new Hexagon();
[Link]();
[Link]();
[Link]();
}
}
Experiment 7
rite a GUI program using Swing and event handlers in Java where:
W
• The user enters a temperature in Celsius or Fahrenheit.
• The user can click a button to convert it to the other scale.
• The result is displayed in the GUI.
• Includes input validation (non-numeric input handled with exception).
his program creates a GUI (Graphical User Interface) using Java Swing to convert
T
temperature between Celsius and Fahrenheit.
Components Used
JFrame → Main window
JLabel → Text labels
JTextField → User input
JButton → Trigger conversion
JComboBox → Select conversion type
JLabel (result) → Display output
Event Handling
Uses ActionListener
When button is clicked:
1. Read input
2. Convert temperature
3. Display result
Exception Handling
If user enters invalid input (like text),
NumberFormatException is handled and error message is shown.
lgorithm
A
1. Start
2. Create a JFrame window
3. Add components:
Label → "Enter Temperature"
TextField → input
ComboBox → select conversion type:
Celsius → Fahrenheit
Fahrenheit → Celsius
Button → "Convert"
Label → result display
4. Add ActionListener to button:
Read input from text field
onvert string → double
C
If invalid → catch NumberFormatException
Check selected option:
If Celsius → Fahrenheit
→ F = (C × 9/5) + 32
If Fahrenheit → Celsius
→ C = (F − 32) × 5/9
Display result
5. Show window
6. End
Code
import [Link].*;
import [Link].*;
import [Link].*;
public class TemperatureConverter extends JFrame implements ActionListener {
JTextField inputField;
JComboBox<String> options;
JLabel resultLabel;
JButton convertButton;
public TemperatureConverter() {
setTitle("Temperature Converter");
setSize(400, 200);
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Components
add(new JLabel("Enter Temperature:"));
inputField = new JTextField(10);
add(inputField);
String[] choices = {
"Celsius to Fahrenheit",
"Fahrenheit to Celsius"
};
options = new JComboBox<>(choices);
add(options);
convertButton = new JButton("Convert");
add(convertButton);
resultLabel = new JLabel("Result: ");
add(resultLabel);
// Event Handling
[Link](this);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
try {
double input = [Link]([Link]());
double result;
if ([Link]() == 0) {
// Celsius to Fahrenheit
result = (input * 9 / 5) + 32;
[Link]("Result: " + result + " °F");
} else {
// Fahrenheit to Celsius
I magine a digital library management system where a librarian interacts with a central record book. In this
scenario, a Java program acts as the librarian, using JDBC as the communication channel to connect to the
database, which represents the record book. Through this connection, the program can perform essential
operationssuchasaddingnewrecords,removingoutdatedentries,updatingexistinginformation,andretrieving
stored data whenever required. This analogy highlights how JDBC enables smoothandorganizedinteraction
between a Java application and a database for complete data management.
I n this system:
Java Program (Librarian) → Handles user requests
JDBC API (Communication Channel) → Connects Java to database
Database (Record Book) → Stores library data
What JDBC Does
JDBC allows a Java program to:
Connect to a database
Insert records (Add books)
Update records (Modify book details)
Delete records (Remove books)
Retrieve records (View books)
Key JDBC Components
Connection → Establish connection
Statement / PreparedStatement → Execute SQL queries
ResultSet → Store retrieved data
lgorithm - Step-by-step:
A
1. Start
2. Load JDBC driver
3. Establish connection to database:
URL, username, password
4. Create SQL operations:
INSERT (Add record)
UPDATE (Modify record)
DELETE (Remove record)
SELECT (Retrieve record)
5. Execute queries using PreparedStatement
6. If SELECT:
Store results in ResultSet
Display data
7 . Handle exceptions (SQLException)
8. Close connection
9. End
Code
import [Link].*;
public class LibraryJDBC {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/library";
String user = "root";
String password = "root";
try {
// 1. Establish Connection
Connection con = [Link](url, user, password);
[Link]("Connected to Database!");
// 2. INSERT (Add Book)
String insertQuery = "INSERT INTO books (id, title) VALUES (?, ?)";
PreparedStatement psInsert = [Link](insertQuery);
[Link](1, 101);
[Link](2, "Java Programming");
[Link]();
// 3. UPDATE (Modify Book)
String updateQuery = "UPDATE books SET title=? WHERE id=?";
PreparedStatement psUpdate = [Link](updateQuery);
[Link](1, "Advanced Java");
[Link](2, 101);
[Link]();
// 4. SELECT (Retrieve Books)
String selectQuery = "SELECT * FROM books";
Statement stmt = [Link]();
ResultSet rs = [Link](selectQuery);
[Link]("Library Records:");
while ([Link]()) {
[Link]([Link]("id") + " - " + [Link]("title"));
}
// 5. DELETE (Remove Book)
String deleteQuery = "DELETE FROM books WHERE id=?";
reparedStatement psDelete = [Link](deleteQuery);
P
[Link](1, 101);
[Link]();
// 6. Close Connection
[Link]();
} catch (SQLException e) {
[Link]("Database Error: " + [Link]());
}
}
}