Organized
Organized
5th Semester
Code: - BCA-508P
Semester: - SEM-5
Acknowledgement
Q1 find the average and sum of the N numbers Using Command line
argument..
CODE:
OUTPUT:-
SumAndAverage.java javac
SumAndAverage.java java
SumAndAverage 10 20 30 40 50
Sum: 150.0
Average: 30.0
OUTPUT:-
Page 1
WAP to
Code:
OUTPUT:-
CountArguments.java javac
CountArguments.java java
CountArguments arg1 arg2 arg3 Input:
java CountArguments arg1 arg2 arg3
OUTPUT:-: Number of arguments: 3
Page 2
WAP to
Code:
import java.util.Scanner;
scanner.close();
}
}
OUTPUT:-
SimpleInterest.java javac
SimpleInterest.java java
SimpleInterest
Enter Principal: 1000 Enter Rate of Interest: 5 Enter Time (in years): 2
Simple Interest: 100.0
Q4 create a Simple class to find out the Area and perimeter of
rectangle and box using super and this keyword.
CODE:
class Rectangle {
double length, width;
Rectangle(double length, double width)
{ this.length = length;
this.width = width;
}
double getArea() {
Page 3
WAP to
OUTPUT:-
ShapeCalculation.java
javac
ShapeCalculation.java
java ShapeCalculation
Input:
(Rectangle with length = 10, width = 5)
(Box with length = 10, width = 5, height = 8)
OUTPUT:-
Rectangle Area: 50.0
Rectangle Perimeter: 30.0
Box Volume: 400.0
Box Surface Area: 340.0
Page 4
Q5 WAP to design a class account using the inheritance and static that
show all function of bank (withdrawl, deposite).
CODE:
class Account {
static double balance = 0; static
void deposit(double amount) {
balance += amount;
System.out.println("Deposited: " + amount);
}
static void withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
System.out.println("Withdrawn: " + amount);
} else {
System.out.println("Insufficient balance.");
} }
static void displayBalance() {
System.out.println("Current Balance: " + balance);
} } class SavingsAccount extends
Account {
SavingsAccount()
{ balance = 0;
} } public class
BankAccount {
public static void main(String[] args) {
SavingsAccount account = new SavingsAccount();
account.deposit(5000);
account.displayBalance();
account.withdraw(2000);
account.displayBalance();
account.withdraw(4000);
account.displayBalance();
}
}
OUTPUT:-
BankAccount.java
javac
BankAccount.java java
BankAccount
Deposited: 5000.0
Current Balance: 5000.0
Withdrawn: 2000.0
Page 5
WAP to
CODE:
circle.draw();
rectangle.draw();
}
}
OUTPUT:-
AbstractExample.java
javac
AbstractExample.java java
AbstractExample Drawing
Circle
Drawing Rectangle
Q7 design a String class that perform String Method(Equal,Reverse the
string,change case).
CODE:
class StringOperations {
Page 6
WAP to
String str;
StringOperations(String str)
{ this.str = str;
}
boolean equals(String other)
{ return str.equals(other);
}
String reverse()
{ String reversed =
"";
for (int i = str.length() - 1; i >= 0; i--)
{ reversed += str.charAt(i);
}
return reversed;
}
String changeCase()
{ String result = "";
for (int i = 0; i < str.length(); i++) { char
ch = str.charAt(i); if
(Character.isLowerCase(ch)) { result
+= Character.toUpperCase(ch);
} else { result +=
Character.toLowerCase(ch);
} }
return result;
} }
public class StringMethodsExample
{ public static void main(String[] args) {
StringOperations strOps = new StringOperations("Hello World");
System.out.println("Original String: " + strOps.str);
System.out.println("Check if equal to 'Hello World': " + strOps.equals("Hello
World"));
System.out.println("Check if equal to 'hello world': " + strOps.equals("hello world"));
System.out.println("Reversed String: " + strOps.reverse());
System.out.println("Changed Case: " + strOps.changeCase());
}
}
OUTPUT:-
StringMethodsExample.java
javac
StringMethodsExample.java java
StringMethodsExample Original
String: Hello World
Check if equal to 'Hello World': true
Check if equal to 'hello world': false
Reversed String: dlroW olleH
Changed Case: hELLO wORLD
Page 7
WAP to
Q8 handle the Exception using try and multiple catch block. CODE
try {
System.out.print("Enter a number: ");
int num1 = scanner.nextInt();
int result = num1 / num2; // Division operation that might throw an exception
System.out.println("Division Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Cannot divide by zero.");
} catch (java.util.InputMismatchException e) {
System.out.println("Error: Invalid input. Please enter valid integers.");
} catch (Exception e) {
System.out.println("Error: Something went wrong.");
} finally
{ scanner.close();
System.out.println("Scanner
closed."); }
}
}
OUTPUT:-
MultipleCatchExample.java
javac
MultipleCatchExample.java
java MultipleCatchExample
Input 1:
Enter a number: 10
Enter another number: 2
OUTPUT:- 1:
Division Result: 5
Scanner closed.
Page 8
WAP
CODE:
interface Vehicle {
void start(); void
stop(); void
accelerate();
}
@Override public
void stop() {
System.out.println("Car is stopping...");
}
}
OUTPUT:-
InterfacePartialImplementation.java
javac
InterfacePartialImplementation.java java
InterfacePartialImplementation Car is
starting...
SportsCar is accelerating...
Car is stopping...
Q10 WAP to create a thread that Implement the Runable interface.
CODE:
Page 9
class MyThread implements Runnable {
@Override public
void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("Thread is running: " + i);
try {
Thread.sleep(500); // Pause for 500 milliseconds
} catch (InterruptedException e) {
System.out.println("Thread
interrupted"); }
}
}
}
OUTPUT:-
ThreadExample.java
javac
ThreadExample.java java
ThreadExample Thread is
running: 1
Main thread: 1
Thread is running: 2
Main thread: 2
Thread is running: 3
Main thread: 3
Thread is running: 4
Main thread: 4
Thread is running: 5
Main thread: 5
Page 10
WAP to create a
Q11 class component that show controls and event handling on that
controls.(math calc).
CODE:
Page 11
result = num1 + num2;
} else if (e.getSource() == subtractButton)
{ result = num1 - num2;
} else if (e.getSource() == multiplyButton) {
result = num1 * num2;
} else if (e.getSource() == divideButton)
{ if (num2 != 0) {
result = num1 / num2;
} else { resultField.setText("Error: Divide
by 0");
return;
} }
resultField.setText(String.valueOf(result));
} catch (NumberFormatException ex)
{ resultField.setText("Error: Invalid Input");
} }
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
CalculatorGUI calculator = new CalculatorGUI();
calculator.setVisible(true);
});
}
}
OUTPUT:-
CalculatorGUI.java
javac
CalculatorGUI.java java
CalculatorGUI
| Number 1: [ ]|
| Number 2: [ ]|
| [ Add ] [Subtract] |
| [Multiply] [ Divide ] |
| Result: [ ]
Result: 15.0
Page 12
WAP to create a
CODE:
Q12 Menu using the frame.
Page 13
});
} }
OUTPUT:-
MenuExample.java
javac
MenuExample.java java
MenuExample
+ +
| File Edit Help |
| |
| |
| |
| [ Application Frame ] |
| |
File
Open
Save
Exit
Open selected
File
Open
Save
Exit
Save selected
Q13 Dialogbox.
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
Page 14
WAP to create a
CODE:
public void actionPerformed(ActionEvent e) {
JDialog dialog = new JDialog(DialogBoxExample.this, "Sample Dialog",
true); dialog.setSize(250, 150); dialog.setLayout(null);
JLabel messageLabel = new JLabel("This is a dialog
box!"); messageLabel.setBounds(50, 30, 150, 20);
dialog.add(messageLabel);
JButton okButton = new JButton("OK");
okButton.setBounds(80, 70, 80, 30);
dialog.add(okButton);
okButton.addActionListener(event -> dialog.dispose());
dialog.setLocationRelativeTo(DialogBoxExample.this);
dialog.setVisible(true);
}
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
DialogBoxExample frame = new DialogBoxExample();
frame.setVisible(true);
}); } }
OUTPUT:-
DialogBoxExample.java
javac
DialogBoxExample.java
java DialogBoxExample
+ +
| [ Show Dialog ] |
+ +
| Sample Dialog |
| | | This is a dialog
box! |
Page 15
| |
| [ OK ] |
+
---+
| Sample Dialog
|
|
--|
| This is a dialog
box! |
| |
| [ OK ] |
+
---+
Page 16
WAP to
CODE:
Q14 Implement the flow layout And Border Layout
import javax.swing.*;
import java.awt.*;
OUTPUT:-
LayoutExample.java
javac
LayoutExample.java java
LayoutExample
+ +
| [ North ] |
| |
| [ West ] [ Center ] [East]|
| |
Page 17
| [ South ] |
+ +
| [ Button 1 ] [ Button 2 ] [ Button 3 ]|
| [ Button 4 ] [ Button 5 ] |
CODE:
Page 18
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
LayoutExample frame = new LayoutExample();
frame.setVisible(true);
}); } }
OUTPUT:-
+ +
| Card 1 |
| [ Card 1 ] |
++
++
| Card 2 |
| [ Card 2 ] |
++
++
| Card 3 |
| [ Card 3 ] |
+ +
Page 19
Q16 Demonstrate Network programming
CODE:
SERVER CODE
import java.net.*;
import java.io.*;
public class Server
{
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(1234);
System.out.println("Server is waiting for client...");
Socket socket = serverSocket.accept();
System.out.println("Client connected.");
BufferedReader input = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter OUTPUT:- = new PrintWriter(socket.getOUTPUT:-Stream(),
true);
String clientMessage = input.readLine();
System.out.println("Client: " + clientMessage);
OUTPUT:-.println("Hello from Server!");
socket.close();
serverSocket.close();
}
}
CLIENT CODE
import java.net.*;
import java.io.*;
public class Client
{
public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 1234);
BufferedReader input = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter OUTPUT:- = new PrintWriter(socket.getOUTPUT:-Stream(),
true);
OUTPUT:-.println("Hello from Client!");
String serverResponse = input.readLine();
System.out.println("Server: " +
serverResponse); socket.close();
}
}
OUTPUT:-
Server OUTPUT:-:
Page 20
Server is waiting for client...
Client connected.
Client: Hello from Client!
Client OUTPUT:-:
Server: Hello from Server!
Q17 WAP to retrieve IPAddress of a local machine on a network.
CODE:
import java.net.*;
OUTPUT:-
GetIPAddress.java
javac
GetIPAddress.java java
GetIPAddress
IP Address of local machine: 192.168.1.5
Page 21
Q18 Demonstrate Mouse event Handling
CODE:
import java.awt.*;
import java.awt.event.*;
OUTPUT:-
MouseEventExample.java
javac
MouseEventExample.java java
MouseEventExample Mouse
Entered the Frame
Mouse Clicked at (x, y)
Page 22
Mouse Pressed at (x, y)
Mouse Released at (x, y)
Mouse Exited the Frame
Q19 Demonstrate Keyboard event Handling
CODE:
import java.awt.*;
import java.awt.event.*;
OUTPUT:-
KeyboardEventExample.java
javac
KeyboardEventExample.java java
KeyboardEventExample Key
Pressed: [key_char]
Key Released: [key_char]
Key Typed: [key_char]
Page 23
to
1. Import JDBC Packages: You need to import the necessary JDBC classes to interact
with the database.
2. Load Database Driver: You must load the database driver for the specific database
you are using (e.g., MySQL, Oracle, etc.).
3. Create a Connection: You need to use the DriverManager.getConnection() method to
establish the connection to the database.
4. Create a Statement: Once the connection is established, you can create a statement
object to execute SQL queries.
5. Execute Query: Use the statement object to execute queries (e.g., SELECT, INSERT,
UPDATE, etc.).
6. Close the Connection: After finishing the database operations, close the connection to
release the resources.
Code:
import java.sql.*;
Page 24
e.printStackTrace();
} finally { try { if
(conn != null)
{ conn.close();
System.out.println("Connection Closed.");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
OUTPUT:-
Page 25
WAP to
CODE:
Q21 retrieve a records from a table
OUTPUT:-
Page 26
WAP to
CODE:
Q22 execute SQL statements using java whiout comment with OUTPUT:-
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
try {
Connection connection = DriverManager.getConnection(url, username, password);
Statement statement = connection.createStatement();
String insertSQL = "INSERT INTO employees (id, name, department) VALUES (1,
'Alice', 'HR'), (2, 'Bob', 'IT')"; int rowsInserted =
statement.executeUpdate(insertSQL);
System.out.println("Rows inserted: " + rowsInserted);
statement.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
OUTPUT:-
Page 27
WAP to
CODE:
Rows inserted: 2
Rows updated: 1
Rows deleted: 1
Q23 update data in a table
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
OUTPUT:-
Rows updated: 1
Page 28
WAP to
CODE:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
try {
Connection connection = DriverManager.getConnection(url, username, password);
Statement statement = connection.createStatement();
statement.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
OUTPUT:-
Rows deleted: 1
And the table will now contain:
id name department
1 RAJNISHMISHRA HR
Page 29
a
CODE:
@WebServlet("/hello")
public class HelloWorldServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/plain");
response.getWriter().write("Hello, World!"); }
}
OUTPUT:-
Hello, World!
Page 30
Q26 Create a servlet to handle form data submitted via a POST request.
CODE:
OUTPUT:-
http://localhost:8080/your-webapp/form.html
Form Submission
Name: [ ]
Email: [ ]
[Submit ]
Page 31
a
Q27Create servlet that demonstrates session management by storing and retrieving user
information in a session.
CODE:
Page 32
response.getWriter().write("</body></
html>"); } }
Page 33
<!DOCTYPE html>
<html>
<head>
<title>Session Demo</title>
</head>
<body>
<h1>Session Management Demo</h1>
<form action="sessionDemo" method="POST">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required><br><br>
<button type="submit">Submit</button>
</form>
</body>
</html>
OUTPUT:-
Name:RAJNISHMISHRA
Email:[email protected]
[Retrieve Session Data]
Name:RAJNISHMISHRA
Email: [email protected]
Q28Create simple JSP page that displays "Hello, World!".
CODE:
<!DOCTYPE html>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h1>Hello, World!</h1>
</body>
</html>
OUTPUT:-
Page 34
a
Hello, World!
Page 35
a
CODE:
package com.example;
public User() {
}
public String getName()
{ return name;
}
public void setName(String name)
{ this.name = name;
}
public String getEmail()
{ return email;
}
public void setEmail(String email)
{ this.email = email;
}
}
<!DOCTYPE html>
<html>
<head>
<title>JavaBean Example</title>
</head>
<body>
<h1>User Details</h1>
<p>Name: <jsp:getProperty name="user" property="name" /></p>
<p>Email: <jsp:getProperty name="user" property="email" /></p>
</body>
</html>
Page 36
a
OUTPUT:-
User Details
Name: RAJNISHMISHRA
Email: [email protected]
Q30 Create JSP page that uses directives and scriptlets to display dynamic content.
CODE:
<!DOCTYPE html>
<html>
<head>
<title>Dynamic Content Example</title>
</head>
<body>
<h1>Dynamic Content Example</h1> <
%
String userName = "John Doe";
LocalDateTime currentTime = LocalDateTime.now();
%>
<p>Welcome, <%= userName %>!</p>
<p>Current Date and Time: <%= currentTime %></p>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Dynamic Content Example</title>
</head>
<body>
<h1>Dynamic Content Example</h1>
<p>Welcome,RAJNISHMISHRA!</p>
<p>Current Date and Time: 2024-11-21T10:45:00</p>
</body>
</html>
OUTPUT:-
Page 37
a
Welcome, RAJNISHMISHRA!
Current Date and Time: 2024-11-21T10:45:00
Page 38