JAVA PROGRAMMING
LAB MANUAL
Department of Data Science
Anurag University 1 Java Programming Lab(R24)
DEPARTMENT OF DATA SCIENCE
Course Name : Java programming Lab
Course Code : EMA2X16
Course Designation : Professional Core Lab
Credits : 4
Year & Sem : II [Link] & II Sem
Course Coordinator
Mr R. SivaKumar
Assistant Professor, Dept. of Data ScienceAU, Hyderabad.
Course Instructors
Mr [Link],Mrs. Shanthi Priya, [Link] Chander
Assistant Professor, Dept. of Data ScienceAU, Hyderabad
Anurag University 2 Java Programming Lab(R24)
DEPARTMENT OF DATA SCIENCE
INDEX
S. No Content Page
Number
1 University Vision & Mission 6
2 Department Vision & Mission 7
3 Programme Educational Objectives (PEO’s) 8
4 Programme Outcomes (PO’s) 9
5 Programme Specific Outcomes (PSOs) 11
6 Course Outcomes (COs) & CO-PO & PSO Articulation Matrix 12
7 Syllabus 13
1) Programs can be created to demonstratefundamental
concepts of Java programming, such as data types, variables,
8 16
operators and control structures.
2 a) Write a program that demonstrates the scope of variables
inside different methods. Define a variable x inside the
main( ) method and try to access it inside a different
method. Illustrate what happens when you try to access a
variable from a different scope.
b) Write a Java program that demonstrates the difference
between instance variables and local variables in terms of
scope and lifetime. Create a method that uses both an
instance variable and a local variable. Show how they
9 21
behave differently when the method is called multiple
times.
i)Create an instance variable name and a local variable
name inside a method.
ii)Call the method twice, once with a value assigned to the
local variable and once with the instance variable modified.
iii)Output the value of the variables after each call and
explain the scope and lifetime of both types of variables.
Anurag University 3 Java Programming Lab(R24)
10 3) Create an Employee Management System to manage 21
employee records. Use constructors to initialize employee
details and this keyword to distinguish between instance
variables and parameters.
a) Add new employees with attributes like name, ID, department, and
salary.
b)Display employee details.
c) Update employee attributes (e.g., salary or department).
11 4)Write a program to maintain employee details with following 24
requirements
a)To maintain a shared count of the total number of employees created
b) To define static utility methods for operations such as
displaying company name or validating employee details.
12 5)Write a program to implement employee details with following 27
requirements
a)Create an abstract class Employee that serves as
the base class for all employee types. The
Employee class should include:
Instance variables such as name, id, designation, and salary.
Abstract methods like calculateSalary( ) and
displayDetails( ) to enforce specific behavior in
subclasses.
A constructor to initialize common employee attributes using this
keyword.
b)Extend the Employee class into specialized subclasses like Manager
and Developer.
Use the super keyword in the subclasses to call the base class constructor
and methods.
13 Skill test-1
14 7)Write a program to organize the system into logical packages such as: 29
entities: For classes like Employee, Manager, and Department.
services: For operations like payroll calculation and performance
evaluation.
Utilities: For helper classes, such as input validation or logging.
15 8)Write a program to create domain-specific exception 33
classes (e.g., InvalidEmployeeIDException,
SalaryOutOfRangeException) to handle specific errors
related to employee data management.
16 9)Implement a multi-threaded producer-consumer system 37
using shared resources such as a queue or buffer.
Producers generate data and place it in a shared queue.
Anurag University 4 Java Programming Lab(R24)
Consumers retrieve data from the queue and process it.
Use wait ( ) and notifyAll( ) for synchronization.
Implement with bounded and unbounded buffer versions.
17 10)Develop Calculator Application: 40
Basic arithmetic operations (addition, subtraction, multiplication,
division).
A responsive GUI with buttons for numbers and operations.
Event handling with ActionListener.
Layout managers like GridLayout
18 11)a) Insert Data: 45
Develop functionality to insert employee records (e.g., name, position,
department, salary, hire date) into an Oracle database.
Ensure that data is secure, accurate, and prevents data duplication or
inconsistencies.
Retrieve Data:
Implement a feature to query and retrieve employee
information from the Oracle database based on criteria such
as employee ID, department, or salary range.
19 12)Develop an application in Java that demonstrates the 49
handling of both mouse and keyboard events. The application
should feature a graphical user interface (GUI) that responds
dynamically to user interactions.
20 13)Programs that demonstrate the layout managers using 54
JFrame
21 14) Review and Skill Test-2 58
Anurag University 5 Java Programming Lab(R24)
DEPARTMENT OF DATA SCIENCE
University Vision & Mission
Vision:
To be a leading university that provides transformative education and research to create
leaders and innovators of tomorrow and to expand frontiers of knowledge for the betterment of
society.
Mission:
● To prepare students to think creatively, broadly, critically and create an ecosystem for
innovation and entrepreneurship from which the leaders and innovators of tomorrow
emerge.
● To create an interdisciplinary ambience to understand and solve real-world problems
thereby contributing to the growth of the nation and humanity.
● To build relationship with industry, research organizations and academia to strengthen the
ecosystem.
Anurag University 6 Java Programming Lab(R24)
DEPARTMENT OF DATA SCIENCE
Department Vision & Mission
Vision:
To provide an environment for academic excellence in the field of Data Science and
prepare the students for the data centric world.
Mission:
M1: To achieve academic excellence by imparting highest quality data science education to the
students through effective Teaching Learning Process.
M2: To promote data-intensive research and encourage students to collaborate and innovate that
will serve the needs of the global community.
M3: To enhance industry–institute collaborations that will help the graduates to emerge as leaders
in academics/ entrepreneurship.
M4: To prepare students to be continuous learners and imbibe moral and ethical responsibilities
in them.
Anurag University 7 Java Programming Lab(R24)
DEPARTMENT OF DATA SCIENCE
Programme Educational Objectives (PEO’s)
PEOs:
PEO 1: Graduate are successful in their profession with strong basics in engineering, science, and
technology.
PEO 2: Graduates be able to analyze, design and develop Data science based solutions for real
world problems.
PEO 3: Be able to work productively in supportive and leadership roles on multidisciplinary
teams with effective communication and team work skills with high regard to legal and ethical
responsibilities.
PEO 4: Be able to embrace lifelong learning to meet ever changing developments in a data-centric
world.
Anurag University 8 Java Programming Lab(R24)
DEPARTMENT OF DATA SCIENCE
Programme Outcomes (PO’s):
PO1: Engineering Knowledge: Apply knowledge of mathematics, natural science, computing,
engineering fundamentals and an engineering specialization as specified in WK1 to WK4
respectively to develop to the solution of complex engineering problems.
PO2: Problem Analysis: Identify, formulate, review research literature and analyze complex
engineering problems reaching substantiated conclusions with consideration for sustainable
development. (WK1 to WK4)
PO3: Design/Development of Solutions: Design creative solutions for complex engineering
problems and design/develop systems/components/processes to meet identified needs with
consideration for the public health and safety, whole-life cost, net zero carbon, culture, society
and environment as required. (WK5)
PO4: Conduct Investigations of Complex Problems: Conduct investigations of complex
engineering problems using research-based knowledge including design of experiments,
modelling, analysis & interpretation of data to provide valid conclusions. (WK8).
PO5: Engineering Tool Usage: Create, select and apply appropriate techniques, resources and
modern engineering & IT tools, including prediction and modelling recognizing their limitations
to solve complex engineering problems. (WK2 and WK6)
PO6: The Engineer and The World: Analyze and evaluate societal and environmental aspects
while solving complex engineering problems for its impact on sustainability with reference to
economy, health, safety, legal framework, culture and environment. (WK1, WK5, and WK7).
PO7: Ethics: Apply ethical principles and commit to professional ethics, human values, diversity
and inclusion; adhere to national & international laws. (WK9)
PO8: Individual and Collaborative Team work: Function effectively as an individual, and as
a member or leader in diverse/multi-disciplinary teams.
PO9: Communication: Communicate effectively and inclusively within the engineering
community and society at large, such as being able to comprehend and write effective reports and
Anurag University 9 Java Programming Lab(R24)
design documentation, make effective presentations considering cultural, language, and learning
differences
PO10: Project Management and Finance: Apply knowledge and understanding of engineering
management principles and economic decision-making and apply these to one’s own work, as a
member and leader in a team, and to manage projects and in multidisciplinary environments.
PO11: Life-Long Learning: Recognize the need for, and have the preparation and ability for i)
independent and life-long learning ii) adaptability to new and emerging technologies and iii)
critical thinking in the broadest context of technological change. (WK8)
Anurag University 10 Java Programming Lab(R24)
DEPARTMENT OF DATA SCIENCE
Programme Specific Outcomes (PSOs)
PSO1: The ability to understand, analyze, build and assess data-based models.
PSO2: The ability to apply data science concepts and methods to solve problems in real-world
contexts
PSO3: Able to independently carry out research/investigation to solve practical problems
Anurag University 11 Java Programming Lab(R24)
DEPARTMENT OF DATA SCIENCE
Course Outcomes (COs):
After completing the Java Programming Lab Course Students will be able to
1. Implement variable handling, classes, objects, including memory management.
2. Apply inheritance, polymorphism, interfaces, and packages to design modular and
reusable Java applications.
3. Examine the use of exceptions for error handling and analyze data management
strategies using the Collection Framework.
4. Implement graphical user interfaces (GUIs) using Swing components.
5. Analyze GUI structure using layout managers and evaluate user interaction handling
through the event delegation model.
Articulation matrix of Course outcomes with PO’s & PSO’s:
Program Specific
Program Outcome’s
COs Outcome’s
PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PSO1 PSO2 PSO3
CO1
3 2 2 1 3 - - 1 2 - 2 3 2 -
3 2 2 1 3 - - 1 1 - 2 3 2 -
CO2
3 3 2 2 3 - - 1 2 - 2 3 3 2
CO3
CO4
3 3 2 2 3 - - 2 2 1 2 3 3 2
CO5
3 2 2 2 3 - - 1 2 - 2 3 3 2
Anurag University 12 Java Programming Lab(R24)
DEPARTMENT OF DATA SCIENCE
Syllabus:
Week 1
1) Programs can be created to demonstrate fundamental concepts of Java programming, such as data
types, variables, operators and control structures.
Week 2
2) a. Write a program that demonstrates the scope of variables inside different methods. Define a
variable x inside the main( ) method and try to access it inside a different method. Illustrate what
happens when you try to access a variable from a different scope.
b) Write a Java program that demonstrates the difference between instance variables and local
variables in terms of scope and lifetime. Create a method that uses both an instance variable and a
local variable. Show how they behave differently when the method is called multiple times. i)
Create an instance variable name and a local variable name inside a method. ii) Call the method
twice, once with a value assigned to the local variable and once with the instance variable
modified.
iii) Output the value of the variables after each call and explain the scope and lifetime of both types of
variables.
Week 3
3) Create an Employee Management System to manage employee records. Use constructors to
initialize employee details and this keyword to distinguish between instance variables and parameters.
a) Add new employees with attributes like name, ID, department, and salary.
b) Display employee details.
c) Update employee attributes (e.g., salary or department).
Week 4
3) Write a program to maintain employee details with following requirements
a) To maintain a shared count of the total number of employees created
b) To define static utility methods for operations such as displaying company name or validating
employee details.
Week 5
3) Write a program to implement employee details with following requirements
Anurag University 13 Java Programming Lab(R24)
a) Create an abstract class Employee that serves as the base class for all employee types.
The Employee class should include:
• Instance variables such as name, id, designation, and salary.
• Abstract methods like calculateSalary( ) and displayDetails( ) to enforce specific behavior in
subclasses.
• A constructor to initialize common employee attributes using this keyword.
b) Extend the Employee class into specialized subclasses like Manager and Developer.
• Use the super keyword in the subclasses to call the base class constructor and methods.
Week 6
Review and Skill Test-I
Week 7
7) Write a program to organize the system into logical packages such as:
• entities: For classes like Employee, Manager, and Department.
• services: For operations like payroll calculation and performance evaluation.
• Utilities: For helper classes, such as input validation or logging.
Week 8
8).Write a program to create domain-specific exception classes (e.g., InvalidEmployeeIDException,
SalaryOutOfRangeException) to handle specific errors related to employee data management.
Week 9
9).Implement a multi-threaded producer-consumer system using shared resources such as a queue or
buffer.
• Producers generate data and place it in a shared queue.
• Consumers retrieve data from the queue and process it.
• Use wait ( ) and notifyAll( ) for synchronization.
• Implement with bounded and unbounded buffer versions.
Week 10
10).Develop Calculator Application:
• Basic arithmetic operations (addition, subtraction, multiplication, division).
• A responsive GUI with buttons for numbers and operations. Event handling with
ActionListener.
• Layout managers like GridLayout
Week 11
11 a) Insert Data:
• Develop functionality to insert employee records (e.g., name, position, department, salary, hire
date) into an Oracle database.
• Ensure that data is secure, accurate, and prevents data duplication or inconsistencies. b)
Retrieve Data:
Anurag University 14 Java Programming Lab(R24)
• Implement a feature to query and retrieve employee information from the Oracle database
based on criteria such as employee ID, department, or salary range.
Week 12
12) Develop an application in Java that demonstrates the handling of both mouse and keyboard
events. The application should feature a graphical user interface (GUI) that responds dynamically to user
interactions.
Week 13
13)Programs that demonstrate the layout managers using JFrame.
Week 14
Review and Skill Test-2
Anurag University 15 Java Programming Lab(R24)
WEEK:1
1) Programs can be created to demonstrate fundamental concepts of Java
programming, such as data types, variables, operators and control
structures.
package week1;
public class ArrayDemo {
public static void main(String[] args) {
// Array of integers
int[] numbers = {1, 2, 3, 4, 5};
// Loop through the array and print each number
for (int i = 0; i < [Link]; i++) {
[Link]("Element at index " + i + ": " + numbers[i]);
}
}
}
OUTPUT:
ControlStructuresDemo:
package week1;
public class ControlStructuresDemo {
public static void main(String[] args) {
int age = 20;
// If-else statement
if (age >= 18) {
[Link]("You are an adult.");
Anurag University 16 Java Programming Lab(R24)
} else {
[Link]("You are a minor.");
}
// Switch statement
String day = "Monday";
switch (day) {
case "Monday":
[Link]("Start of the week!");
break;
case "Friday":
[Link]("It's almost weekend!");
break;
default:
[Link]("Just another day.");
break;
}
}
}
OUTPUT:
DataTypesDemo:
package week1;
public class DataTypesDemo {
public static void main(String[] args) {
// Integer variable
int number = 10;
// Double (floating-point) variable
double price = 19.99;
// Boolean variable
boolean isActive = true;
// Character variable
char grade = 'A';
Anurag University 17 Java Programming Lab(R24)
// String variable
String message = "Hello, Java!";
// Output
[Link]("Number: " + number);
[Link]("Price: " + price);
[Link]("Is Active: " + isActive);
[Link]("Grade: " + grade);
[Link]("Message: " + message);
}
}
OUTPUT:
ForLoopDemo:
package week1;
public class ForLoopDemo {
public static void main(String[] args) {
// Looping through numbers from 1 to 5
for (int i = 1; i <= 5; i++) {
[Link]("Iteration: " + i);
}
}
}
OUTPUT:
Anurag University 18 Java Programming Lab(R24)
OperatorsDemo:
package week1;
public class OperatorsDemo {
public static void main(String[] args) {
int a = 5, b = 3;
// Arithmetic Operators
int sum = a + b;
int difference = a - b;
int product = a * b;
int quotient = a / b;
int remainder = a % b;
// Relational Operator
boolean isEqual = (a == b);
// Logical Operators
boolean isBothTrue = (a > 2) && (b < 5);
// Output
[Link]("Sum: " + sum);
[Link]("Difference: " + difference);
[Link]("Product: " + product);
[Link]("Quotient: " + quotient);
[Link]("Remainder: " + remainder);
[Link]("Are a and b equal? " + isEqual);
[Link]("Is both conditions true? " + isBothTrue);
}
}
OUTPUT:
Anurag University 19 Java Programming Lab(R24)
WhileLoopDemo:
package week1;
public class WhileLoopDemo {
public static void main(String[] args) {
int i = 1;
// While loop that runs until i is less than or equal to 5
while (i <= 5) {
[Link]("Iteration: " + i);
i++; // Increment i by 1
}
}
}
OUTPUT:
Anurag University 20 Java Programming Lab(R24)
WEEK:2
a) Write a program that demonstrates the scope of variables inside
different methods. Define a variable x inside the main( ) method and try to
access it inside a different method. Illustrate what happens when you try
to access a variable from a different scope.
package week2;
public class ScopeDemo {
public static void main(String[] args) {
int x = 10; // Local variable inside main()
[Link]("Value of x inside main(): " + x);
// Trying to access x inside another method
display();
}
public static void display() {
// Uncommenting the next line will cause a compile-time error
// [Link]("Trying to access x inside display(): " + x);
[Link]("Cannot access variable x here because x is local to main()");
}
}
OUTPUT:
Anurag University 21 Java Programming Lab(R24)
b) Write a Java program that demonstrates the difference between
instance variables and local variables in terms of scope and lifetime.
Create a method that uses both an instance variable and a local variable.
Show how they behave differently when the method is called multiple
times. i) Create an instance variable name and a local variable name inside
a method. ii) Call the method twice, once with a value assigned to the local
variable and once with the instance variable modified.
iii) Output the value of the variables after each call and explain the scope
and lifetime of both types of variables.
package week2;
public class VariableScopeDemo {
// Instance variable (class-level variable)
String name;
// Method that uses both instance variable and local variable
public void showNames() {
// Local variable (method-level variable)
String name = "Local Name"; // Initially set to "Local Name"
// Output the values of the local and instance variables
[Link]("Inside showNames method:");
[Link]("Local Variable name: " + name); // This will print the local
variable
[Link]("Instance Variable name: " + [Link]); // This will print the
instance variable
}
public static void main(String[] args) {
// Creating an object of the class
VariableScopeDemo obj = new VariableScopeDemo();
// i) First call: Local variable assigned to "Local Name", instance variable is null by
default
[Link]("=== First Call ===");
[Link](); // Local variable is "Local Name", instance variable is default (null)
// Modify the instance variable
[Link] = "Instance Name Modified"; // Changing the instance variable
// ii) Second call: Instance variable is modified, but local variable will be "Local Name"
again
[Link]("\n=== Second Call ===");
Anurag University 22 Java Programming Lab(R24)
[Link](); // Local variable is still "Local Name", but instance variable has
been modified
// iii) Output is printed above, and below is the explanation
}
}
OUTPUT:
Anurag University 23 Java Programming Lab(R24)
WEEK:3
Create an Employee Management System to manage employee records. Use
constructors to initialize employee details and this keyword to distinguish
between instance variables and parameters. a) Add new employees with
attributes like name, ID, department, and salary.
package week3;
class EmployeeAdd {
int id;
String name;
String department;
double salary;
EmployeeAdd(int id, String name, String department, double salary) {
[Link] = id;
[Link] = name;
[Link] = department;
[Link] = salary;
}
}
public class AddEmployee {
public static void main(String[] args) {
EmployeeAdd e1 = new EmployeeAdd(101, "John", "IT", 50000);
EmployeeAdd e2 = new EmployeeAdd(102, "Sara", "HR", 45000);
[Link]("Employees added successfully.");
}
}
OUTPUT:
b) Display employee details.
package week3;
class EmployeeDisplay {
Anurag University 24 Java Programming Lab(R24)
int id;
String name;
String department;
double salary;
EmployeeDisplay(int id, String name, String department, double salary) {
[Link] = id;
[Link] = name;
[Link] = department;
[Link] = salary;
}
void display() {
[Link](id + " " + name + " " + department + " " + salary);
}
}
public class DisplayEmployee {
public static void main(String[] args) {
EmployeeDisplay e1 = new EmployeeDisplay(101, "John", "IT", 50000);
EmployeeDisplay e2 = new EmployeeDisplay(102, "Sara", "HR", 45000);
[Link]();
[Link]();
}
}
OUTPUT:
c). Update employee attributes (e.g., salary or department).
package week3;
class EmployeeUpdate {
int id;
String name;
String department;
double salary;
EmployeeUpdate(int id, String name, String department, double salary) {
Anurag University 25 Java Programming Lab(R24)
[Link] = id;
[Link] = name;
[Link] = department;
[Link] = salary;
}
void updateSalary(double newSalary) {
[Link] = newSalary;
}
void updateDepartment(String newDept) {
[Link] = newDept;
}
void display() {
[Link](id + " " + name + " " + department + " " + salary);
}
}
public class UpdateEmployee {
public static void main(String[] args) {
EmployeeUpdate e1 = new EmployeeUpdate(101, "John", "IT", 50000);
[Link](60000);
[Link]("Finance");
[Link]();
}
}
OUTPUT:
Anurag University 26 Java Programming Lab(R24)
WEEK:4
Write a program to maintain employee details with following requirements
a) To maintain a shared count of the total number of employees created
package week4;
class EmployeeCount {
static int count = 0; // shared counter
String name;
EmployeeCount(String name) {
[Link] = name;
count++; // increase count every time new employee is created
}
void show() {
[Link]("Employee Name: " + name);
}
}
public class TotalEmployees {
public static void main(String[] args) {
EmployeeCount e1 = new EmployeeCount("John");
EmployeeCount e2 = new EmployeeCount("Sara");
EmployeeCount e3 = new EmployeeCount("Mike");
[Link]("Total Employees Created: " + [Link]);
}
}
OUTPUT:
Anurag University 27 Java Programming Lab(R24)
b) To define static utility methods for operations such as displaying company
name or validating employee details.
package week4;
class EmployeeUtil {
static void showCompanyName() {
[Link]("Company: ABC Technologies");
}
static boolean validateName(String name) {
return name != null && ![Link]();
}
}
public class EmployeeUtilityDemo {
public static void main(String[] args) {
[Link]();
// Validating employee name
if ([Link]("John")) {
[Link]("Name is valid");
} else {
[Link]("Invalid name");
}
}
}
OUTPUT:
Anurag University 28 Java Programming Lab(R24)
WEEK:5
Write a program to implement employee details with following requirements
a) Create an abstract class Employee that serves as the base class for all
employee types.
The Employee class should include:
• Instance variables such as name, id, designation, and salary.
• Abstract methods like calculateSalary( ) and displayDetails( ) to enforce
specific behavior in subclasses.
• A constructor to initialize common employee attributes using this keyword.
package week5;
abstract class EmployeeSuper {
String name;
int id;
String designation;
double salary;
EmployeeSuper(String name, int id, String designation, double salary) {
[Link] = name;
[Link] = id;
[Link] = designation;
[Link] = salary;
}
abstract void calculateSalary();
abstract void displayDetails();
}
class Manager extends EmployeeSuper {
Manager(String name, int id, double salary) {
super(name, id, "Manager", salary);
}
void calculateSalary() {
salary += 5000; // Manager allowance
}
void displayDetails() {
[Link](id + " " + name + " " + designation + " " + salary);
}
}
class Developer extends EmployeeSuper {
Developer(String name, int id, double salary) {
super(name, id, "Developer", salary);
}
Anurag University 29 Java Programming Lab(R24)
void calculateSalary() {
salary += 3000; // Developer bonus
}
void displayDetails() {
[Link](id + " " + name + " " + designation + " " + salary);
}
}
public class EmployeeSystemDemo {
public static void main(String[] args) {
Manager m = new Manager("John", 101, 50000);
Developer d = new Developer("Sara", 102, 40000);
[Link]();
[Link]();
[Link]();
[Link]();
}
}
OUTPUT:
Anurag University 30 Java Programming Lab(R24)
b) Extend the Employee class into specialized subclasses like Manager and
Developer.
• Use the super keyword in the subclasses to call the base class constructor and
methods.
package week5;
//Abstract class Employee
abstract class Employee {
String name;
int id;
String designation;
double salary;
Employee(String name, int id, String designation, double salary) {
[Link] = name;
[Link] = id;
[Link] = designation;
[Link] = salary;
}
abstract double calculateSalary();
abstract void displayDetails();
}
//Manager subclass
class Manager extends Employee {
Manager(String name, int id, double salary) {
super(name, id, "Manager", salary); // call base constructor
}
double calculateSalary() {
return salary + 5000; // bonus
}
void displayDetails() {
[Link]("Name: " + name + ", ID: " + id);
[Link]("Designation: " + designation);
[Link]("Total Salary: " + calculateSalary());
}
}
//Developer subclass
class Developer extends Employee {
Developer(String name, int id, double salary) {
super(name, id, "Developer", salary); // call base constructor
}
Anurag University 31 Java Programming Lab(R24)
double calculateSalary() {
return salary + 3000; // allowance
}
void displayDetails() {
[Link]("Name: " + name + ", ID: " + id);
[Link]("Designation: " + designation);
[Link]("Total Salary: " + calculateSalary());
}
}
//Main class
public class Main {
public static void main(String[] args) {
Manager m = new Manager("Alice", 101, 60000);
Developer d = new Developer("Bob", 102, 50000);
[Link]();
[Link]();
[Link]();
}
}
OUTPUT:
Anurag University 32 Java Programming Lab(R24)
WEEK 7:
Write a program to organize the system into logical packages such as:
(a)entities: For classes like Employee, Manager, and Department.
(b)services: For operations like payroll calculation and performance
evaluation.
(c)Utilities: For helper classes, such as input validation or logging.
entities: For classes like Employee, Manager, and Department.
Employee:
package entities;
public class Employee {
protected String name;
protected int id;
protected double salary;
public Employee() {
// default constructor
}
public Employee(String name, int id, double salary) {
[Link] = name;
[Link] = id;
[Link] = salary;
}
public void display() {
[Link]("Name: " + name);
[Link]("ID: " + id);
[Link]("Salary: " + salary);
}
public String getName() { return name; }
public int getId() { return id; }
public double getSalary() { return salary; }
}
Manager:
package entities;
public class Manager extends Employee{
private String department;
public Manager(String name, int id, double salary, String department) {
super(name, id, salary);
[Link] = department;
Anurag University 33 Java Programming Lab(R24)
}
@Override
public void display() {
[Link]();
[Link]("Department: " + department);
}
Department:
package entities;
public class Department {
public String deptName;
public Department(String deptName) {
[Link] = deptName;
}
public void showDept() {
[Link]("Department Name: " + deptName);
}
b) services: For operations like payroll calculation and performance
evaluation.
Payroll Calculation:
package services;
import [Link];
public class PayrollService {
public double calculateBonus(Employee emp) {
return [Link]() * 0.10; // 10% bonus
}
Anurag University 34 Java Programming Lab(R24)
Performance Evaluation:
package services;
import [Link];
public class PerformanceEvaluation {
public void evaluate(Employee emp) {
if ([Link]() > 50000) {
[Link]([Link]() + " has Excellent Performance");
} else {
[Link]([Link]() + " has Good Performance");
}
}
}
c)Utilities: For helper classes, such as input validation or logging.
InputValidation:
package utilities;
public class InputValidator {
public static boolean isValidSalary(double salary) {
return salary > 0;
}
}
Logger:
package utilities;
public class Logger {
public static void log(String message) {
[Link]("[LOG]: " + message);
}
}
Anurag University 35 Java Programming Lab(R24)
MainTest:
package week7;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class MainTest {
public static void main(String[] args) {
[Link]("Creating Manager object...");
Manager m = new Manager("Soumya", 101, 60000, "IT");
if ([Link]([Link]())) {
[Link]();
}
PayrollService payroll = new PayrollService();
double bonus = [Link](m);
[Link]("Bonus: " + bonus);
PerformanceEvaluation eval = new PerformanceEvaluation();
[Link](m);
}
}
Output:
Anurag University 36 Java Programming Lab(R24)
WEEK 8:
Write a program to create domain-specific exception classes (e.g.,
InvalidEmployeeIDException, SalaryOutOfRangeException) to handle
specific errors related to employee data management.
Create a Package:
DomainSpecificExceptionDemo
package [Link];
public class DomainSpecificExceptionDemo {
public static void main(String[] args) {
try {
Employee e1 = new Employee("EMP123", 35000);
[Link]();
Employee e2 = new Employee("E123", 30000); // Invalid ID
}
catch (InvalidEmployeeIDException | SalaryOutOfRangeException e) {
[Link]("Error: " + [Link]());
}
try {
Employee e3 = new Employee("EMP200", 500000); // Salary too high
}
catch (InvalidEmployeeIDException | SalaryOutOfRangeException e) {
[Link]("Error: " + [Link]());
}
}
}
Anurag University 37 Java Programming Lab(R24)
InvalidEmployeeIDException:
package [Link];
public class InvalidEmployeeIDException extends Exception {
public InvalidEmployeeIDException(String message) {
super(message);
}
}
SalaryOutOfRangeException:
package [Link];
public class SalaryOutOfRangeException extends Exception {
public SalaryOutOfRangeException(String message) {
super(message);
}
}
Employee:
package [Link];
public class Employee {
private String empID;
private double salary;
public Employee(String empID, double salary)
throws InvalidEmployeeIDException, SalaryOutOfRangeException {
setEmpID(empID);
Anurag University 38 Java Programming Lab(R24)
setSalary(salary);
}
public void setEmpID(String empID) throws InvalidEmployeeIDException {
if (empID == null || ) {
throw new InvalidEmployeeIDException("Employee ID must be in format
EMPXXX (e.g., EMP101)");
}
[Link] = empID;
}
public void setSalary(double salary) throws SalaryOutOfRangeException {
if (salary < 10000 || salary > 100000) {
throw new SalaryOutOfRangeException("Salary must be between 10,000 and
100,000");
}
[Link] = salary;
}
public void display() {
[Link]("Employee ID: " + empID);
[Link]("Salary: " + salary);
}
}
Output:
Anurag University 39 Java Programming Lab(R24)
WEEK 9:
Implement a multi-threaded producer-consumer system using
shared resources such as a queue or buffer.
Producers generate data and place it in a shared queue.
Consumers retrieve data from the queue and process it.
Use wait ( ) and notify All( ) for synchronization.
Implement with bounded and unbounded buffer versions.
ProducerConsumerBounded:
package w9;
import [Link];
import [Link];
class BoundedBuffer {
private final Queue<Integer> queue = new LinkedList<>();
private final int capacity;
BoundedBuffer(int capacity) {
[Link] = capacity;
}
public synchronized void produce(int value) throws InterruptedException {
while ([Link]() == capacity) {
[Link]("Buffer Full! Producer waiting...");
wait();
}
[Link](value);
[Link]("Produced: " + value + " | Buffer size: " + [Link]());
notifyAll();
}
public synchronized int consume() throws InterruptedException {
while ([Link]()) {
[Link]("Buffer Empty! Consumer waiting...");
wait();
}
int value = [Link]();
[Link]("Consumed: " + value + " | Buffer size: " + [Link]());
notifyAll();
return value;
}
}
class ProducerB implements Runnable {
private final BoundedBuffer buffer;
private volatile boolean running = true;
Anurag University 40 Java Programming Lab(R24)
ProducerB(BoundedBuffer buffer) { [Link] = buffer; }
public void shutdown() { running = false; }
@Override
public void run() {
int value = 1;
try {
while (running) {
[Link](value++);
[Link](400);
}
} catch (InterruptedException e) {
// thread interrupted: exit run
}
[Link]("Producer stopped.");
}
}
class ConsumerB implements Runnable {
private final BoundedBuffer buffer;
private volatile boolean running = true;
ConsumerB(BoundedBuffer buffer) { [Link] = buffer; }
public void shutdown() { running = false; }
@Override
public void run() {
try {
while (running) {
[Link]();
[Link](600);
}
} catch (InterruptedException e) {
// exit
}
[Link]("Consumer stopped.");
}
}
public class ProducerConsumerBounded {
public static void main(String[] args) throws InterruptedException {
BoundedBuffer buffer = new BoundedBuffer(5);
ProducerB producerRunnable = new ProducerB(buffer);
ConsumerB consumerRunnable = new ConsumerB(buffer);
Thread producer = new Thread(producerRunnable, "Producer-Thread");
Thread consumer = new Thread(consumerRunnable, "Consumer-Thread");
Anurag University 41 Java Programming Lab(R24)
[Link]();
[Link]();
// Run for 10 seconds then stop cleanly (example)
[Link](10000);
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
[Link]("Main finished.");
}
}
ProducerConsumerUnbounded:
import [Link];
import [Link];
class SharedQueue {
private final Queue<Integer> queue = new LinkedList<>();
public synchronized void produce(int value) {
[Link](value);
[Link]("Produced: " + value + " | Buffer size: " + [Link]());
notifyAll();
}
public synchronized int consume() throws InterruptedException {
while ([Link]()) {
wait();
}
int value = [Link]();
[Link]("Consumed: " + value + " | Buffer size: " + [Link]());
return value;
}
}
class Producer implements Runnable {
private final SharedQueue shared;
private volatile boolean running = true;
Producer(SharedQueue shared) { [Link] = shared; }
public void shutdown() { running = false; }
@Override
public void run() {
Anurag University 42 Java Programming Lab(R24)
int value = 1;
try {
while (running) {
[Link](value++);
[Link](500);
}
} catch (InterruptedException e) {}
[Link]("Producer stopped.");
}
}
class Consumer implements Runnable {
private final SharedQueue shared;
private volatile boolean running = true;
Consumer(SharedQueue shared) { [Link] = shared; }
public void shutdown() { running = false; }
@Override
public void run() {
try {
while (running) {
[Link]();
[Link](700);
}
} catch (InterruptedException e) {}
[Link]("Consumer stopped.");
}
}
public class ProducerConsumerUnbounded {
public static void main(String[] args) throws InterruptedException {
SharedQueue shared = new SharedQueue();
Producer p = new Producer(shared);
Consumer c = new Consumer(shared);
Thread pt = new Thread(p, "Producer");
Thread ct = new Thread(c, "Consumer");
[Link](); [Link]();
[Link](10000);
[Link](); [Link]();
[Link](); [Link]();
[Link](); [Link]();
[Link]("Done.");
}
}
Anurag University 43 Java Programming Lab(R24)
Output:
Anurag University 44 Java Programming Lab(R24)
WEEK 10:
Develop Calculator Application:
Basic arithmetic operations (addition, subtraction, multiplication, division).
A responsive GUI with buttons for numbers and operations.
Event handling with ActionListener.
Layout managers like GridLayout
Step 1:Create a Package in eclipse calculator
Step 2:Create a class with in the package with the name CalculatorGUI
[Link]:
package calculator;
import [Link].*;
import [Link].*;
import [Link].*;
public class CalculatorGUI extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JTextField display;
private String operator = "";
private double num1 = 0, num2 = 0;
public CalculatorGUI() {
// Frame settings
setTitle("Simple Calculator");
setSize(300, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
// Display Field
display = new JTextField();
Anurag University 45 Java Programming Lab(R24)
[Link](false);
[Link](new Font("Arial", [Link], 24));
add(display, [Link]);
// Buttons panel with GridLayout
JPanel panel = new JPanel();
[Link](new GridLayout(4, 4, 5, 5));
String buttons[] = {
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"0", "C", "=", "+"
};
for (String text : buttons) {
JButton btn = new JButton(text);
[Link](new Font("Arial", [Link], 20));
[Link](this); // EVENT HANDLER
[Link](btn);
}
add(panel);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
String btnText = [Link]();
if ([Link]("[0-9]")) { // number clicked
[Link]([Link]() + btnText);
}
else if ([Link]("[+\\-*/]")) { // operator clicked
Anurag University 46 Java Programming Lab(R24)
num1 = [Link]([Link]());
operator = btnText;
[Link]("");
}
else if ([Link]("=")) {
num2 = [Link]([Link]());
double result = 0;
switch (operator) {
case "+": result = num1 + num2; break;
case "-": result = num1 - num2; break;
case "*": result = num1 * num2; break;
case "/": result = num2 != 0 ? num1 / num2 : 0; break;
}
[Link]([Link](result));
}
else if ([Link]("C")) { // clear
[Link]("");
num1 = num2 = 0;
operator = "";
}
}
public static void main(String[] args) {
new CalculatorGUI();
}
}
Anurag University 47 Java Programming Lab(R24)
Output:
Anurag University 48 Java Programming Lab(R24)
WEEK 11:
a)Insert Data:
Develop functionality to insert employee records (e.g., name, position,
department, salary, hire date) into an Oracle database.
Ensure that data is secure, accurate, and prevents data duplication or
inconsistencies.
b)Retrieve Data:
Implement a feature to query and retrieve employee information
from the Oracle database based on criteria such as employee ID,
department, or salary range.
Create one EMPLOYEE table:
CREATE TABLE EMPLOYEE (
EMP_ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
NAME VARCHAR2(50),
POSITION VARCHAR2(50),
DEPARTMENT VARCHAR2(50),
SALARY NUMBER(10,2),
HIRE_DATE DATE
);
Add Oracle JDBC Driver to Eclipse:
1. Download JDBC driver: [Link]
2. In Eclipse → Right click your Project → Build Path → Configure Build Path
3. Click Add External JARs
4. Select [Link]
5. Apply and Close
Create one employee package with in that create two classes
[Link]
[Link]
1. [Link]
package employee;
Anurag University 49 Java Programming Lab(R24)
import [Link].*;
import [Link];
public class InsertEmployee {
public static void main(String[] args) {
String url = "jdbc:oracle:thin:@localhost:1521:xe";
String user = "JAVA";
String pass = "java";
try {
[Link]("[Link]");
Connection con = [Link](url, user, pass);
String sql = "INSERT INTO EMPLOYEE (EMP_ID, NAME, POSITION,
DEPARTMENT, SALARY, HIRE_DATE) VALUES (?, ?, ?, ?, ?, ?)";
PreparedStatement ps = [Link](sql);
[Link](1, 1); // EMP_ID
[Link](2, "RAMU"); // NAME
[Link](3, "Software Engineer"); // POSITION
[Link](4, "IT"); // DEPARTMENT
[Link](5, 45000); // SALARY
// Convert string to SQL date
[Link] hireDate = new [Link](
new SimpleDateFormat("yyyy-MM-dd").parse("2025-02-01").getTime()
);
[Link](6, hireDate); // HIRE_DATE
int rows = [Link]();
if (rows > 0) {
[Link]("Employee Record Inserted Successfully!");
}
[Link]();
} catch (Exception e) {
[Link]();
}
}
}
Anurag University 50 Java Programming Lab(R24)
Output:
[Link]
package employee;
import [Link].*;
import [Link];
public class RetrieveEmployee {
public static void main(String[] args) {
String url = "jdbc:oracle:thin:@localhost:1521:xe";
String user = "JAVA";
String pass = "java";
Scanner sc = new Scanner([Link]);
try {
[Link]("[Link]");
Connection con = [Link](url, user, pass);
[Link]("Search by:");
[Link]("1. Employee ID");
[Link]("2. Department");
[Link]("3. Salary Range");
int choice = [Link]();
PreparedStatement ps = null;
switch (choice) {
case 1:
[Link]("Enter Employee ID: ");
int id = [Link]();
ps = [Link]("SELECT * FROM EMPLOYEE WHERE
EMP_ID = ?");
[Link](1, id);
break;
case 2:
Anurag University 51 Java Programming Lab(R24)
[Link]("Enter Department: ");
String dept = [Link]();
ps = [Link]("SELECT * FROM EMPLOYEE WHERE
DEPARTMENT = ?");
[Link](1, dept);
break;
case 3:
[Link]("Enter Min Salary: ");
double min = [Link]();
[Link]("Enter Max Salary: ");
double max = [Link]();
ps = [Link]("SELECT * FROM EMPLOYEE WHERE
SALARY BETWEEN ? AND ?");
[Link](1, min);
[Link](2, max);
break;
default:
[Link]("Invalid choice!");
return;
}
ResultSet rs = [Link]();
while ([Link]()) {
[Link]("-------------------------------------------------");
[Link]("EMP_ID : " + [Link]("EMP_ID"));
[Link]("Name : " + [Link]("NAME"));
[Link]("Position : " + [Link]("POSITION"));
[Link]("Department : " + [Link]("DEPARTMENT"));
[Link]("Salary : " + [Link]("SALARY"));
[Link]("Hire Date : " + [Link]("HIRE_DATE"));
}
[Link]();
} catch (Exception e) {
[Link]();
} finally {
[Link]();
}
}
}
Anurag University 52 Java Programming Lab(R24)
Output:
Anurag University 53 Java Programming Lab(R24)
WEEK 12:
Develop an application in Java that demonstrates the handling of both mouse and
keyboard events. The application should feature a graphical user interface (GUI) that
responds dynamically to user interactions.
Create a package events with in that write a class EventDemo
[Link]:
import [Link].*;
import [Link].*;
import [Link].*;
public class EventDemo extends JFrame implements MouseListener, MouseMotionListener,
KeyListener {
private static final long serialVersionUID = 1L;
JLabel label;
public EventDemo() {
setTitle("Mouse & Keyboard Events Demo");
setSize(500, 400);
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
label = new JLabel("Perform mouse or keyboard actions...");
[Link](new Font("Arial", [Link], 16));
add(label);
// Add listeners
addMouseListener(this);
addMouseMotionListener(this);
addKeyListener(this);
setVisible(true);
Anurag University 54 Java Programming Lab(R24)
setFocusable(true);
}
// MouseListener Methods
public void mouseClicked(MouseEvent e) {
[Link]("Mouse Clicked at (" + [Link]() + ", " + [Link]() + ")");
}
public void mousePressed(MouseEvent e) {
[Link]("Mouse Pressed");
}
public void mouseReleased(MouseEvent e) {
[Link]("Mouse Released");
}
public void mouseEntered(MouseEvent e) {
[Link]("Mouse Entered Window");
}
public void mouseExited(MouseEvent e) {
[Link]("Mouse Exited Window");
}
// MouseMotionListener Methods
public void mouseMoved(MouseEvent e) {
[Link]("Mouse Moved at (" + [Link]() + ", " + [Link]() + ")");
}
public void mouseDragged(MouseEvent e) {
[Link]("Mouse Dragged");
}
// KeyListener Methods
Anurag University 55 Java Programming Lab(R24)
public void keyTyped(KeyEvent e) {
[Link]("Key Typed: " + [Link]());
}
public void keyPressed(KeyEvent e) {
[Link]("Key Pressed: " + [Link]());
}
public void keyReleased(KeyEvent e) {
[Link]("Key Released: " + [Link]());
}
public static void main(String[] args) {
new EventDemo();
}
}
Output:
Anurag University 56 Java Programming Lab(R24)
Anurag University 57 Java Programming Lab(R24)
WEEEK 13:
Program that demonstrate the layout managers using JFrame.
[Link]:
package layouts;
import [Link].*;
import [Link].*;
public class FlowLayoutExample {
public static void main(String[] args) {
JFrame frame = new JFrame("FlowLayout Example");
// Use [Link] for layout
[Link](new FlowLayout());
[Link](new JButton("Button 1"));
[Link](new JButton("Button 2"));
[Link](new JButton("Button 3"));
[Link](new JButton("Button 4"));
[Link](new JButton("Button 5"));
[Link](400, 200);
[Link](true);
[Link](JFrame.EXIT_ON_CLOSE);
}
}
Output:
Anurag University 58 Java Programming Lab(R24)
[Link]:
package layouts;
import [Link].*;
import [Link].*;
public class BorderLayoutExample {
public static void main(String[] args) {
JFrame frame = new JFrame("BorderLayout Example");
[Link](new BorderLayout());
[Link](new JButton("North"), [Link]);
[Link](new JButton("South"), [Link]);
[Link](new JButton("East"), [Link]);
[Link](new JButton("West"), [Link]);
[Link](new JButton("Center"), [Link]);
[Link](400, 300);
[Link](true);
[Link](JFrame.EXIT_ON_CLOSE);
}
}
Output:
Anurag University 59 Java Programming Lab(R24)
[Link]:
package layouts;
import [Link].*;
import [Link].*;
public class GridLayoutExample {
public static void main(String[] args) {
JFrame frame = new JFrame("GridLayout Example");
[Link](new GridLayout(2, 3)); // 2 rows, 3 columns
for (int i = 1; i <= 6; i++) {
[Link](new JButton("Button " + i));
}
[Link](400, 200);
[Link](true);
[Link](JFrame.EXIT_ON_CLOSE);
}
}
Output:
Anurag University 60 Java Programming Lab(R24)
BoxLayoutExample:
package layouts;
import [Link].*;
public class BoxLayoutExample {
public static void main(String[] args) {
JFrame frame = new JFrame("BoxLayout Example");
JPanel panel = new JPanel();
[Link](new BoxLayout(panel, BoxLayout.Y_AXIS)); // vertical
[Link](new JButton("Button 1"));
[Link]([Link](10)); // spacing
[Link](new JButton("Button 2"));
[Link]([Link](10));
[Link](new JButton("Button 3"));
[Link](panel);
[Link](300, 200);
[Link](true);
[Link](JFrame.EXIT_ON_CLOSE);
}
}
Output:
Anurag University 61 Java Programming Lab(R24)
[Link]:
package layouts;
import [Link].*;
import [Link].*;
public class CardLayoutExample {
public static void main(String[] args) {
JFrame frame = new JFrame("CardLayout Example");
CardLayout card = new CardLayout();
JPanel panel = new JPanel(card);
JPanel card1 = new JPanel();
[Link](new JLabel("This is Card 1"));
[Link](new JButton("Button 1"));
JPanel card2 = new JPanel();
[Link](new JLabel("This is Card 2"));
[Link](new JButton("Button 2"));
[Link](card1, "First");
[Link](card2, "Second");
JButton next = new JButton("Next");
[Link](e -> [Link](panel));
[Link](panel, [Link]);
[Link](next, [Link]);
[Link](400, 250);
[Link](true);
[Link](JFrame.EXIT_ON_CLOSE);
}
}
Output:
Anurag University 62 Java Programming Lab(R24)