CSE B 07917702722 MANEET
Experiment 1
Aim: Write a Java program to print numbers from 1 to n. For multiples of 3,
print "Fizz" instead of the number, and for multiples of 5, print "Buzz". For
numbers that are multiples of both 3 and 5, print "FizzBuzz".
Code:
import java.util.Scanner;
class fizz {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter 1st number: ");
int a = sc.nextInt();
System.out.println("Enter 2nd number: ");
int b = sc.nextInt();
for(int i=a;i<=b;i++)
{
if(i%15==0)
System.out.println("FizzBuzz");
else if(i%3==0)
System.out.println("Fizz");
else if(i%5==0)
System.out.println("Buzz");
else
System.out.println(i);
}
}
}
CSE B 07917702722 MANEET
Output:
Learning Outcomes:
CSE B 07917702722 MANEET
Experiment 2
Aim: Create an abstract class BankAccount with the following:
a) An accountNumber (String) and balance (double) as instance variables.
b) A constructor to initialize the account number and balance.
c) Abstract methods:
• deposit(double amount)
• withdraw(double amount)
d) Create two subclasses:
SavingsAccount:
• Has an additional variable interestRate (double).
• Overrides the deposit method to add interest to the balance. • Withdrawals are
allowed only if the balance remains above a certain minimum (e.g., 500).
CurrentAccount:
• Has an additional variable overdraftLimit (double).
• Overrides the withdraw method to allow overdraft up to the specified limit.
Write a program that:
e) Creates objects of both subclasses.
f) Performs deposit and withdrawal operations.
g) Displays the final account details for each object.
Code:
abstract class BankAccount {
String accountNumber;
double balance;
BankAccount() {}
BankAccount(String a, double b) {
accountNumber = a;
balance = b;
}
abstract void deposit(double amount);
abstract void withdraw(double amount);
public void disp() {
System.out.println("Account number: " + accountNumber);
System.out.println("Balance: " + balance);
System.out.println();
}
CSE B 07917702722 MANEET
class SavingsAccount extends BankAccount {
double interestRate;
SavingsAccount() {}
SavingsAccount(String accountNumber, double balance, double ir) {
super(accountNumber, balance);
interestRate = ir;
}
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
balance += balance * (interestRate / 100);
System.out.println("Deposit successful. New Balance: " +
balance);
} else {
System.out.println("Invalid Amount");
}
}
public void withdraw(double amount) {
if (balance - amount > 500) {
balance -= amount;
System.out.println("Amount withdrawn: " + amount);
System.out.println("Balance amount is: " + balance);
} else {
System.out.println("Insufficient Balance");
}
}
}
class CurrentAccount extends BankAccount {
double overdraftLimit;
CurrentAccount(String accountNumber, double balance, double odl) {
super(accountNumber, balance);
overdraftLimit = odl;
CSE B 07917702722 MANEET
}
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("Deposit successful. New Balance: " +
balance);
} else {
System.out.println("Invalid Amount");
}
}
public void withdraw(double amount) {
if (balance - amount > overdraftLimit) {
balance -= amount;
System.out.println("Withdrawal Successful. New balance: " +
balance);
} else {
System.out.println("Invalid amount. Overdraft Limit
exceeded.");
}
}
}
public class Main {
public static void main(String[] args) {
SavingsAccount savingsAccount = new SavingsAccount("SA123", 1000,
5);
System.out.println("\nSavings Account:");
savingsAccount.disp();
savingsAccount.deposit(500);
savingsAccount.withdraw(200);
savingsAccount.withdraw(1000);
System.out.println("Final account details are:");
savingsAccount.disp();
System.out.println();
CurrentAccount currentAccount = new CurrentAccount("CA456", 2000,
1000);
System.out.println("\nCurrent Account:");
CSE B 07917702722 MANEET
currentAccount.disp();
currentAccount.deposit(300);
currentAccount.withdraw(2500);
currentAccount.withdraw(1000);
System.out.println("Final account details are:");
currentAccount.disp();
}
}
CSE B 07917702722 MANEET
Output:
Learning Outcomes:
CSE B 07917702722 MANEET
Experiment 3
Aim: Write an efficient code in java to check all the prime numbers in a given
range of numbers.
CSE B 07917702722 MANEET
Code:
import java.util.Scanner;
public class Prime1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the starting number (a): ");
int a = sc.nextInt();
System.out.print("Enter the ending number (b): ");
int b = sc.nextInt();
for (int i = a; i <= b; i++) {
int c = 0;
if (i % 2 == 0 && i > 2) {
System.out.println(i + " is not a prime number");
continue;
}
for (int j = 2; j <= Math.sqrt(i); j++) {
if (i % j == 0) {
c++;
break;
}
}
if (c == 0 && i > 1) {
System.out.println(i + " is a prime number");
CSE B 07917702722 MANEET
}
else {
System.out.println(i + " is not a prime number");
}
}
sc.close();
}
}
Output:
Learning Outcomes:
CSE B 07917702722 MANEET
Experiment 4
Aim: N soldiers (or people) stand in a circle. The king gives a sword to the first
soldier, who kills the person to their left and passes the sword to the next
surviving person. This process continues until only one person remains. Write a
java program to find the safe position to stand. Assuming first position is=1.
Theory:
CSE B 07917702722 MANEET
Code:
import java.util.Scanner;
public class Soldiers {
public static int solution(int n) {
if (n == 1)
return 1;
else
return (solution(n - 1) + 1) % n + 1;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of soldiers: ");
int n = sc.nextInt();
sc.close();
int safePosition = solution(n);
System.out.println("The safe position is: " + safePosition);
}
}
CSE B 07917702722 MANEET
Output:
Learning Outcomes:
CSE B 07917702722 MANEET
Experiment 5
Aim: Write a two thread based program in java, where thread1 adds
all even numbers and thread2 adds all odd numbers from a given file
which has large number of positive integers.
Code:
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class numbers {
public static void main(String[] args) {
try (FileWriter writer = new FileWriter("all.txt")) {
Random r = new Random();
for (int i = 0; i < 10; i++) {
int num = r.nextInt(1000) + 1;
writer.write(String.format("%d%n", num));
}
} catch (IOException e) {
System.err.println("Error writing to file: " +
e.getMessage());
}
System.out.println("\nRandom numbers saved to all.txt");
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.submit(new EvenNumberAdder("all.txt"));
executor.submit(new OddNumberAdder("all.txt"));
executor.shutdown();
}
}
class EvenNumberAdder implements Runnable {
CSE B 07917702722 MANEET
private String filename;
public EvenNumberAdder(String filename) {
this.filename = filename;
}
@Override
public void run() {
try (Scanner scanner = new Scanner(new java.io.File(filename)))
{
int sum = 0;
while (scanner.hasNextInt()) {
int num = scanner.nextInt();
if (num % 2 == 0) {
sum += num;
}
}
System.out.println("Sum of even numbers: " + sum);
} catch (IOException e) {
System.err.println("Error reading from file: " +
e.getMessage());
}
}
}
class OddNumberAdder implements Runnable {
private String filename;
public OddNumberAdder(String filename) {
this.filename = filename;
}
@Override
public void run() {
try (Scanner scanner = new Scanner(new java.io.File(filename)))
{
int sum = 0;
CSE B 07917702722 MANEET
while (scanner.hasNextInt()) {
int num = scanner.nextInt();
if (num % 2 != 0) {
sum += num;
}
}
System.out.println("Sum of odd numbers: " + sum);
} catch (IOException e) {
System.err.println("Error reading from file: " +
e.getMessage());
}
}
}
Output:
Learning Outcomes:
CSE B 07917702722 MANEET
Experiment 6
Aim: Write a java program using Java Database
Connectivity (JDBC) to:
1. Fetch all the records from the employee table.
2. Search employee with empid
3. Update specific employee details
4. Delete a particular employee record
Employee has fields in MySQL Empid, EmpName,
EmpCity, EmpSalary.
Setup:
CSE B 07917702722 MANEET
CSE B 07917702722 MANEET
Code:
import java.sql.*;
import java.util.Scanner;
public class jdbc {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/maneet"; // Change
"testdb" to your database name
String user = "root"; // Default XAMPP user
String password = ""; // Default XAMPP password (empty)
try {
// Load MySQL JDBC Driver
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection(url, user,
password);
System.out.println("\nConnected to the database!");
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("\nEnter an SQL query (or type 'exit'
to quit):");
String query = scanner.nextLine().trim();
if (query.equalsIgnoreCase("exit")) {
System.out.println("Exiting program...");
break;
}
try (Statement stmt = conn.createStatement()) {
if (query.toLowerCase().startsWith("select")) {
ResultSet rs = stmt.executeQuery(query);
ResultSetMetaData metaData = rs.getMetaData();
int columnCount = metaData.getColumnCount();
// Print column names
for (int i = 1; i <= columnCount; i++) {
System.out.printf("%-15s",
metaData.getColumnName(i));
}
System.out.println("\
n-------------------------------------------------");
// Print rows
while (rs.next()) {
for (int i = 1; i <= columnCount; i++) {
System.out.printf("%-15s",
rs.getString(i));
}
System.out.println();
}
} else {
CSE B 07917702722 MANEET
int rowsAffected = stmt.executeUpdate(query);
System.out.println("Query executed successfully.
Rows affected: " + rowsAffected);
}
} catch (SQLException e) {
System.out.println("Error executing query: " +
e.getMessage());
}
}
// Close resources
conn.close();
scanner.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
Learning Outcomes: