You are on page 1of 16

exp 1

AIM- WAP a program that prints all real solutions to the quadratic equation

Algorithm-
1. Start
2. Define main function
3. create scanner object to read input
4. input a,b and c from user
5. calculate discriminant from the formula b * b-4*a*c
6. use conditional statement to check the value of discriminant
if discriminant > 0
calculate two real roots using quadratic formula
display the values of roots
if discriminant =0
calculate one real roots using quadratic formula
display the value of root
if discriminant <0
display "No real solutions"
7.End

Program code

import java.util.Scanner;

public class Main {


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

System.out.print("Enter coefficient a: ");


double a = scanner.nextDouble();

System.out.print("Enter coefficient b: ");


double b = scanner.nextDouble();

System.out.print("Enter coefficient c: ");


double c = scanner.nextDouble();

double discriminant = b * b - 4 * a * c;

if (discriminant > 0) {
double root1 = (-b + Math.sqrt(discriminant)) / (2 * a);
double root2 = (-b - Math.sqrt(discriminant)) / (2 * a);
System.out.println("Two real solutions:");
System.out.println("Root 1: " + root1);
System.out.println("Root 2: " + root2);
} else if (discriminant == 0) {
double root = -b / (2 * a);
System.out.println("One real solution:");
System.out.println("Root: " + root);
} else {
System.out.println("No real solutions (discriminant is negative).");
}

scanner.close();
}
}

exp 2
AIM- Write a Java program that uses both recursive and non-recursive functions to
print the nth value of the Fibonacci sequence.

NON RECURSIVE:
Algorithm-
1. import java.util.Scanner
2. define main function
3. integers integers a and b to 0 and 1 and integer c
4. create Scanner object
5. Display "Enter upto which value: " and read num from user
6. display a and b
7. for i=2 to num-1
set c=a+b and display c
set a=b
set b=c
8. End

Code:
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner obj=new Scanner(System.in);
int a=0;
int b=1;
int c;
System.out.print("Enter up to which value: ");
int num = obj.nextInt();
System.out.println(" "+a);
System.out.println(" "+b);
for(int i=2;i<num;++i)
{
c=a+b;
System.out.println(" "+c);
a=b;
b=c;
}

}
}

RECURSIVE:
Algorithm-
1. Define recursive function fibonacci(n)
if n<=1 return n
else -> return fibonacci(n-1) + fibonacci(n-2)
2. Define main function
3. Create Scanner object
4. Read integer n from user
5. Display "Fibonacci Series: "
6. For i=0 to n-1
Display fibonacci (i)
7. End

Code-
import java.util.Scanner;
public class Main {
static int fibonacci(int n) {
if (n <= 1) {
return n;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}

public static void main(String[] args) {


Scanner obj=new Scanner(System.in);
System.out.print("Enter up to which value: ");
int n=obj.nextInt();

System.out.println("Fibonacci Series:");
for (int i = 0; i < n; i++) {
System.out.print(fibonacci(i) + " ");
}
}
}

exp 3
AIM- Write a program in Java for find AXB where A is a matrix of 3X3 and B is a
matrix of 2X3.

Algorithm-
1. Start
2. Import necessary java utility package
3. Define main method
4. Create Object and declare 3 int arrays a,b,c
5. Use loop to read and store elements in a and b array
6. use nested loop to perform matrix multiplication and
store result in c and print the product of elements of c array
7. End

Code-
import java.util.Scanner;
public class Matrix {
public static void main(String[] args) {
Scanner obj = new Scanner(System.in);
int[][] a = new int[3][3];
int[][] b = new int[3][3];
int[][] c = new int[3][3];
System.out.println("Enter the elements of 1st matrix: ");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
a[i][j] = obj.nextInt();
}
}
System.out.println("Enter the elements of 2nd matrix: ");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
b[i][j] = obj.nextInt();
}
}
System.out.println("Multiplying the matrices.. \n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
for (int k = 0; k < 3; k++) {
c[i][j] = c[i][j] + a[i][k] * b[k][j];
}
}
}
System.out.println("The product is :");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(c[i][j] + " ");
}
System.out.println();
}
}
}

exp 4
AIM- Write a program in Java with class Rectangle with the data fields width,
length, area and color. The length, width and area are of double type and color is
of string type. The methods are set_length() , set_width() , set_color(), and
find_area(). Create two object of Rectangle and compare their area and color. If
area and color same for the objects then display “Matching Rectangles” otherwise
display “Non Matching Rectangle”.

Algorithm-
1. Start
2. Create a rectangle class with attributes for length,width,area
and color.
Define methods to set and get these attributes and calculate area.
3. In main, create object to read user input and two rectangle objects,
rectangle1 and rectangle2.
4. Prompt the user to input the width,length and color for rectangle1
5. Read and set the width,length,color for rectangle1
6. Calculate the area of rectangle1 using the FindArea method
7. Prompt the user to input the width.length and color for rectangle2
8. Read and set the width.length,color for rectangle2
9. Calculate the area of rectangle2 using the findArea method.
10. Compare the areas and colors of rectangle1 and rectangle2 using
getArea and getColor method.
11. check if the areas are equal and the colors are equal.
12. If they match, print "Matching rectangles", if they don't print
"Non-matching recatngles"
13. End

code-
import java.util.Scanner;
class Rectangle{
double length;
double width;
double area;
String color;
public void setLength(double length){
this.length=length;
}
public void setWidth(double width){

this.width=width;
}
public void setColor(String color) {
this.color = color;
}
public void findArea() {
area = width * length;
}
public double getArea(){

return area;
}
public String getColor(){

return color;
}

}
public class Main {
public static void main(String[] args) {
Scanner ob = new Scanner(System.in);

Rectangle rectangle1 = new Rectangle();


System.out.print("Enter width for rectangle 1: ");
rectangle1.setWidth(ob.nextDouble());
System.out.print("Enter length for rectangle 1: ");
/., rectangle1.setLength(ob.nextDouble());
0 System.out.print("Enter color for rectangle 1: ");
ob.nextLine(); // Consume the newline left from previous input
rectangle1.setColor(ob.nextLine());
rectangle1.findArea();

Rectangle rectangle2 = new Rectangle();


System.out.print("Enter width for rectangle 2: ");
rectangle2.setWidth(ob.nextDouble());
System.out.print("Enter length for rectangle 2: ");
rectangle2.setLength(ob.nextDouble());
System.out.print("Enter color for rectangle 2: ");
ob.nextLine(); // Consume the newline left from previous input
rectangle2.setColor(ob.nextLine());
rectangle2.findArea();

if (rectangle1.getArea() == rectangle2.getArea() &&


rectangle1.getColor().equalsIgnoreCase(rectangle2.getColor()))
{
System.out.println("\nMatching rectangles!");
} else {
System.out.println("\nNon-matching rectangles.");
}
}
}

exp 5
AIM- write a program in java which implement interface Student which has two
methods Display_Grade and Attendence for PG_Students and UG_Students (PG_Students
and UG_Students are two
different classes for Post Graduate and Under Graduate Students respectively).

Algorithm-
1. Create an interface named Student with two abstract methods:
displayGrade() and displayAttendance()
2. Define a class named PGStudent that implements the Student
interface.
3. Include private instance variables name, m1, m2, m3, and
attendance to store student information.
4. Create a constructor to initialize the instance variables.
5. Implement the displayGrade() method to calculate the total marks
and display the grade based on specific criteria.
6. Implement the displayAttendance() method to display the attendance
information.
7. Define a class named UGStudent that implements the Student
interface.
8. Include private instance variables name, m1, m2, m3, and attendance
to store student information.
9. Create a constructor to initialize the instance variables.
10.Implement the displayGrade() method to calculate the total marks
and display the grade based on specific criteria.
11. Implement the displayAttendance() method to display the attendance
information.

code-

interface Student {
void displayGrade();

void displayAttendance();
}

class PGStudent implements Student {


private String name;
private int m1, m2, m3, attendance;

PGStudent(String name, int m1, int m2, int m3, int attendance) {
this.name = name;
this.m1 = m1;
this.m2 = m2;
this.m3 = m3;
this.attendance = attendance;
}

@Override
public void displayGrade() {
int total = m1 + m2 + m3;
String grade;

if (total > 250) {


grade = "A";
} else if (total < 250 && total >= 200) {
grade = "B";
} else if (total < 200) {
grade = "C";
} else {
grade = "D";
}

System.out.println("Name: " + name);


System.out.println("Total Marks: " + total);
System.out.println("Grade: " + grade);
}

@Override
public void displayAttendance() {
System.out.println("Name: " + name);
System.out.println("Attendance: " + attendance);
}
}

class UGStudent implements Student {


private String name;
private int m1, m2, m3, attendance;

UGStudent(String name, int m1, int m2, int m3, int attendance) {
this.name = name;
this.m1 = m1;
this.m2 = m2;
this.m3 = m3;
this.attendance = attendance;
}

@Override
public void displayGrade() {
int total = m1 + m2 + m3;
String grade;

if (total > 300) {


grade = "S";
} else if (total > 250) {
grade = "A";
} else if (total < 250 && total >= 200) {
grade = "B";
} else if (total < 200) {
grade = "C";
} else {
grade = "D";
}

System.out.println("Name: " + name);


System.out.println("Total Marks: " + total);
System.out.println("Grade: " + grade);
}

@Override
public void displayAttendance() {
System.out.println("Name: " + name);
System.out.println("Attendance: " + attendance);
}
}

public class StudentDemo {


public static void main(String[] args) {
PGStudent pg = new PGStudent("Alex", 45, 68, 47, 35);
pg.displayGrade();
pg.displayAttendance();

UGStudent ug = new UGStudent("Aman", 95, 88, 77, 25);


ug.displayGrade();
ug.displayAttendance();
}
}
exp 6
AIM- Write a program in Java to display name and roll number of students.
Initialize respective array variables for 10 studnets. Handle
ArrayIndexOutOfBoundsException, so that any such problem dose not cause illegal
termination of program.

Algorithm-
1. Start
2. Import the required Java library java.util.Scanner.
3. Define a class named Student.
4. Inside main :Create a Scanner object to read input from the user.
5. Initialize two arrays: studentNames to store student names and
rollNumbers to store roll numbers.
6. Input student names and roll numbers for 10 students using a for loop
7. Read the student's name and roll number
8. Use a try-catch block to catch ArrayIndexOutOfBoundsException which
may occur when trying to access elements beyond the array bounds.
9. Inside the try block, attempt to display the name and roll number
of each student by iterating through the arrays using a for loop
that runs from 0 to 10
10. In the catch block, handle the ArrayIndexOutOfBoundsException
Print an error message indicating that an Array Index Out of
Bounds Exception occurred.
Print a message stating that the program terminated safely.
11. Close the Scanner object to release resources.
12. End the program.

code-
import java.util.Scanner;

public class StudentInfo {


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

// Initialize arrays for student names and roll numbers


String[] studentNames = new String[10];
int[] rollNumbers = new int[10];

// Input student names and roll numbers


for (int i = 0; i < 10; i++) {
System.out.println("Enter the name of student " + (i + 1) + ": ");
studentNames[i] = scanner.nextLine();

System.out.println("Enter the roll number of student " + (i + 1) + ":


");
rollNumbers[i] = scanner.nextInt();
scanner.nextLine(); // Consume the newline character
}

try {
// Display the name and roll number of each student
for (int i = 0; i < 11; i++) { // Trying to access 11 students (0 to
10)
System.out.println("Student Name: " + studentNames[i]);
System.out.println("Roll Number: " + rollNumbers[i]);
System.out.println();
}
} catch (ArrayIndexOutOfBoundsException e) {
// Handle the exception gracefully
System.out.println("Array Index Out of Bounds Exception occurred.");
System.out.println("Program terminated safely.");
}

scanner.close();
}
}

exp 7
AIM- Write a java program using thread synchronization in multithreading.

Algorithm-
1.Create a Java class named ThreadSynchronization.
2.Define a main method in the ThreadSynchronization class.
3.Inside the main method:
i)Create two MyThread objects, thread1 and thread2, with respective
names.
ii)Start both thread1 and thread2.
4.In the MyThread class:
i)Define a static array message containing strings.
ii)Create a constructor that takes a name for the thread and sets
it using super.
iii)Override the run method:
a)Loop through the message array:
b)Add a random wait period to simulate different execution
times.
c)Print the thread name and a message from the array.
5.The randomWait method:
i)Generates a random sleep time and catches InterruptedException
if it occurs.
6. End

code-
package LABTasks;

public class ThreadSynchronization {

public static void main(String args[]) {


MyThread thread1 = new MyThread("thread1: ");
MyThread thread2 = new MyThread("thread2: ");
thread1.start();
thread2.start();

boolean thread1IsAlive = true;


boolean thread2IsAlive = true;

do {
if (thread1IsAlive && !thread1.isAlive()) {
thread1IsAlive = false;
System.out.println("Thread 1 is dead.");
}

if (thread2IsAlive && !thread2.isAlive()) {


thread2IsAlive = false;
System.out.println("Thread 2 is dead.");
}
} while (thread1IsAlive || thread2IsAlive);
}
}

class MyThread extends Thread {


static String message[] = { "Eat", "Well", "Sleep", "Well", "Do", "WELL." };

public MyThread(String id) {


super(id);
}

public void run() {


SynchronizedOutput.displayList(getName(), message);
}

void randomWait() {
try {
sleep((long) (3000 * Math.random()));
} catch (InterruptedException x) {
System.out.println("Interrupted!");
}
}
}

class SynchronizedOutput {
public static synchronized void displayList(String name, String list[]) {
for (int i = 0; i < list.length; ++i) {
MyThread t = (MyThread) Thread.currentThread();
t.randomWait();
System.out.println(name + list[i]);
}
}
}

exp 8-
AIM- Write a program to create Client/Server socket to establish communication in
bi-directional.

Code-

Server-
import java.net.*;
import java.io.*;

public class Server {


public static void main(String[] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(3333);
System.out.println("Server is running and waiting for connections...");

Socket clientSocket = serverSocket.accept();


System.out.println("Client connected.");

DataInputStream din = new DataInputStream(clientSocket.getInputStream());


DataOutputStream dout = new
DataOutputStream(clientSocket.getOutputStream());

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

String str = "";


String str2 = "";

while (!str.equals("stop")) {
str = din.readUTF();
System.out.println("Client says: " + str);

System.out.print("Server: ");
str2 = br.readLine();
dout.writeUTF(str2);
dout.flush();
}

din.close();
dout.close();
clientSocket.close();
serverSocket.close();
}
}

Client-
import java.net.*;
import java.io.*;

public class Client {


public static void main(String[] args) throws Exception {
Socket clientSocket = new Socket("localhost", 3333);

DataInputStream din = new DataInputStream(clientSocket.getInputStream());


DataOutputStream dout = new
DataOutputStream(clientSocket.getOutputStream());

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

String str = "";


String str2 = "";

while (!str.equals("stop")) {
System.out.print("Client: ");
str = br.readLine();
dout.writeUTF(str);
dout.flush();

str2 = din.readUTF();
System.out.println("Server says: " + str2);
}

dout.close();
clientSocket.close();
}
}

Algorithm

Server Algorithm:
1.Create a ServerSocket on a specified port (e.g., 3333).
2.Print a message indicating that the server is running and waiting
for connections.
3.Accept a client connection using serverSocket.accept().
4.Print a message indicating that a client has connected.
5.Create input and output streams (DataInputStream and DataOutputStream)
for communication with the client.
6.Create a BufferedReader to read input from the console.
7.Initialize two empty strings, str and str2.
8.Enter a loop that continues until the value of str is "stop".
i)Read a UTF-encoded string from the client using din.readUTF()
and store it in str.
ii)Print the received message from the client.
iii)Prompt the user to enter a message from the server using the
console (System.out.print("Server: ")).
iv)Read a line from the console and store it in str2.
v)Send the server's message to the client using dout.writeUTF(str2)
and flush the stream.
9.Close the input and output streams, client socket, and server socket.

Client Algorithm:
1.Create a Socket and connect to the server at the specified address
and port (e.g., "localhost", 3333).
2.Create input and output streams (DataInputStream and DataOutputStream) for
communication with the server.
3.Create a BufferedReader to read input from the console.
4.Initialize two empty strings, str and str2.
5.Enter a loop that continues until the value of str is "stop".
i)Prompt the user to enter a message from the client using the
console (System.out.print("Client: ")).
ii)Read a line from the console and store it in str.
iii)Send the client's message to the server using dout.
writeUTF(str) and flush the stream.
iv)Read a UTF-encoded string from the server using din.readUTF()
and store it in str2.
v)Print the received message from the server.
6.Close the input and output streams and the client socket.

exp 9
AIM- Create a simple HTML form containing a Text field and a Button.
By clicking on submit button,servlet is opened displaying a simple
Hello message with the name entered in the Text field.

Code-
index.html
<html>
<head>
<title>Hello Form</title>
</head>
<body>
<form action="EchoServlet" method="GET">
First Name: <input type="text" name="firstName">
<br />
Last Name: <input type="text" name="lastName" />
<br />
<input type="submit" value="Submit" />
</form>
</body>
</html>

EchoServlet.java
import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

public class EchoServlet extends HttpServlet {

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Set response content type
response.setContentType("text/html");

// Get the input from the form


String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");

// Generate the HTML output


PrintWriter out = response.getWriter();
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Hello, " + firstName + " " + lastName + "</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Hello, " + firstName + " " + lastName + "!</h1>");
out.println("</body>");
out.println("</html>");
}
}

