[Link].
CSIT 7th Semester
CSC-409: Advanced Java Programming
Lab 01 : Arithmetic operation in Java
Objective: Write a program in java that implements the following menu
1. ADD
2. SUBSTRACT
3. EXIT
Required Theory: Java is a high-level, object-oriented programming language. It
was designed to be platform-independent, meaning that Java programs can run on
any device or operating system that has a Java Virtual Machine (JVM) installed.
Arithmetic operations in Java are similar to other programming languages. You
can perform addition, subtraction, multiplication, division, and other mathematical
operations using arithmetic operators.
Executable Code:
import [Link];
public class ArithmeticMenu {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
int choice;
do {
[Link]("Menu:");
[Link]("1. ADD");
[Link]("2. SUBTRACT");
[Link]("3. EXIT");
choice = [Link]();
switch (choice) {
case 1:
[Link]("Enter two numbers:");
int num1 = [Link]();
int num2 = [Link]();
int sum = num1 + num2;
[Link]("Sum: " + sum);
break;
Prepared by Ankit Pangeni
case 2:
[Link]("Enter two numbers:");
int num3 = [Link]();
int num4 = [Link]();
int diff = num3 - num4;
[Link]("Difference: " + diff);
break;
case 3:
[Link]("Exiting...");
break;
default:
[Link]("Invalid choice. Please try again.");
break;
}
} while (choice != 3);
[Link]();
}
}
Output:
Prepared by Ankit Pangeni
[Link] 7th Semester
CSC-409: Advanced Java Programming
Lab 02 : Inheritance example in Java
Objective: Write a program in java that implements the following classes:
1. Room
-length
-breadth
-int getArea();
2. Bedroom (inherits Room)
-height
-int getVolume();
3. Create a driver class called RoomTest that creates two objects of Bedroom
and computes their area and volume.
Required Theory: Java Inheritance allows a class (subclass or derived class) to
inherit attributes and methods from another class (superclass or base class),
enabling code reusability and the creation of hierarchical relationships between
classes.
Executable Code:
class Room {
int length;
int breadth;
Room(int length, int breadth) {
[Link] = length;
[Link] = breadth;
}
int getArea() {
return length * breadth;
}
}
class BedRoom extends Room {
Prepared by Ankit Pangeni
int height;
BedRoom(int length, int breadth, int height) {
super(length, breadth);
[Link] = height;
}
int getVolume() {
return length * breadth * height;
}
}
public class RoomTest {
public static void main(String[] args) {
BedRoom room1 = new BedRoom(10, 12, 8);
BedRoom room2 = new BedRoom(15, 14, 10);
[Link]("Bedroom 1 Area:" + [Link]());
[Link]("Bedroom 1 Volume:" + [Link]());
[Link]("Bedroom 2 Area:" + [Link]());
[Link]("Bedroom 2 Volume:" + [Link]());
}
}
Output:
Bedroom 1 Area:120
Bedroom 1 Volume:960
Bedroom 2 Area:210
Bedroom 2 Volume:2100
Prepared by Ankit Pangeni
[Link] 7th Semester
CSC-409: Advanced Java Programming
Lab 03 : Inherface example in Java
Objective: Write a program in java that defines the interface and classes:
1. interface shape with
PI3.14 (constant)
double getArea(); (abstract method)
2. class circle implements shape interface and has radius
3. class rectangle implements shape interface and has length and breadth
Now, create a driver class Interface Test that creates objects of circle and rectangle
computes their area
Required Theory: An interface is a reference type that defines a set of abstract
methods and/or constants. It is similar to a class but differs in that it cannot contain
method implementations. Instead, classes implement interfaces by providing
concrete implementations for the methods declared in the interface.
Executable Code:
interface Shape {
double PI = 3.14;
double getArea();
}
class Circle implements Shape {
double radius;
Circle(double radius) {
[Link] = radius;
}
public double getArea() {
return PI * radius * radius;
}
}
Prepared by Ankit Pangeni
class Rectangle implements Shape {
double length;
double breadth;
Rectangle(double length, double breadth) {
[Link] = length;
[Link] = breadth;
}
public double getArea() {
return length * breadth;
}
}
public class InterfaceTest {
public static void main(String[] args) {
Circle circle = new Circle(5);
Rectangle rectangle = new Rectangle(4, 6);
[Link]("Area of Circle: " + [Link]());
[Link]("Area of Rectangle: " + [Link]());
}
}
Output:
Prepared by Ankit Pangeni
[Link] 7th Semester
CSC-409: Advanced Java Programming
Lab 04 : Graphical User Interface(GUI) Programming in Java
Objective: Write a GUI program in java to calculate simple interest, program
takes input (Principle, Rate, Years) from input textfields, and has a button named
FIND SI, the result is shown in a textfield.
Required Theory: Creating GUIs in Java using Swing involves designing and
implementing graphical interfaces for desktop applications. Swing, part of the Java
Foundation Classes (JFC), provides a rich set of components such as buttons, text
fields, labels, and panels for building interactive user interfaces. GUI development
in Swing typically follows a component-based approach, where UI elements are
added to containers such as JFrames, JPanels, or JDialogs.
Layout managers are used to arrange these components within containers, ensuring
proper resizing and alignment across different platforms and screen resolutions.
Event-driven programming is fundamental in Swing, where actions performed by
the user, such as button clicks or keyboard input, trigger event listeners to execute
specific actions or behaviors. Swing provides platform independence, allowing
GUIs to run seamlessly across different operating systems that support Java.
Executable code:
import [Link].*;
import [Link].*;
import [Link].*;
public class SimpleInterestCalculator extends JFrame {
private JTextField principalField, rateField, yearsField, resultField;
public SimpleInterestCalculator() {
setTitle("Simple Interest Calculator");
setSize(300, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel panel = new JPanel();
[Link](new GridLayout(4, 2));
JLabel principalLabel = new JLabel("Principal:");
JLabel rateLabel = new JLabel("Rate:");
Prepared by Ankit Pangeni
JLabel yearsLabel = new JLabel("Years:");
JLabel resultLabel = new JLabel("Simple Interest:");
principalField = new JTextField();
rateField = new JTextField();
yearsField = new JTextField();
resultField = new JTextField();
[Link](false); // Making resultField read-only
JButton calculateButton = new JButton("FIND SI");
[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
calculateSimpleInterest();
}});
[Link](principalLabel);
[Link](principalField);
[Link](rateLabel);
[Link](rateField);
[Link](yearsLabel);
[Link](yearsField);
[Link](resultLabel);
[Link](resultField);
add(panel, [Link]);
add(calculateButton, [Link]);
}
private void calculateSimpleInterest() {
try {
double principal = [Link]([Link]());
double rate = [Link]([Link]());
double years = [Link]([Link]());
double simpleInterest = (principal * rate * years) / 100;
[Link]([Link]("%.2f", simpleInterest));
}
catch (NumberFormatException ex) {
[Link](this, "Please enter valid numbers in
all fields.", "Input Error", JOptionPane.ERROR_MESSAGE);
}
}
public static void main(String[] args) {
[Link](new Runnable() {
public void run() {
new SimpleInterestCalculator().setVisible(true);
}
});
}
}
Prepared by Ankit Pangeni
Output:
Prepared by Ankit Pangeni
[Link] 7th Semester
CSC-409: Advanced Java Programming
Lab 05 : Graphical User Interface(GUI) and File handling in Java
Objective: Write a Swing program to create a simple form to input employee
details such as name, age, gender, and salary, and saves them to a file when the
"Save" button is clicked.
Required Theory: Swing allows developers to create interactive graphical user
interfaces (GUIs) for desktop applications. When combined with file handling,
Swing enables the creation of applications that not only provide a user-friendly
interface for input and output but also allow users to interact with files on the
system.
File handling in Java typically involves classes like FileReader, FileWriter,
BufferedReader, and BufferedWriter, which allow reading from and writing to
files. By integrating Swing components like JTextFields, JButtons, JComboBoxes,
etc., with file handling operations, developers can create applications that let users
input data through the GUI and then save or retrieve that data to/from files on the
system. For example, a Swing application may have text fields for users to enter
data, and when they click a "Save" button, the entered data is written to a file using
FileWriter.
Executable code:
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
public class EmployeeDetailsForm extends JFrame implements ActionListener {
private JTextField nameField, ageField, salaryField;
private JComboBox<String> genderComboBox;
private JButton saveButton;
public EmployeeDetailsForm() {
setTitle("Employee Details Form");
setSize(300, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Prepared by Ankit Pangeni
JPanel panel = new JPanel();
[Link](new GridLayout(5, 2));
JLabel nameLabel = new JLabel("Name:");
JLabel ageLabel = new JLabel("Age:");
JLabel genderLabel = new JLabel("Gender:");
JLabel salaryLabel = new JLabel("Salary:");
nameField = new JTextField();
ageField = new JTextField();
salaryField = new JTextField();
String[] genders = {"Male", "Female"};
genderComboBox = new JComboBox<>(genders);
saveButton = new JButton("Save");
[Link](this);
[Link](nameLabel);
[Link](nameField);
[Link](ageLabel);
[Link](ageField);
[Link](genderLabel);
[Link](genderComboBox);
[Link](salaryLabel);
[Link](salaryField);
[Link](saveButton);
add(panel);
}
public void actionPerformed(ActionEvent e) {
if ([Link]() == saveButton) {
saveEmployeeDetails();
}
}
private void saveEmployeeDetails() {
String name = [Link]();
String age = [Link]();
String gender = (String) [Link]();
String salary = [Link]();
try (FileWriter fw = new FileWriter("employee_details.txt", true);
BufferedWriter bw = new BufferedWriter(fw)) {
[Link]("Name: " + name + ", Age: " + age + ", Gender: " + gender
+ ", Salary: " + salary + "\n");
[Link](this, "Employee details saved
successfully!", "Success", JOptionPane.INFORMATION_MESSAGE);
// Clear fields after saving
[Link]("");
[Link]("");
[Link]("");
Prepared by Ankit Pangeni
} catch (IOException ex) {
[Link](this, "Error occurred while saving
employee details.", "Error", JOptionPane.ERROR_MESSAGE);
[Link]();
}
}
public static void main(String[] args) {
[Link](() -> {
new EmployeeDetailsForm().setVisible(true);
});
}
}
Output:
Prepared by Ankit Pangeni
[Link] 7th Semester
CSC-409: Advanced Java Programming
Lab 06: Java Database Connectivity (JDBC) Program in Java
Objective: Write a JDBC program in java to connect to a database named
'practical', and create a simple table for 'employee', add an employee detail and
retrieve it from database.
Required Theory: JDBC (Java Database Connectivity) in Java is a standard API
(Application Programming Interface) that allows Java applications to interact with
databases. It provides a set of classes and interfaces that enable developers to
perform database operations such as connecting to a database, executing SQL
queries, and processing the results.
JDBC acts as a bridge between Java applications and different database
management systems (DBMS) by providing a uniform interface for database
access regardless of the underlying database technology. With JDBC, developers
can write database-independent code, allowing their applications to work with
various databases seamlessly. Overall, JDBC simplifies database access and
integration within Java applications, making it easier to store, retrieve, and
manipulate data stored in databases.
Executable code:
import [Link].*;
public class EmployeeDatabase {
public static void main(String[] args) {
try {
// Register JDBC driver
[Link]("[Link]");
String JDBC_URL = "jdbc:mysql://localhost:3306/practical";
String USERNAME = "root";
String PASSWORD = "";
Prepared by Ankit Pangeni
// Open a connection
[Link]("Connecting to database...");
Connection conn = [Link](JDBC_URL, USERNAME,
PASSWORD);
// Create a statement
[Link]("Creating statement...");
Statement stmt = [Link]();
// Create table
String createTableSQL = "CREATE TABLE employee (" +
"id INT AUTO_INCREMENT PRIMARY KEY," +
"name VARCHAR(100)," +
"age INT," +
"position VARCHAR(100))";
[Link](createTableSQL);
[Link]("Table 'employee' created successfully.");
// Insert a record
String insertSQL = "INSERT INTO employee (name, age, position)
VALUES ('Ankit Pangeni', 22, 'Manager')";
[Link](insertSQL);
[Link]("Record inserted successfully.");
// Retrieve record
String retrieveSQL = "SELECT * FROM employee";
ResultSet rs = [Link](retrieveSQL);
// Display retrieved records
[Link]("Retrieved employee details:");
while ([Link]()) {
int id = [Link]("id");
String name = [Link]("name");
int age = [Link]("age");
String position = [Link]("position");
[Link]("ID: " + id + ", Name: " + name + ", Age: "
+ age + ", Position: " + position);
}
[Link]();
[Link]();
[Link]();
} catch (SQLException | ClassNotFoundException e) {
[Link]();
}
}
}
Prepared by Ankit Pangeni
Output from VS Code:
Output from Mysql:
Prepared by Ankit Pangeni
[Link] 7th Semester
CSC-409: Advanced Java Programming
Lab 07: Servlet Program example in Java
Objective: Create a basic servlet that can be deployed in a web application to
handle incoming HTTP requests and generate dynamic HTML responses.
Required Theory: A servlet class is used to extend the capabilities of servers that
host applications accessed by means of a request-response programming model.
Servlets are essentially server-side components that generate responses to requests
from clients, typically web browsers. They are based on the Java Servlet API,
which provides a standard interface for interacting with the web server
environment.
Servlets can handle various HTTP methods (GET, POST, PUT, DELETE, etc.)
and are commonly used in web applications to generate dynamic content, interact
with databases, process form data, and more. They are a fundamental part of Java
web development, particularly in conjunction with technologies like JavaServer
Pages (JSP), JavaServer Faces (JSF), and frameworks like Spring MVC.
Executable code:
[Link]
import [Link].*;
import [Link].*;
import [Link].*;
public class HelloServlet extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws
IOException, ServletException
{
[Link]("text/html");
PrintWriter out = [Link]();
[Link]("<html><head><title> Hello Ankit</title></head>");
[Link]("<body>Welcome Ankit!!!</body></html>");
[Link]();
}
}
Prepared by Ankit Pangeni
[Link]
<web-app>
<servlet>
<servlet-name>a</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>a</servlet-name>
<url-pattern>/gototest</url-pattern>
</servlet-mapping>
</web-app>
Output:
Prepared by Ankit Pangeni
[Link] 7th Semester
CSC-409: Advanced Java Programming
Lab 08: Servlet Program to receive HTML form parameters and display them.
Objective: Develop a J2EE web application named "formapp" that provides the
functionality of submitting the form parameters to a servlet that receives them.
Required Theory: A servlet class is used to extend the capabilities of servers that
host applications accessed by means of a request-response programming model.
Servlets are essentially server-side components that generate responses to requests
from clients, typically web browsers. They are based on the Java Servlet API,
which provides a standard interface for interacting with the web server
environment.
Servlets can handle various HTTP methods (GET, POST, PUT, DELETE, etc.)
and are commonly used in web applications to generate dynamic content, interact
with databases, process form data, and more. They are a fundamental part of Java
web development, particularly in conjunction with technologies like JavaServer
Pages (JSP), JavaServer Faces (JSF), and frameworks like Spring MVC.
Executable code:
[Link]
<html>
<head><title> Employee Form</title> </head>
<body>
<form action="gotoform">
<label for="name"> Name: </label> <br>
<input type="text" id="name" name="name"> <br>
<label for="salary"> Salary: </label> <br>
<input type="number" id="salary" name="salary"> <br>
<label for="phone"> Phone: </label> <br>
<input type="number" id="phone" name="phone"> <br>
<button type="submit"> Submit </button>
</form>
</body>
</html>
Prepared by Ankit Pangeni
[Link]
<web-app>
<servlet>
<servlet-name>a</servlet-name>
<servlet-class>FormApp</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>a</servlet-name>
<url-pattern>/gotoform</url-pattern>
</servlet-mapping>
</web-app>
[Link]
import [Link].*;
import [Link].*;
import [Link].*;
public class FormApp extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws
IOException, ServletException
{
[Link]("text/html");
PrintWriter out = [Link]();
String name = [Link]("name");
String salary = [Link]("salary");
String phone = [Link]("phone");
[Link]("<html><head><title> Hello</title></head>");
[Link]("<body>Welcome!!!");
[Link]("<br>Name: " + name + "<br> Salary: " + salary +
"<br>Phone:" + phone );
[Link]("</body></html>");
[Link]();
}
}
Prepared by Ankit Pangeni
Output from HTML form:
Output from Servlet:
Prepared by Ankit Pangeni
[Link] 7th Semester
CSC-409: Advanced Java Programming
Lab 09: Servlet Program to implement Cookies and Sessions.
Objective: Develop a servlet application to implement cookies and sessions.
When a user enters their name, the application should display the name through
cookies and sessions.
Required Theory: Cookies, small pieces of data stored in the client's browser,
offer a simple yet effective mechanism for storing information such as user
preferences or session identifiers. Servlets can set cookies in HTTP responses,
enabling subsequent requests to include the cookie data, facilitating personalized
experiences or authentication processes. Also, cookies offer configurability in
terms of expiration, allowing developers to define the duration for which the data
remains valid, thus enhancing security and privacy.
Sessions in servlets provide a more robust solution for maintaining stateful
communication with clients. A session, essentially a server-side storage associated
with a specific user, allows servlets to store and retrieve data across multiple
requests within a predefined time frame. By using sessions, servlets can manage
complex interactions, retaining user-specific information without relying solely on
client-side storage.
Executable code:
[Link]
<html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Enter Your Name</title>
</head>
<body>
<h1>Enter Your Name</h1>
<form action="NameServlet" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br><br>
<input type="submit" value="Submit">
</form> </body> </html>
Prepared by Ankit Pangeni
[Link]
<web-app>
<display-name>NameDisplayExample</display-name>
<welcome-file-list>
<welcome-file>[Link]</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>NameServlet</servlet-name>
<servlet-class>NameServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>NameServlet</servlet-name>
<url-pattern>/NameServlet</url-pattern>
</servlet-mapping>
</web-app>
[Link]
import [Link].*;
import [Link];
import [Link];
import [Link].*;
@WebServlet("/NameServlet")
public class NameServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
String name = [Link]("name");
// Creating a session
HttpSession session = [Link]();
[Link]("name", name);
// Creating a cookie
Cookie cookie = new Cookie("name", name);
[Link](5); // Cookie will expire after 30 minutes
[Link](cookie);
// Sending a success response
[Link]("text/html");
PrintWriter out = [Link]();
[Link]("<html><body>");
[Link]("<h1>Hello, " + name + "!</h1>");
[Link]("</body></html>");
}
}
Prepared by Ankit Pangeni
Output from HTML form:
Output from Servlet:
Prepared by Ankit Pangeni
[Link] 7th Semester
CSC-409: Advanced Java Programming
Lab 10: Servlet Program to Implement Three-Tier Architecture (Client, Server,
and Database).
Objective: Develop a servlet application to insert data into a database by
obtaining input from the user via an HTML form.
Required Theory: The servlet application facilitates seamless interaction between
the user and the database via an HTML form interface. Through the form, users
input data which is then processed by the servlet. Upon submission, the servlet
captures the user inputs and employs JDBC (Java Database Connectivity) to insert
the data into the designated database tables. This interaction is facilitated by the
server-side logic of the servlet, ensuring efficient handling of user data and
database operations.
Executable code:
[Link]
<html>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Employee Form</title>
</head>
<body>
<h2>Employee Form</h2>
<form action="gototest" method="get">
<label for="name">Name:</label><br>
<input type="text" id="name" name="name"><br>
<label for="salary">Salary:</label><br>
<input type="text" id="salary" name="salary"><br>
<label for="phone">Phone:</label><br>
<input type="text" id="phone" name="phone"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Prepared by Ankit Pangeni
[Link]
<web-app>
<display-name>FormApp</display-name>
<servlet>
<servlet-name>FormServlet</servlet-name>
<servlet-class>FormServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FormServlet</servlet-name>
<url-pattern>/gototest</url-pattern>
</servlet-mapping>
</web-app>
[Link]
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
public class FormServlet extends HttpServlet {
static Connection con;
public static Connection connect() {
try {
if (con != null)
return con;
[Link]("[Link]");
String JDBC_URL = "jdbc:mysql://localhost:3306/employeeform";
String USERNAME = "root";
String PASSWORD = "";
con = [Link](JDBC_URL, USERNAME, PASSWORD);
return con;
} catch (Exception e) {
[Link]();
return null;
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();
Prepared by Ankit Pangeni
String name = [Link]("name");
float salary= [Link]([Link]("salary"));
int phone= [Link]([Link]("phone"));
try {
Connection con = connect();
if (con != null) {
String query = "INSERT INTO empdetails VALUES (?, ?, ?)";
PreparedStatement stmt = [Link](query);
[Link](1, name);
[Link](2, salary);
[Link](3, phone);
int rowsAffected = [Link]();
if (rowsAffected > 0) {
[Link]("<h3>Data inserted successfully!</h3>");
} else {
[Link]("<h3>Failed to insert data!</h3>");
}
[Link]();
[Link]();
} else {
[Link]("<h3>Connection not established!</h3>");
}
}
catch (SQLException e) {
[Link]();
[Link]("<h3>Database operation failed!</h3>");
}
}
}
Prepared by Ankit Pangeni
Output from HTML form:
Output from Servlet:
Output from Database:
Prepared by Ankit Pangeni