Java File
Java File
PRACTICAL FILE
Semester: 6
R1 R2 R3 R4 R5
1. Write a program to
implement parameterized
constructor in Java.
2. Write a program to
implement method
overriding in Java.
3. Write a program to
implement polymorphism
in Java.
4. Write a program to
implement Exception
handling in Java.
5. Write a program to
implement Exception
handling in Java.
6. Write a program to
implement Socket
Programming in Java.
7. Implement Datagram UDP
socket programming in
java.
8. Implement Socket
programming for TCP in
Java Server and Client
Sockets.
9. Implement Producer-
Consumer Problem using
multithreading.
10. Illustrate Priorities in
Multithreading via help of
getPriority() and
setPriority() method.
11. Illustrate Deadlock in
multithreading.
SNo. Experiment Name Date Marks Signature
R1 R2 R3 R4 R5
Create a class Box that uses a parameterized constructor to initialize the dimensions of a box. The
dimensions of the Box are width, height, depth. The class should have a method that can return the
volume of the box. Create an object of the Box class and test the functionalities.
class ClassName {
TypeName variable1;
TypeName variable2;
ClassName(TypeName variable1, TypeName variable2)
{ this.variable1 = variable1;
this.variable2 = variable2;
}
}
Source Code:
package Java;
import [Link];
class Box {
int width,height,depth;
Box (int w, int h, int d) {
width=w;
height=h;
depth=d;
}
int calVolume() {
return width*height*depth;
}
}
Create a base class Fruit which has name ,taste and size as its attributes. A method called eat() is
created which describes the name of the fruit and its taste. Inherit the same in 2 other class Apple and
Orange and override the eat() method to represent each fruit taste.
Overview: Method overriding is a fundamental concept in object-oriented programming (OOP) that allows a
subclass (child class) to provide a specific implementation for a method inherited from its superclass (parent
class). This enables customization of behavior based on the specific subclass without modifying the superclass
itself.
class ClassName1 {
TypeName variable1;
TypeName variable2;
returnType method (parameters) {}
}
Class ClassName2 extends
ClassName1{ returnType method
(parameters) {}
}
Source Code:
package Java;
class Fruit {
String
name,taste; int
size;
void eat() {
[Link]("Inside Fruit class");
}
}
class Apple extends Fruit
{ Apple (String n, String t, int
s) { name=n;
taste=t;
size=s;
}
void eat() {
[Link]("Name: "+ name +"\nTaste: "+ taste);
}
}
class Orange extends Fruit
{ Orange (String n, String t, int s)
{ name=n;
taste=t;
size=s;
}
void eat() {
[Link]("Name: "+ name +"\nTaste: "+ taste);
}
}
Output:
PROGRAM-3
Create a class named shape. It should contain 2 methods- draw() and erase() which should print
“Drawing Shape” and “Erasing Shape” respectively. For this class we have three sub classes- Circle,
Triangle and Square and each class override the parent class functions- draw () and erase (). The
draw() method should print “Drawing Circle”, “Drawing Triangle”, “Drawing Square” respectively.
The erase() method should print “Erasing Circle”, “Erasing Triangle”, “Erasing Square” respectively.
Create objects of Circle, Triangle and Square in the following way and observe the polymorphic
nature of the class by calling draw() and erase() method using each object. Shape c=new Circle();
Shape t=new Triangle(); Shape s=new Square();
Overview: Polymorphism in Java is a concept by which we can perform a single action in different
ways. Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means
many and "morphs" means forms. So polymorphism means many forms. There are two types of
polymorphism in Java: compile-time polymorphism and runtime polymorphism.
class ClassName1 {}
class ClassName2 extends ClassName1 {}
ClassName1 cn1 = new ClassName2();
Source Code:
package Java;
class Shape
{ void draw() {
[Link]("Drawing Shape");
}
void erase()
{ [Link]("Erasing
Shape");
}
}
class Circle extends Shape
{ void draw() {
[Link]("Drawing Circle");
}
void erase()
{ [Link]("Erasing
Circle");
}
}
class Triangle extends Shape
{ void draw() {
[Link]("Drawing Triangle");
}
void erase() {
[Link]("Erasing Triangle");
}
}
class Square extends Shape
{ void draw() {
[Link]("Drawing Square");
}
void erase()
{ [Link]("Erasing
Square");
}
}
Output:
PROGRAM-4
Write a Program to take care of Number Format Exception if user enters values other than integer for
calculating average marks of 2 students. The name of the students and marks in 3 subjects are taken
from the user while executing the program. In the same Program write your own Exception classes to
take care of Negative values and values out of range (i.e. other than in the range of 0-100).
Overview: An exception is an issue (run time error) that occurred during the execution of a program.
When an exception occurred the program gets terminated abruptly and, the code past the line that
generated the exception never gets [Link] exceptions cover almost all the general types of
exceptions that may occur in the programming. However, we sometimes need to create custom
exceptions.
Source Code:
package Java;
import [Link];
Output:
PROGRAM-5
Write a program that takes as input the size of the array and the elements in the array. The program
then asks the user to enter a particular index and prints the element at that index. Index starts from
zero. This program may generate Array Index Out Of Bounds Exception or Number Format
Exception. Use Exception handling mechanisms to handle this exception.
Overview: An exception is an issue (run time error) that occurred during the execution of a program.
When an exception occurred the program gets terminated abruptly and, the code past the line that
generated the exception never gets executed. The ArrayIndexOutOfBoundsException occurs
whenever we are trying to access any item of an array at an index which is not present in the array. In
other words, the index may be negative or exceed the size of an array. The NumberFormatException
is thrown when we try to convert a string into a numeric value such as float or integer, but the format
of the input string is not appropriate or illegal.
try {
// Block of code to try
}
catch (Exception e) {
// Block of code to handle errors
}
Source Code:
import [Link];
Output:
PROGRAM-6
Source code-
// A Java program for a
Client import [Link].*;
import [Link].*;
}
catch (IOException i) {
[Link](i);
}
}
public static void main(String args[])
{
Client client = new Client("[Link]", 5000);
}
}
socket = [Link]();
[Link]("Client accepted"); in
= new DataInputStream(
new BufferedInputStream([Link]()));
}
catch(IOException i)
{
[Link](i);
}
}
[Link]("Closing connection");
[Link]();
[Link]();
}
catch(IOException i)
{
[Link](i);
}
}
public static void main(String args[]){Server server = new Server(5000);}}
OUTPUT-
PROGRAM 7
SOURCE CODE:
import [Link].*;
5000;
}}
OUTPUT:
PROGRAM 8
AIM: Implement Socket programming for TCP in Java Server and Client Sockets.
OVERVIEW:
The Client-Server Model Establishes a two-way communication between a server program and a client
program.
• TCP Sockets: Uses TCP (Transmission Control Protocol) for reliable data transfer with error.
SOURCE CODE:
portNumber = 6789;
try (
ServerSocket serverSocket = new ServerSocket(portNumber);
Socket clientSocket = [Link]();
BufferedReader in = new BufferedReader(new
InputStreamReader([Link]())); PrintWriter out = new
PrintWriter([Link](), true);
){
[Link]("Client connected!"); String message; while
} catch (IOException e) {
}}
Client side code:
import [Link].*; import [Link].*; public class Client { public static void main(String[] args) throws
IOException { String serverAddress = "localhost";
int portNumber = 6789;
try (Socket clientSocket = new Socket(serverAddress, portNumber); BufferedReader in =
new BufferedReader(new
InputStreamReader([Link]())); PrintWriter out = new
PrintWriter([Link](), true);
BufferedReader stdIn = new BufferedReader(new InputStreamReader([Link]))
){
String serverMessage; String userMessage;
while ((serverMessage = [Link]()) != null) { [Link]("Server: " + serverMessage); if
([Link]("quit")) {break; }} [Link](userMessage);
if ([Link]("quit")) {
break; }
serverMessage = [Link]();
[Link]("Server: " + serverMessage); }
} catch (IOException e) {
[Link]("Client error: " + [Link]()); }
}}
OUTPUT:
PROGRAM-9
AIM: Implement Producer-Consumer Problem using multithreading.
OVERVIEW:
The producer-consumer problem is a fundamental challenge in computer science that arises when two
processes share a limited buffer. One process, the producer, creates data and adds it to the buffer. The
other process, the consumer, removes data from the buffer and processes it. The key difficulty is
ensuring synchronization between the producer and consumer to avoid data loss or corruption. This
problem is a classic example of inter-process communication and is essential for understanding
concurrency control in operating systems.
SOURCE CODE:
[Link]; import
consumption [Link]();
} finally { [Link]();
[Link]();
(head + 1) % size;
item;
} finally { [Link]();
{ int bufferSize = 5;
String[] items = {"Item 1", "Item 2", "Item 3", "Item 4", "Item
5"}; for (String item : items) { try { [Link](item);
} catch (InterruptedException e) {
[Link]();
});
{ [Link]();
} catch (InterruptedException e) {
[Link]();
} });
[Link](); [Link]();
[Link](); [Link]();
}
OUTPUT:
PROGRAM-10
AIM: Illustrate Priorities in Multithreading via help of getPriority() and
setPriority() method.
OVERVIEW:
Java threads have priorities (1-10) influencing CPU access. getPriority() retrieves the current priority,
while setPriority() attempts to change it (actual priority might be lower due to system restrictions). Use
these methods to create scenarios where higher priority threads are more likely to be scheduled first by
the CPU, showcasing the impact of priority on thread execution order.
SOURCE CODE:
public class PriorityDemo {
[Link](); [Link]();
}
}
OUTPUT:
PROGRAM-11
AIM: Illustrate Deadlock in multithreading.
OVERVIEW:
Deadlock in multithreading occurs when two or more threads are permanently blocked, waiting for
resources held by each other. Imagine Thread A holding Resource 1 and waiting for Resource 2 held by
Thread B. Simultaneously, Thread B holds Resource 2 and waits for Resource 1 held by Thread A.
Neither thread can proceed, creating a deadlock. To avoid this, acquire resources in a consistent order or
use techniques like timeouts to prevent indefinite waiting.
SOURCE CODE:
public class ANUDeadlockDemo {
[Link](); [Link]();
}
}
OUTPUT:
PROGRAM-12
AIM: Illustrate use of java beans.
OVERVIEW:
JavaBeans facilitate reusable software components in Java. They encapsulate functionality,
expose properties accessed via getter/setter methods, and handle events. Supporting
customization and design-time features, they follow a lifecycle model and support serialization.
Adhering to naming conventions, JavaBeans ensure interoperability and platform
independence, enabling portable and versatile
component-based development.
SOURCE CODE:
public PersonBean() {
OUTPUT:
PROGRAM-13
AIM: Illustrate use of encapsulation in java beans.
OVERVIEW:
Encapsulation in JavaBeans involves concealing the internal state of objects by
declaring fields as private and providing public methods to access or modify them.
This safeguards data integrity and controls access to properties, promoting
modular design and facilitating reusable software components with well-defined
interfaces and controlled behavior.
SOURCE CODE:
// [Link]
public class PersonBean {
// Private fields
private String name;
private int age;
}
}
OUTPUT:
PROGRAM-14
AIM: Write a Java program to insert data into a table using JSP.
OVERVIEW:
In JSP, data insertion into a database table typically involves accepting user input through
HTML forms, processing it using JSP, and executing SQL queries to insert the data into the
database. This process integrates presentation (HTML forms) with logic (JSP) and data
manipulation (SQL), enabling dynamic and interactive web applications with data
persistence capabilities.
SOURCE CODE:
<%
// Initialize variables
String name = [Link]("name");
int age = [Link]([Link]("age"));
try {
// Obtain DataSource from JNDI (Java Naming and Directory Interface)
Context initContext = new InitialContext();
Context envContext = (Context)[Link]("java:/comp/env");
DataSource dataSource = (DataSource)[Link]("jdbc/myDataSource");
OUTPUT:
PROGRAM-15
AIM: Implement Regular Expressions validation before submitting data in JSP.
OVERVIEW:
SOURCE CODE:
<!DOCTYPE html>
<html>
<head>
<title>Regex Validation in JSP</title>
</head>
<body>
<h2>Regex Validation in JSP</h2>
<form action="process" method="post">
Name: <input type="text" name="name" required><br>
Age: <input type="text" name="age" required><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@WebServlet("/process")
public class ProcessServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// Retrieve form data
String name = [Link]("name");
String ageStr = [Link]("age");
if (.matches()) {
[Link]().println("Invalid age. Please enter only positive integers.");
return;
}
OUTPUT:
PROGRAM-16
AIM: Write JSP program to implement form data validation.
OVERVIEW:
To implement form data validation in JSP, validate user inputs against predefined criteria
(e.g., required fields, data formats) using JavaScript or server-side logic. Display error
messages for invalid inputs and prevent form submission until all inputs are valid. This
ensures data integrity and enhances user experience by guiding users to provide correct
input.
SOURCE CODE:
<!DOCTYPE html>
<html>
<head>
<title>Form Data Validation in JSP</title>
</head>
<body>
<h2>Form Data Validation in JSP</h2>
<form action="[Link]" method="post">
Name: <input type="text" name="name" required><br>
Age: <input type="text" name="age" required><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
<%@ page language="java" %>
<%@ page import="[Link]" %>
<%@ page import="[Link].*" %>
<%@ page import="[Link].*" %>
<%
String name = [Link]("name");
String ageStr = [Link]("age");
OUTPUT:
PROGRAM-17
AIM: Write a Java program to show user validation using Servlet.
OVERVIEW:
In a Java Servlet program for user validation, capture user input from a form, then validate
it server-side using predefined criteria (e.g., username availability, password strength). If
validation fails, display error messages to guide the user. Successful validation allows
further processing (e.g., authentication, data processing). This ensures data integrity and
enhances security.
SOURCE CODE:
import [Link].*;
import [Link].*;
import [Link];
import [Link].*;
@WebServlet("/login")
public class UserValidationServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// Retrieve form data
String username = [Link]("username");
String password = [Link]("password");
// Validate user input (e.g., check if username and password are not empty)
if (username != null && ![Link]() && password != null && ![Link]()) {
// Successful validation, perform further processing (e.g., authentication)
// Add your code here...
OUTPUT:
If the user submits valid data (non-empty username and password), the output will be:
PROGRAM-18
AIM: Write a program to set cookie information using Servlet using java
OVERVIEW:
To set cookie information using a Servlet, retrieve the HttpServletResponse object in the
servlet, then create a Cookie object with desired name-value pairs and additional
attributes if needed (e.g., expiration time, domain). Add the cookie to the response using
HttpServletResponse's addCookie() method. Once set, the cookie will be sent to the
client's browser with subsequent responses, facilitating state management and user
tracking across sessions.
SOURCE CODE:
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@WebServlet("/setCookie")
public class SetCookieServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// Create a new cookie
Cookie cookie = new Cookie("username", "john_doe");
OUTPUT:
PROGRAM-19
AIM: Design Servlet Login and Logout using Cookies
OVERVIEW:
To design a Servlet login and logout system using cookies, authenticate users by
validating their credentials against a database. Upon successful login, set a session cookie
with a unique identifier. Implement a logout mechanism to invalidate the session cookie.
Cookies facilitate user authentication across requests, providing a seamless login
experience, while logout clears the session, enhancing security and user privacy.
SOURCE CODE:
[Link]:
import [Link].*;
import [Link].*;
import [Link];
import [Link].*;
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
String username = [Link]("username");
String password = [Link]("password");
[Link]:
import [Link].*;
import [Link].*;
import [Link];
import [Link].*;
@WebServlet("/logout")
public class LogoutServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// Expire the session cookie
Cookie sessionCookie = new Cookie("session", "");
[Link](0); // Set the cookie age to 0 to expire it immediately
[Link](sessionCookie);
OUTPUT:
The output of the provided Servlets will be observed in the browser. Here's how the program flow and
outputs would appear:
1. Login Attempt:
User enters username and password and submits the login form.
If the credentials are correct, the user is redirected to the home page ([Link]).
If the credentials are incorrect, the user is redirected back to the login page ([Link])
with an error message.
2. Logout:
When the user clicks on the logout link or button, the LogoutServlet is invoked.
The session cookie is invalidated, and the user is redirected to the login page ([Link]).
3. Output Display:
If login is successful, the user sees the home page content.
If login fails, the user is redirected back to the login page with an error message.
After logout, the user is redirected to the login page.
PROGRAM-20
AIM: To Create a servlet that recognizes a visitor for the first time to a web application and
responds by saying “Welcome, you are visiting for the first time”. When the page is visited for the
second time, it should say “Welcome Back”.
OVERVIEW:
To create a servlet recognizing a visitor for the first time, store a unique identifier (e.g., IP
address, browser fingerprint) in a cookie upon the initial visit. On subsequent visits,
retrieve the identifier from the cookie. If the identifier exists, greet the visitor with
"Welcome Back"; otherwise, greet them with "Welcome, you are visiting for the first time".
This approach facilitates personalized greetings based on user visits, enhancing user
experience.
SOURCE CODE:
import [Link].*;
import [Link].*;
import [Link];
import [Link].*;
@WebServlet("/welcome")
public class WelcomeServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// Check if the visitor has visited before by checking for a cookie
Cookie[] cookies = [Link]();
boolean visitedBefore = false;
if (cookies != null) {
for (Cookie cookie : cookies) {
if ([Link]().equals("visited") && [Link]().equals("true")) {
visitedBefore = true;
break;
}
}
}
OUTPUT:
When the servlet is accessed for the first time, it sets a cookie to mark the visitor's
first visit and responds with:
Upon subsequent visits, the servlet recognizes the visitor based on the presence
of the cookie and responds with:
PROGRAM-21
AIM: Develop a small web program using Servlets, JSPs with Database connectivity.
OVERVIEW:
To develop a small web program using Servlets, JSPs, and Database connectivity, start by
creating Servlets to handle business logic and interact with the database. Use JSPs to
generate dynamic HTML content for presentation. Establish database connectivity using
JDBC to perform database operations. Servlets retrieve data from the database and
forward it to JSPs for rendering, enabling dynamic web content generation based on
database data.
SOURCE CODE:
@WebServlet("/user")
public class UserServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
String username = [Link]("username");
[Link]("username", username);
[Link]("[Link]").forward(request, response);
}}
OUTPUT: