0% found this document useful (0 votes)
14 views

Lab Manual

Uploaded by

Jayantraj Pundir
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Lab Manual

Uploaded by

Jayantraj Pundir
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

1: Java program to find the sum of odd and even numbers in an array:

public class SumOfOddEven {


public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int sumEven = 0;
int sumOdd = 0;

for (int num : arr) {


if (num % 2 == 0) {
sumEven += num;
} else {
sumOdd += num;
}
}

System.out.println("Sum of even numbers: " + sumEven);


System.out.println("Sum of odd numbers: " + sumOdd);
}
}
Output:
Sum of even numbers: 30
Sum of odd numbers: 25
2. Java program to print the prime numbers between n1 to n2 using class,
objects, and methods:
public class PrimeNumbers {
public static void main(String[] args) {
int n1 = 10, n2 = 50;
printPrimeNumbers(n1, n2);
}

static boolean isPrime(int num) {


if (num <= 1) return false;
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) return false;
}
return true;
}

static void printPrimeNumbers(int start, int end) {


System.out.println("Prime numbers between " + start + " and " + end +
":");
for (int i = start; i <= end; i++) {
if (isPrime(i)) {
System.out.print(i + " ");
}
}
}
}
Output:
Prime numbers between 10 and 50:
11 13 17 19 23 29 31 37 41 43 47
3. Java program for calculating the age of a person and displaying the age in the
form of years, months, and days:
import java.time.LocalDate;
import java.time.Period;
public class AgeCalculator {
public static void main(String[] args) {
LocalDate birthDate = LocalDate.of(1990, 5, 15);
LocalDate currentDate = LocalDate.now();
Period age = Period.between(birthDate, currentDate);
System.out.println("Age: " + age.getYears() + " years, " + age.getMonths()
+ " months, " + age.getDays() + " days");
}
}
Output:
Age: 33 years, 8 months, 12 days
4. Java program demonstrating method overloading for different types of
transaction modes:
public class Transaction {
public void transferMoney(int amount) {
// Default method for transferring money
System.out.println("Transferring money using default method: " + amount);
}

public void transferMoney(String mode, int amount) {


// Method overloading for different transaction modes
System.out.println("Transferring money using " + mode + " mode: " +
amount);
}

public void transferMoney(String mode, int amount, String accountNumber) {


// Method overloading for different transaction modes and account numbers
System.out.println("Transferring money using " + mode + " mode to
account " + accountNumber + ": " + amount);
}

public static void main(String[] args) {


Transaction transaction = new Transaction();
transaction.transferMoney(1000);
transaction.transferMoney("Credit card", 2000);
transaction.transferMoney("Net banking", 3000, "1234567890");
}
}
Output:
Transferring money using default method: 1000
Transferring money using Credit card mode: 2000
Transferring money using Net banking mode to account 1234567890: 3000
5. Java program using abstract class to calculate the area of different shapes by overriding methods:

abstract class Shape {

abstract double area();

class Rectangle extends Shape {

double length;

double width;

Rectangle(double length, double width) {

this.length = length;

this.width = width;

@Override

double area() {

return length * width;

class Circle extends Shape {

double radius;

Circle(double radius) {

this.radius = radius;

@Override

double area() {

return Math.PI * radius * radius;

public class AreaCalculator {

public static void main(String[] args) {

Rectangle rectangle = new Rectangle(5, 4);


Circle circle = new Circle(3);

System.out.println("Area of rectangle: " + rectangle.area());

System.out.println("Area of circle: " + circle.area());

Output:

Area of rectangle: 20.0

Area of circle: 28.274333882308138

6. Java program for Library application using multiple inheritances:

class LibraryItem {

String title;

int id;

void issue() {

// Issue operation

void returnItem() {

// Return operation

class Book extends LibraryItem {

String author;

int pages;

void search() {

// Search operation

}
void renew() {

// Renew operation

void fineCalculation() {

// Fine calculation

class Magazine extends LibraryItem {

String category;

String publicationDate;

void issue() {

// Issue operation for magazine

class Journal extends LibraryItem {

String journalType;

void issue() {

// Issue operation for journal

public class Library extends Book {

public static void main(String[] args) {

// Operations related to Library

}
7. Java program for banking application with exception handling:

class InsufficientBalanceException extends Exception {

InsufficientBalanceException(String message) {

super(message);

class TransactionCountExceededException extends Exception {

TransactionCountExceededException(String message) {

super(message);

class TransactionAmountExceededException extends Exception {

TransactionAmountExceededException(String message) {

super(message);

class BankingApplication {

int balance = 100000;

int transactionCount = 0;

void withdraw(int amount) throws InsufficientBalanceException,


TransactionCountExceededException, TransactionAmountExceededException {

if (amount > balance) {

throw new InsufficientBalanceException("Insufficient balance");

if (transactionCount >= 3) {

throw new TransactionCountExceededException("Transaction count exceeds limit");


}

if (amount > 100000) {

throw new TransactionAmountExceededException("Transaction amount exceeds limit");

balance -= amount;

transactionCount++;

System.out.println("Withdrawal successful. Remaining balance: " + balance);

public class BankApplicationDemo {

public static void main(String[] args) {

BankingApplication bank = new BankingApplication();

try {

bank.withdraw(50000);

bank.withdraw(30000);

bank.withdraw(20000);

bank.withdraw(40000); // This will throw an exception

} catch (InsufficientBalanceException | TransactionCountExceededException |


TransactionAmountExceededException e) {

System.out.println("Error: " + e.getMessage());

Output:

Withdrawal successful. Remaining balance: 50000

Withdrawal successful. Remaining balance: 20000

Withdrawal successful. Remaining balance: 0

Error: Transaction count exceeds limit

8. Create a student database and store the details of the students in a table. Perform the SELECT,
INSERT, UPDATE and DELETE operations using JDBC connectivity
import java.sql.*;

public class StudentDatabase {

// JDBC URL, username, and password

static final String JDBC_URL = "jdbc:mysql://localhost:3306/student_db";

static final String USERNAME = "your_username";

static final String PASSWORD = "your_password";

public static void main(String[] args) {

Connection connection = null;

Statement statement = null;

try {

// Register JDBC driver

Class.forName("com.mysql.cj.jdbc.Driver");

// Open a connection

System.out.println("Connecting to database...");

connection = DriverManager.getConnection(JDBC_URL, USERNAME, PASSWORD);

// Create table

System.out.println("Creating table...");

statement = connection.createStatement();

String createTableSQL = "CREATE TABLE IF NOT EXISTS students (" +

"id INT AUTO_INCREMENT PRIMARY KEY," +

"name VARCHAR(100) NOT NULL," +

"age INT NOT NULL)";

statement.executeUpdate(createTableSQL);

System.out.println("Table created successfully");

// Insert data

System.out.println("Inserting data...");
String insertSQL = "INSERT INTO students (name, age) VALUES (?, ?)";

PreparedStatement preparedStatement = connection.prepareStatement(insertSQL);

preparedStatement.setString(1, "John");

preparedStatement.setInt(2, 20);

int rowsInserted = preparedStatement.executeUpdate();

if (rowsInserted > 0) {

System.out.println("Data inserted successfully");

// Select data

System.out.println("Selecting data...");

String selectSQL = "SELECT * FROM students";

ResultSet resultSet = statement.executeQuery(selectSQL);

while (resultSet.next()) {

int id = resultSet.getInt("id");

String name = resultSet.getString("name");

int age = resultSet.getInt("age");

System.out.println("ID: " + id + ", Name: " + name + ", Age: " + age);

// Update data

System.out.println("Updating data...");

String updateSQL = "UPDATE students SET age = ? WHERE name = ?";

preparedStatement = connection.prepareStatement(updateSQL);

preparedStatement.setInt(1, 21);

preparedStatement.setString(2, "John");

int rowsUpdated = preparedStatement.executeUpdate();

if (rowsUpdated > 0) {

System.out.println("Data updated successfully");

}
// Delete data

System.out.println("Deleting data...");

String deleteSQL = "DELETE FROM students WHERE name = ?";

preparedStatement = connection.prepareStatement(deleteSQL);

preparedStatement.setString(1, "John");

int rowsDeleted = preparedStatement.executeUpdate();

if (rowsDeleted > 0) {

System.out.println("Data deleted successfully");

} catch (ClassNotFoundException | SQLException e) {

e.printStackTrace();

} finally {

// Close resources

try {

if (statement != null) {

statement.close();

if (connection != null) {

connection.close();

} catch (SQLException e) {

e.printStackTrace();

Make sure to replace "your_username" and "your_password" with your actual MySQL database
username and password respectively.

Output:

Connecting to database...
Creating table...

Table created successfully

Inserting data...

Data inserted successfully

Selecting data...

ID: 1, Name: John, Age: 20

Updating data...

Data updated successfully

Deleting data...

Data deleted successfully

9. Create a HTML login page (login.html) with username and password fields.

Create a servlet (LoginServlet.java) to handle the login request and validate the username and
password.

Configure the servlet mapping in web.xml file.

Create a database table to store user credentials.

Connect to the database and validate the user credentials in the servlet.

Below is the solution for the above steps:

login.html (HTML login page):

html

Copy code

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Login Page</title>

</head>

<body>

<h2>Login</h2>

<form action="login" method="post">


Username: <input type="text" name="username"><br>

Password: <input type="password" name="password"><br>

<input type="submit" value="Login">

</form>

</body>

</html>

LoginServlet.java (Servlet to handle login request and validate credentials):

java

Copy code

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

import java.sql.*;

public class LoginServlet extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

String username = request.getParameter("username");

String password = request.getParameter("password");

try {

Class.forName("com.mysql.jdbc.Driver");

Connection con = DriverManager.getConnection(

"jdbc:mysql://localhost:3306/your_database_name", "username", "password");

PreparedStatement ps = con.prepareStatement(

"select * from users where username=? and password=?");

ps.setString(1, username);
ps.setString(2, password);

ResultSet rs = ps.executeQuery();

if (rs.next()) {

out.println("Welcome " + username);

} else {

out.println("Invalid username or password");

} catch (Exception e) {

System.out.println(e);

out.close();

web.xml (Servlet mapping):

xml

Copy code

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns="http://xmlns.jcp.org/xml/ns/javaee"

xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"

id="WebApp_ID" version="4.0">

<servlet>

<servlet-name>LoginServlet</servlet-name>

<servlet-class>LoginServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>LoginServlet</servlet-name>

<url-pattern>/login</url-pattern>

</servlet-mapping>
<welcome-file-list>

<welcome-file>login.html</welcome-file>

</welcome-file-list>

</web-app>

Create a database table named users with columns username and password. Insert some sample
data into the table.

Configure the database connection details (jdbc:mysql://localhost:3306/your_database_name,


username, password) in LoginServlet.java.

Output:

When a user enters valid credentials, it will display "Welcome [username]".

When a user enters invalid credentials, it will display "Invalid username or password".

Make sure to replace "your_database_name", "username", and "password" with your actual
database name, username, and password respectively.

You might also like