Algorithm-
1.Create a HTML form with <form> element
2. Set the action attribute to the servlet path and use method="GET"
to send data via a GET request
3. Include "First Name" and "Last Name" input fields with name attributes
4.Create a java Servlet
5. Override the doGet method
6. Set the response content type to "text/html"
7. Get "First Name" and "Last Name" from the request using
request.getParameter()
8. Create a PrintWriter to generate HTML
9. Output the HTML response, including the personalized
"Hello,FirstName LastName!" message.
10. Handle exceptions gracefully.

exp 10
AIM- Write a program to create a student registration form with the
help of swings in Java and also do the database connectivity.

code-

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;

public class RegistrationForm implements ActionListener {


JFrame frame;
String[] gender={"Male","Female"};
JLabel nameLabel=new JLabel("NAME");
JLabel genderLabel=new JLabel("GENDER");
JLabel fatherNameLabel=new JLabel("FATHER NAME");
JLabel passwordLabel=new JLabel("PASSWORD");
JLabel confirmPasswordLabel=new JLabel("CONFIRM PASSWORD");
JLabel cityLabel=new JLabel("CITY");
JLabel emailLabel=new JLabel("EMAIL");
JTextField nameTextField=new JTextField();
JComboBox genderComboBox=new JComboBox(gender);
JTextField fatherTextField=new JTextField();
JPasswordField passwordField=new JPasswordField();
JPasswordField confirmPasswordField=new JPasswordField();
JTextField cityTextField=new JTextField();
JTextField emailTextField=new JTextField();
JButton registerButton=new JButton("REGISTER");
JButton resetButton=new JButton("RESET");

RegistrationForm()
{
//Calling methods from constructor
createWindow();
setLocationAndSize();
addComponentsToFrame();
}
public void createWindow()
{
frame=new JFrame();
frame.setTitle("Registration Form");
frame.setBounds(40,40,380,600);
frame.getContentPane().setBackground(Color.pink);
frame.getContentPane().setLayout(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
}
public void setLocationAndSize()
{
//Setting Location and Size of Each Component
nameLabel.setBounds(20,20,40,70);
genderLabel.setBounds(20,70,80,70);
fatherNameLabel.setBounds(20,120,100,70);
passwordLabel.setBounds(20,170,100,70);
confirmPasswordLabel.setBounds(20,220,140,70);
cityLabel.setBounds(20,270,100,70);
emailLabel.setBounds(20,320,100,70);
nameTextField.setBounds(180,43,165,23);
genderComboBox.setBounds(180,93,165,23);
fatherTextField.setBounds(180,143,165,23);
passwordField.setBounds(180,193,165,23);
confirmPasswordField.setBounds(180,243,165,23);
cityTextField.setBounds(180,293,165,23);
emailTextField.setBounds(180,343,165,23);
registerButton.setBounds(70,400,100,35);
resetButton.setBounds(220,400,100,35);
}
public void addComponentsToFrame()
{
//Adding components to Frame
frame.add(nameLabel);
frame.add(genderLabel);
frame.add(fatherNameLabel);
frame.add(passwordLabel);
frame.add(confirmPasswordLabel);
frame.add(cityLabel);
frame.add(emailLabel);
frame.add(nameTextField);
frame.add(genderComboBox);
frame.add(fatherTextField);
frame.add(passwordField);
frame.add(confirmPasswordField);
frame.add(cityTextField);
frame.add(emailTextField);
frame.add(registerButton);
frame.add(resetButton);
}
@Override
public void actionPerformed(ActionEvent e) {

}
public static void main (String []args)
{
new RegistrationForm();
}
}

Algorithm-
1.Create RegistrationForm Class:
2.Define a class named RegistrationForm.
3.Implement the ActionListener interface.
4.Declare JFrame and Components:
i)Declare a JFrame named frame.
ii)Declare JLabels for various fields (name, gender, father name,
password, confirm password, city, email).
iii)Declare JTextFields for input (name, father name, city, email).
iv)Declare JComboBox for the gender selection.
v)Declare JPasswordFields for password and confirm password.
vi)Declare JButtons for registration and reset.
5.Create Constructor:
i)Create a constructor RegistrationForm.
ii)Call methods to create the window, set location and size of
components, and add components to the frame.
6.Create Window:
i)Create a method createWindow to initialize the JFrame.
ii)Set the title, size, background color, visibility, default
close operation, and resizable properties.
7.Set Location and Size:
i)Create a method setLocationAndSize to set the location and
size of each component.
8.Add Components to Frame:
i)Create a method addComponentsToFrame to add all components to
the frame.
9.Main Method:
i)Implement a main method to instantiate an object of the
RegistrationForm class.
10.Action Performed (ActionListener):
i)Implement the actionPerformed method from the ActionListener
interface (currently empty).

You might also like