Java Lab File

Download as pdf or txt
Download as pdf or txt
You are on page 1of 22

JAVA PROGRAMMING LAB FILE

ICT-312P
Submitted in partial fulfilment of the requirements for the award of the degree
of
B.Tech.
in
Information Technology

SUBMITTED TO: SUBMITTED BY:


Prof. JASPREETI SINGH NAME – ABHISHEK KUMAR
ENROLLMENT NO.-04716401521
BATCH - 2021-25(6th sem)

UNIVERSITY SCHOOL OF INFORMATION COMMUNICATION AND TECHNOLOGY


GURU GOBIND SINGH INDRAPRASTHA UNIVERSITY
MAY – 2024
INDEX
S.NO. NAME OF PRACTICAL DATE SIGN

Write a program to print the reverse of the numbers, the


1
number is take as input form the user.
Program to maintain bank account. Extend Bank account
2
details to current and saving account.

3 Program to maintain bank account using packages.

Program to run the main thread and perform operations


4
on it. Change the name and priority of the main thread.

Program to illustrate the working of the child threads in


5
concurrence with the main thread.

Program to illustrate that the high priority thread occupies


6
more CPU cycles as compared to a low priority thread.

Program to print the table of 5 and 7 using threads and in


7
synchronized manner.

Program to take a string array as "100", "10.2", "5.hello",


8 "100hello" and check whether it contains valid integer or
double using exception handling.

Program to create a user defined exception


9 ‘MyException’ and throw this exception when the age
entered is less than 18.
Implement the concept of producer consumer problem
10 using the concept of multithreading
PRACTICAL 1
Aim: Write a program to print the reverse of the numbers, the number is take as
input form the user.

CODE:

OUTPUT:
PRACTICAL 2
Aim: Program to maintain bank account. Extend Bank account details to current
and saving account.

CODE:
import java.util.Scanner;

class BankAccount {
protected String accountNumber;
protected double balance;
public BankAccount(String accountNumber, double balance) {
this.accountNumber = accountNumber;
this.balance = balance;
}
public void deposit(double amount) {
balance += amount;
System.out.println("Deposit successful. New balance: " + balance);
}
public void withdraw(double amount) {
if (balance >= amount) {
balance -= amount;
System.out.println("Withdrawal successful. New balance: " + balance);
}
else {
System.out.println("Insufficient funds.");
}
}

public void displayBalance() {


System.out.println("Account Number: " + accountNumber);
System.out.println("Balance: " + balance);
}
}

class CurrentAccount extends BankAccount {


private double overdraftLimit;
public CurrentAccount(String accountNumber, double balance, double overdraftLimit) {
super(accountNumber, balance);
this.overdraftLimit = overdraftLimit;
}
@Override
public void withdraw(double amount) {
if (balance + overdraftLimit >= amount) {
balance -= amount;
System.out.println("Withdrawal successful. New balance: " + balance);
} else {
System.out.println("Insufficient funds (including overdraft limit).");
}
}
}

class SavingsAccount extends BankAccount {


private double interestRate;

public SavingsAccount(String accountNumber, double balance, double interestRate) {


super(accountNumber, balance);
this.interestRate = interestRate;
}

public void addInterest() {


balance += balance * interestRate / 100;
System.out.println("Interest added. New balance: " + balance);
}
}

public class Main {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
CurrentAccount currentAccount = new CurrentAccount("123456", 1000.0, 500.0);
SavingsAccount savingsAccount = new SavingsAccount("789012", 2000.0, 5.0);

int choice;
do {
System.out.println("\n1. Deposit");
System.out.println("2. Withdraw");
System.out.println("3. Display Balance");
System.out.println("4. Add Interest (Savings Account)");
System.out.println("0. Exit");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();

switch (choice) {
case 1:
System.out.print("Enter amount to deposit: ");
double depositAmount = scanner.nextDouble();
currentAccount.deposit(depositAmount);
break;
case 2:
System.out.print("Enter amount to withdraw: ");
double withdrawAmount = scanner.nextDouble();
currentAccount.withdraw(withdrawAmount);
break;
case 3:
currentAccount.displayBalance();
break;
case 4:
savingsAccount.addInterest();
break;
case 0:
System.out.println("Exiting...");
break;
default:
System.out.println("Invalid choice.");
}
} while (choice != 0);
}
}

OUTPUT:
PRACTICAL 3
Aim: Program to maintain bank account using packages.

CODE:

1. BankAccount.java
package com.bank.account;

class BankAccount {
protected String accountNumber;
protected double balance;
public BankAccount(String accountNumber, double balance) {
this.accountNumber = accountNumber;
this.balance = balance;
}
public void deposit(double amount) {
balance += amount;
System.out.println("Deposit successful. New balance: " + balance);
}
public void withdraw(double amount) {
if (balance >= amount) {
balance -= amount;
System.out.println("Withdrawal successful. New balance: " + balance);
}
else {
System.out.println("Insufficient funds.");
}
}

public void displayBalance() {


System.out.println("Account Number: " + accountNumber);
System.out.println("Balance: " + balance);
}
}

2. CurrentAccount.java
package com.bank.account;
import com.bank.account.BankAccount;

class CurrentAccount extends BankAccount {


private double overdraftLimit;
public CurrentAccount(String accountNumber, double balance, double overdraftLimit) {
super(accountNumber, balance);
this.overdraftLimit = overdraftLimit;
}
@Override
public void withdraw(double amount) {
if (balance + overdraftLimit >= amount) {
balance -= amount;
System.out.println("Withdrawal successful. New balance: " + balance);
} else {
System.out.println("Insufficient funds (including overdraft limit).");
}
}
}

3. SavingsAccount.java
package com.bank.account;
import com.bank.account.BankAccount;

class SavingsAccount extends BankAccount {


private double interestRate;

public SavingsAccount(String accountNumber, double balance, double interestRate) {


super(accountNumber, balance);
this.interestRate = interestRate;
}

public void addInterest() {


balance += balance * interestRate / 100;
System.out.println("Interest added. New balance: " + balance);
}
}

4. Main.java
package com.bank;
import com.bank.account.CurrentAccount;
import com.bank.account.SavingsAccount;

import java.util.Scanner;

public class Main {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
CurrentAccount currentAccount = new CurrentAccount("123456", 1000.0, 500.0);
SavingsAccount savingsAccount = new SavingsAccount("789012", 2000.0, 5.0);

int choice;
do {
System.out.println("\n1. Deposit");
System.out.println("2. Withdraw");
System.out.println("3. Display Balance");
System.out.println("4. Add Interest (Savings Account)");
System.out.println("0. Exit");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();

switch (choice) {
case 1:
System.out.print("Enter amount to deposit: ");
double depositAmount = scanner.nextDouble();
currentAccount.deposit(depositAmount);
break;
case 2:
System.out.print("Enter amount to withdraw: ");
double withdrawAmount = scanner.nextDouble();
currentAccount.withdraw(withdrawAmount);
break;
case 3:
System.out.print("Which account Current(1) or Savings(2): ");
double account=scanner.nextDouble();
if(account==1){
currentAccount.displayBalance();
}
else{
savingsAccount.displayBalance();
}
break;
case 4:
savingsAccount.addInterest();
break;
case 0:
System.out.println("Exiting...");
break;
default:
System.out.println("Invalid choice.");
}
} while (choice != 0);
}
}
OUTPUT:
1. Deposit
2. Withdraw
3. Display Balance
4. Add Interest (Savings Account)
0. Exit
Enter your choice: 3
Which account Current(1) or Savings(2): 2
Account Number: 789012
Balance: 2000.0

1. Deposit
2. Withdraw
3. Display Balance
4. Add Interest (Savings Account)
0. Exit
Enter your choice: 4
Interest added. New balance: 2100.0

1. Deposit
2. Withdraw
3. Display Balance
4. Add Interest (Savings Account)
0. Exit
Enter your choice: 0
Exiting...
Process finished with exit code 0

Structure of package in java (in src folder)


PRACTICAL 4
Aim: Program to run the main thread and perform operations on it. Change the
name and priority of the main thread.
CODE:
public class Main {
public static void main(String[] args) {
Thread t= Thread.currentThread();
System.out.println("Main Thread Running\n");
System.out.println("Initial Main Thread: " + t.getName());
System.out.println("Initial Priority: " + t.getPriority());
t.setName("Main_Updated");
t.setPriority(Thread.MAX_PRIORITY);
System.out.println("Updated Main Thread: " + t.getName());
System.out.println("Updated Priority: " + t.getPriority());
System.out.println("\nThread running for 5 seconds:");
for (int i = 1; i <= 5; i++) {
System.out.println(i);
try {
Thread.sleep(1000); // Sleep for 1 second
} catch (InterruptedException e) {
System.out.println(e);
}
}
System.out.println("Main Thread Ended.");
}
}

OUTPUT:
PRACTICAL 5
Aim: Program to illustrate the working of the child threads in concurrence with
the main thread.
CODE:
class MyThread extends Thread {
int num;
MyThread(int child_num){
num=child_num;
}
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("Child Thread " + num +": "+ i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}
class ChildThreadExample {
public static void main(String[] args) {
MyThread childThread1 = new MyThread(1);
MyThread childThread2 = new MyThread(2);
MyThread childThread3 = new MyThread(3);
childThread1.start();
childThread2.start();
childThread3.start();
for (int i = 1; i <= 5; i++) {
System.out.println("Main Thread: " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}
OUTPUT:
PRACTICAL 6
Aim: Program to illustrate that the high priority thread occupies more CPU cycles
as compared to a low priority thread.
CODE:
class Clicker implements Runnable {
long click = 0;
Thread t;
private volatile boolean running = true;
public Clicker (int p) {
t = new Thread(this);
t.setPriority(p);
}
public void run() {
while(running) {
click++;
}
}
public void stop() {
running = false;
}
public void start() {
t.start();
}
}

class Priority {
public static void main(String args[]) {
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
Clicker hi = new Clicker(Thread.NORM_PRIORITY + 2);
Clicker lo = new Clicker(Thread.NORM_PRIORITY - 2);
hi.start();
lo.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("main thread interrupted");
}
lo.stop();
hi.stop();
try {
hi.t.join();
lo.t.join();
} catch (InterruptedException e) {
System.out.println("interrupted exception catched in main");
}
System.out.println("low-priority thread : " + lo.click);
System.out.println("hi-priority thread : " + hi.click);
}
}

OUTPUT:
PRACTICAL 7
Aim: Program to print the table of 5 and 7 using threads and in synchronized
manner.
CODE:
class MyThread extends Thread {
int num;
MyThread(int child_num){
num=child_num;
}
public void run() {
synchronized(this){
for (int i = 1; i <= 10; i++) {
System.out.println(num +"*"+ i + "=" + num*i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}
}
class ChildThreadExample {
public static void main(String[] args) {
MyThread childThread1 = new MyThread(5);
MyThread childThread2 = new MyThread(7);
childThread1.start();
childThread2.start();
try{
childThread1.join();
childThread2.join();
}
catch(InterruptedException e){
System.out.println(e);
}
System.out.println("Main thread ended");
}
}
OUTPUT:
PRACTICAL 8
Aim: Program to take a string array as "100", "10.2", "5.hello", "100hello" and
check whether it contains valid integer or double using exception handling.
CODE:
class ValidNumber{
public static void main(String[] args) {
String[] array = {"100", "10.2", "5.hello", "100hello"};
for (int i=0;i<4;i++) {
String str=array[i];
try{
int intValue = Integer.parseInt(str);
System.out.println("\"" + str + "\" is a valid integer");
}
catch (NumberFormatException e1){
try{
double doubleValue = Double.parseDouble(str);
System.out.println("\"" + str + "\" is a valid double");
}
catch (NumberFormatException e2){
System.out.println("\"" + str + "\" is a String");
}
}
}
}
}

OUTPUT:
PRACTICAL 9
Aim: Program to create a user defined exception ‘MyException’ and throw this
exception when the age entered is less than 18.
CODE:
import java.util.Scanner;
class MyException extends Exception {
public MyException(String message) {
super(message);
}
}
class AgeValidator {
public void checkAge(int age) throws MyException {
if (age < 18) {
throw new MyException("Age cannot be less than 18.");
} else {
System.out.println("Age is valid.");
}
}
}

class UserDefinedExceptionExample {
public static void main(String[] args) {
AgeValidator v = new AgeValidator();
Scanner sc=new Scanner(System.in);
System.out.print("Enter your age: ");
int age=sc.nextInt();
try{
v.checkAge(age);
}
catch (MyException e){
System.out.println("Exception: " + e.getMessage());
}
}
}
OUTPUT:
PRACTICAL-10
Implement the concept of producer consumer problem using the concept of
multithreading.
CODE
import java.util.Arrays;
import java.util.LinkedList;

class ProducerConsumer {
Integer[] val = {0,1,2};
private LinkedList<Integer> buffer = new LinkedList<>(Arrays.asList(val));
private int capacity;

ProducerConsumer(int capacity) {
this.capacity = capacity;
}

public void produce() throws InterruptedException {


int value = 0;
while (true) {
synchronized (this) {
while (buffer.size() == capacity) {
wait();
}
System.out.println("Producer produced: " + value);
buffer.add(value++);
notify();
Thread.sleep(1000);
}
}
}

public void consume() throws InterruptedException {


while (true) {
synchronized (this) {
while (buffer.isEmpty()) {
wait();
}
int consumedValue = buffer.removeFirst();
System.out.println("Consumer consumed: " + consumedValue);
notify();
Thread.sleep(1000);
}
}
}
}
public class MultiThreading {
public static void main(String[] args) {
ProducerConsumer pc = new ProducerConsumer(5);

Thread producerThread = new Thread(() -> {


try {
pc.produce();
} catch (InterruptedException e) {
e.printStackTrace();
}
});

Thread consumerThread = new Thread(() -> {


try {
pc.consume();
} catch (InterruptedException e) {
e.printStackTrace();
}
});

producerThread.start();
consumerThread.start();
}
}
OUTPUT:

You might also like