Advancejavalab
Advancejavalab
Code:
import javax.swing.*;
f.setTitle("User Form");
f.add(namelabel);
f.add(namefield);
f.add(addresslabel);
f.add(addressfield);
f.add(emaillabel);
f.add(emailfield);
gendergroup.add(male);
gendergroup.add(female);
f.add(genderlabel);
f.add(male);
f.add(female);
f.add(jcountryfield);
f.add(jcountrylabel);
f.add(hobbies);
f.add(reading);
f.add(dancing);
f.add(singing);
f.add(travelling);
f.setSize(500, 500);
f.setLayout(null);
f.setVisible(true);
}}
OUTPUT:
2. Write a program to create a circle with border red and filled color as yellow.
Code:
import javax.swing.*;
import java.awt.*;
public class Lab2_rollno21 extends Canvas {
public void paint(Graphics graphic) {
graphic.setColor(Color.yellow);
graphic.fillRect(10, 10, 100, 100);
graphic.setColor(Color.red);
graphic.drawRect(10, 10, 100, 100);
}
public static void main(String[] args) {
Lab2_rollno9 canvas = new Lab2_rollno9();
JFrame f = new JFrame();
f.getContentPane().add(canvas);
f.setSize(400, 400);
f.setVisible(true);
f.setLayout(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Output:
3. Write a java GUI Program to calculate square of entered number.
Code:
import java.awt.*;
import javax.swing.*;
public class Lab3_rollno21 implements ActionListener {
JTextField inputField;
JTextField outputField;
public Lab3_rollno9() {
JLabel inputLabel = new JLabel("Enter any number:");
JFrame f = new JFrame();
f.setTitle("Square Calculator");
inputField = new JTextField();
inputLabel.setBounds(20, 20, 200, 25);
inputField.setBounds(200, 20, 150, 25);
f.add(inputLabel);
f.add(inputField);
Button Calculatebtn = new Button("Calculate");
Calculatebtn.setBounds(200, 60, 150, 25);
f.add(Calculatebtn);
JLabel outputLabel = new JLabel("Square of a entered number:");
outputField = new JTextField();
outputLabel.setBounds(20, 100, 200, 25);
outputField.setBounds(200, 100, 150, 25);
Calculatebtn.addActionListener(this);
f.add(outputLabel);
f.add(outputField);
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
int number = Integer.parseInt(inputField.getText());
int Square = number * number;
outputField.setText(String.valueOf(Square));
}
public static void main(String[] args) {
new Lab3_rollno21();
}
}
Output:
4. Write a program to calculate the sum of two digits.
Code:
import javax.swing.*;
import java.awt.event.*;
public class Lab4_Rollno21 implements ActionListener {
JTextField firstDigit, secondDigit;
JButton calculateButton;
JTextField outputField;
JFrame f = new JFrame();
public Lab4_Rollno9() {
f.setTitle("Two Digit Calculator");
JLabel firstDigitLabel = new JLabel("First Digit:");
firstDigitLabel.setBounds(20, 20, 200, 25);
firstDigit = new JTextField();
firstDigit.setBounds(200, 20, 150, 25);
f.add(firstDigitLabel);
f.add(firstDigit);
JLabel secondDigitLabel = new JLabel("Second Digit:");
secondDigit = new JTextField();
secondDigit.setBounds(200, 60, 150, 25);
f.add(secondDigitLabel);
f.add(secondDigit);
calculateButton = new JButton("Calculate");
calculateButton.setBounds(200, 100, 150, 25);
f.add(calculateButton);
JLabel outputLabel = new JLabel("Sum:");
outputLabel.setBounds(20, 140, 200, 25);
outputField = new JTextField();
outputField.setBounds(200, 140, 150, 25);
calculateButton.addActionListener(this);
f.add(outputField);
f.add(outputLabel);
f.setSize(400, 300);
f.setLayout(null);
f.setVisible(true);}
public void actionPerformed(ActionEvent e) {
int number1 = Integer.parseInt(firstDigit.getText());
int number2 = Integer.parseInt(secondDigit.getText());
int sum = number1 + number2;
outputField.setText(String.valueOf(sum));
}
public static void main(String[] args) throws Exception {
new Lab4_Rollno21();
}}
Output:
5. Write a GUI program using components to find sum and difference of two numbers.
Use two text fields for giving input and a label for output. The program should
display sum if user presses key and difference if user release key.
Code:
import java.awt.*;
import java.awt.event.*;
public class Lab5_rollno21 extends Frame implements KeyListener {
TextField num1Field, num2Field;
Label resultLabel;
Lab5_rollno9() {
Frame frame = new Frame("Sum and Difference Calculator");
num1Field = new TextField();
num1Field.setBounds(50, 50, 150, 20);
num2Field = new TextField();
num2Field.setBounds(50, 100, 150, 20);
resultLabel = new Label("Result will be displayed here");
resultLabel.setBounds(50, 150, 250, 20);
num1Field.addKeyListener(this);
num2Field.addKeyListener(this);
frame.add(num1Field);
frame.add(num2Field);
frame.add(resultLabel);
frame.setSize(400, 300);
frame.setLayout(null);
frame.setVisible(true);
}
public void keyPressed(KeyEvent e) {
calculateSum();
}
public void keyReleased(KeyEvent e) {
calculateDifference();
}
public void keyTyped(KeyEvent e) {
}
private void calculateSum() {
try {
int num1 = Integer.parseInt(num1Field.getText());
int num2 = Integer.parseInt(num2Field.getText());
int sum = num1 + num2;
resultLabel.setText("Sum: " + sum);
} catch (NumberFormatException ex) {
resultLabel.setText("Please enter valid numbers");
}} private void calculateDifference() {
try {
int num1 = Integer.parseInt(num1Field.getText());
int num2 = Integer.parseInt(num2Field.getText());
int difference = num1 - num2;
resultLabel.setText("Difference: " + difference);
} catch (NumberFormatException ex) {
resultLabel.setText("Please enter valid numbers");
}}
public static void main(String[] args) {
new Lab5_rollno21();
}}
Output:
6. Write a GUI program using components to find sum and difference of two
numbers. Use two text fields for giving input and a label for output. The program
should display sum if user presses key and difference if user release key.
Code:
import java.awt.*;
import javax.swing.*;
public class Lab6_rollno21 extends Frame implements MouseListener {
TextField num1Field;
TextField num2Field;
Label resultLabel;
Lab6_rollno9() {
Frame frame = new Frame("Sum and Difference Calculator");
num1Field = new TextField();
num1Field.setBounds(50, 50, 150, 20);
num2Field = new TextField();
num2Field.setBounds(50, 100, 150, 20);
resultLabel = new Label("Result will be displayed here");
resultLabel.setBounds(50, 150, 250, 20);
frame.addMouseListener(this);
frame.add(num1Field);
frame.add(num2Field);
frame.add(resultLabel);
frame.setSize(400, 300);
frame.setLayout(null);
frame.setVisible(true);
}
public void mouseClicked(MouseEvent e) {}
public void mousePressed(MouseEvent e) {
calculateSum();}
public void mouseReleased(MouseEvent e) {
calculateDifference();
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
private void calculateSum() {
try {
int num1 = Integer.parseInt(num1Field.getText());
int num2 = Integer.parseInt(num2Field.getText());
int sum = num1 + num2;
resultLabel.setText("Sum: " + 7);
} catch (NumberFormatException ex) {
resultLabel.setText("Please enter valid numbers");}}
private void calculateDifference() {
try {
int num1 = Integer.parseInt(num1Field.getText());
int num2 = Integer.parseInt(num2Field.getText());
int difference = num1 - num2;
resultLabel.setText("Difference: " + difference);
} catch (NumberFormatException ex) {
resultLabel.setText("Please enter valid numbers");
}} public static void main(String[] args) {
new Lab6_rollno21();
}}
Output:
7. Write a GUI program using components to find sum and difference of two numbers.
Use two text fields for giving input and a label for output. The program should
display sum if user presses key and difference if user release key using adapter class.
Code:
import java.awt.event.*;
import javax.swing.*;
public class Lab7_rollno21 extends KeyAdapter {
JLabel l1, l2, l3;
JTextField t1, t2, t3;
JFrame f = new JFrame("New key Adapter");
Lab7_rollno9() {
l1 = new JLabel("First Number");
l1.setBounds(10, 10, 200, 20);
t1 = new JTextField();
t1.setBounds(150, 10, 200, 20);
l2 = new JLabel("Second Number");
l2.setBounds(10, 40, 200, 20);
t2 = new JTextField();
t2.setBounds(150, 40, 200, 20);
l3 = new JLabel("Press any key");
l3.setBounds(10, 70, 200, 20);
t3 = new JTextField();
t3.setBounds(150, 70, 200, 20);
t3.addKeyListener(this);
f.add(l1);
f.add(l2);
f.add(t1);
f.add(t2);
f.add(t3);
f.setSize(600, 600);
f.setLayout(null);
f.setVisible(true);
}
public void keyPressed(KeyEvent e) {
int num1 = Integer.parseInt(t1.getText());
int num2 = Integer.parseInt(t2.getText());
int sum = num1 + num2;
t3.setText(String.valueOf(sum));
}
public static void main(String[] args) throws Exception {
new Lab7_rollno21();
}}
Output:
f.setSize(300, 200);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
Code:
In App.java
import java.sql.*;
public void CreateStudent(int id, String name, String address, String gender) {
try {Class.forName("com.mysql.cj.jdbc.Driver");
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, id);
ps.setString(2, name);
ps.setString(3, address);
ps.setString(4, gender);
ps.executeUpdate();
con.close();
System.out.println("Data Inserted");
} catch (Exception e) {
System.out.println(e);}}
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://
localhost:3306/sixthdb?useSSL=false", "root","root");
while (rs.next()) {
+ rs.getString("Gender")); }
con.close();
} catch (Exception e) {
System.out.println(e);}}
public void UpdateStudent(int id, String name, String address, String gender) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, address);
ps.setString(2, gender;
ps.setInt(3, id);
ps.executeUpdate();
con.close();
System.out.println("Data Updated");
} catch (Exception e) {
System.out.println(e);}
public void DeleteStudent(int id) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, id);
ps.executeUpdate();
con.close();
System.out.println("Data Deleted");
} catch (Exception e) {
System.out.println(e);
}}
In Lab12.java
import java.util.Scanner;
obj.GetAllStudent();
obj.DeleteStudent(2);
obj.GetAllStudent();}}
Output:
13. Write a program to update record in given table tblstudent whose id=4 and fetch
updated record.
Code:
In Lab13.java
import java.util.Scanner;
public class Lab13 {
public static void main(String[] args) {
App obj = new App();
System.out.println("Fetching all students:");
obj.GetAllStudent();
obj.UpdateStudent(4, "Rim", "BKT", "Female");
System.out.println("Fetching all students after update:");
obj.GetAllStudent();
}}
In App.java
import java.sql.*;
public class App {
public static void main(String[] args) {}
public void GetAllStudent() {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/sixthdb?useSSL=false",
"root","root");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM tblstudent");
while (rs.next()) {
System.out.println(rs.getInt("ID") + " " + rs.getString("Name") + " " +
rs.getString("Address") + " "
+ rs.getString("Gender")); // Adjusted to print all fields
}
con.close();
} catch (Exception e) {
System.out.println(e);
}}
public void UpdateStudent(int id, String name, String address, String gender) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306
/sixthdb?useSSL=false", "root","root");
String sql = "UPDATE tblstudent SET Address = ?, Gender = ? WHERE ID = ?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, address);
ps.setString(2, gender);
ps.setInt(3, id);
ps.executeUpdate();
con.close();
System.out.println("Data Updated");
} catch (Exception e) {
System.out.println(e);
}}}
Output:
14. Write a java program to fetch first,last,previous,next record using Scrollable
Resultset in JDBC.
Code:
import java.sql.*;
public class Lab14 {
public static void main(String[] args) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/sixthdb?useSSL=false",
"root","root");
Statement stmt = con.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet rs = stmt.executeQuery("SELECT * FROM tblstudent");
if (rs.last()) {
System.out.println("Last Row:");
System.out.println("ID: " + rs.getInt("id") + ", Name: " +
rs.getString("name"));
}
if (rs.first()) {
System.out.println("First Row:");
System.out.println("ID: " + rs.getInt("id") + ", Name: " +
rs.getString("name"));
}
if (rs.absolute(2)) {
System.out.println("Second Row:");
System.out.println("ID: " + rs.getInt("id") + ", Name: " +
rs.getString("name"));
}
if (rs.previous()) {
System.out.println("Previous Row:");
System.out.println("ID: " + rs.getInt("id") + ", Name: " +
rs.getString("name"));
}
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
15. Create a simple servlet that reads and displays data from HTML form. Assume
form with two fields username and password.
Code:
In index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Login Form</title>
</head>
<body>
<h2>Login Form</h2>
<label for="username">Username:</label><br>
<label for="password">Password:</label><br>
</form>
</body>
</html>
In GetfullName.java
import java.io.*;
import jakarta.servlet.*
response.setContentType("text/html");
out.println("<html><body>");
out.println("<h1>Login Information</h1>");
out.println("</body></html>");}}
1Output:
16. Write a Java program to store Username and Password from two input field in
cookies and retrieve value from cookies using Servlet.
Code:
CookiesServletOne.java
import java.io.*;
import jakarta.servlet.*;
public class CookiesServletOne extends HttpServlet {
public CookiesServletOne() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try{
response.setContentType("text/html");
PrintWriter pwriter = response.getWriter();
String name = request.getParameter("userName");
String password = request.getParameter("userPassword");
pwriter.print("Hello "+name);
pwriter.print("Your Password is: "+password);
Cookie c1=new Cookie("userName",name);
Cookie c2=new Cookie("userPassword",password);
response.addCookie(c1);
response.addCookie(c2);
pwriter.print("<br><a href='CookiesServletTwo'>View Details</a>");
pwriter.close();
}catch(Exception exp){
System.out.println(exp);
}}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}}
CookiesServletTwo.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
@WebServlet("/CookiesServletTwo")
public class CookiesServletTwo extends HttpServlet {
private static final long serialVersionUID = 1L;
public CookiesServletTwo() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try{
response.setContentType("text/html");
PrintWriter pwriter = response.getWriter();
Cookie c[]=request.getCookies();
pwriter.print("Name: "+c[0].getValue());
pwriter.print("Password: "+c[1].getValue());
pwriter.close();
}catch(Exception exp){
System.out.println(exp);}}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}}
Index.html
<body>
<form action="CookiesServletOne" method="post">
User Name:<input type="text" name="userName"/><br/>
Password:<input type="password" name="userPassword"/><br/>
<input type="submit" value="submit"/>
</form>
</body>
</html>
Output:
17. Write a Java program to store “Swastik College” String value in session and
retrieve from session using Servlet.
Code:
SessionServletOne.Java
import java.io.*;
import jakarta.servlet.*;
public class SessionServletOne extends HttpServlet {
private static final long serialVersionUID = 1L;
public SessionServletOne() {
super();}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
HttpSession session=request.getSession();
session.setAttribute("uname",n);
out.print("<a href='SessionServletTwo'>visit</a>");
out.close();
}catch(Exception e){
System.out.println(e);
} }
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}}
SessionServletTwo.java
import java.io.*;
import jakarta.servlet.*;
public class SessionServletTwo extends HttpServlet {
private static final long serialVersionUID = 1L;
public SessionServletTwo() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
HttpSession session=request.getSession(false);
String n=(String)session.getAttribute("uname");
out.print("Hello "+n);
out.close();
}catch(Exception e){System.out.println(e);}}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}}
index.html
<body>
<form action="SessionServletOne">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
</body>
Output:
18. Create a jsp page that contains three textboxes to input three numbers and a button.
It should display the greatest number among three number when button is clicked.
Code:
<body>
<form method="post">
</form>
<%
if (request.getParameter("num1") != null) {
%>
</body>
Output:
19. Write a Java program to implement Java RMI using an interface interfaceadder
with an add method.Create a server (MyServer.java) and client (Client.java) that
perform addition remotely using RMI.
Code:
In Interfaceadder.java
import java.rmi.*;
public interface interfaceadder extends Remote {
public int add(int x, int y) throws RemoteException;
}
In MyServer.java
import java.rmi.*;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
public class MyServer extends UnicastRemoteObject implements interfaceadder {
public MyServer() throws RemoteException {
super();
}
public static void main(String[] args) throws RemoteException {
try {
Registry reg = LocateRegistry.createRegistry(5000);
reg.rebind("hi_server", new MyServer());
System.out.println("Server is Now Ready..");
} catch (RemoteException e) {
System.out.println(e);
}}
public int add(int x, int y) throws RemoteException {
return x + y;
}}
In Client.java
import java.rmi.*;
public class Client {
public static void main(String[] args) throws RemoteException {
Client client = new Client();
client.connectRemote();
}
private void connectRemote() throws RemoteException {
try {
Registry reg = LocateRegistry.getRegistry("localhost", 5000);
interfaceadder ad = (interfaceadder) reg.lookup("hi_server");
System.out.println("Addition:" + ad.add(20, 30));
} catch (NotBoundException | RemoteException e) {
System.out.println(e);
}}}
Output: