Java Programming Lab File - 049

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 19

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 – TARUUN R MALIK
ENROLLMENT NO.-04916401521
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
6 occupies 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",


8 "5.hello", "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.
PRACTICAL – 1

AIM:
Program to print the reverse of the numbers, the numbers are taken as an input
from the user.

CODE:-
import java.util.Scanner;

public class ReverseNumber {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter a number: ");


int number = scanner.nextInt();

int reversedNumber = 0;

while (number != 0) {
int digit = number % 10;
reversedNumber = reversedNumber * 10 + digit;
number /= 10;
}

System.out.println("Reversed number: " + reversedNumber);

scanner.close();
}
}

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:
1. Deposit
2. Withdraw
3. Display Balance
4. Add Interest (Savings Account)
0. Exit
Enter your choice: 1
Enter amount to deposit: 10000
Deposit successful. New balance: 11000.0

1. Deposit
2. Withdraw
3. Display Balance
4. Add Interest (Savings Account)
0. Exit
Enter your choice: 2
Enter amount to withdraw: 5000
Withdrawal successful. New balance: 6000.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


PRACTICAL – 3

AIM:
Program to maintain bank account using packages.
CODE:-
interface Account {
void deposit(double amount);
void withdraw(double amount);
double getBalance();
}

interface Interest {
void addInterest();
}

class SavingsAccount implements Account, Interest {


private String accountNumber;
private double balance;
private double interestRate;

public SavingsAccount(String accountNumber, double balance, double


interestRate) {
this.accountNumber = accountNumber;
this.balance = balance;
this.interestRate = interestRate;
}

public void deposit(double amount) {


balance += amount;
System.out.println("Deposited: " + amount);
}

public void withdraw(double amount) {


if (balance >= amount) {
balance -= amount;
System.out.println("Withdrawn: " + amount);
} else {
System.out.println("Insufficient funds");
}
}

public double getBalance() {


return balance;
}
public void addInterest() {
double interest = balance * (interestRate / 100);
deposit(interest);
System.out.println("Added interest: " + interest);
}
}

class CurrentAccount implements Account {


private String accountNumber;
private double balance;
private double overdraftLimit;

public CurrentAccount(String accountNumber, double balance, double


overdraftLimit) {
this.accountNumber = accountNumber;
this.balance = balance;
this.overdraftLimit = overdraftLimit;
}

public void deposit(double amount) {


balance += amount;
System.out.println("Deposited: " + amount);
}

public void withdraw(double amount) {


if (balance - amount >= -overdraftLimit) {
balance -= amount;
System.out.println("Withdrawn: " + amount);
} else {
System.out.println("Exceeds overdraft limit");
}
}

public double getBalance() {


return balance;
}
}

public class Main {


public static void main(String[] args) {
SavingsAccount savingsAccount = new SavingsAccount("SA123", 1000,
5.0);
CurrentAccount currentAccount = new CurrentAccount("CA456", 2000,
500);

System.out.println("Savings Account Balance: " +


savingsAccount.getBalance());
System.out.println("Current Account Balance: " +
currentAccount.getBalance());

savingsAccount.deposit(500);
savingsAccount.addInterest();
savingsAccount.withdraw(200);

currentAccount.deposit(1000);
currentAccount.withdraw(2500);

System.out.println("Updated Savings Account Balance: " +


savingsAccount.getBalance());
System.out.println("Updated Current Account Balance: " +
currentAccount.getBalance());
}
}

OUTPUT :-
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:
Main Thread Running

Initial Main Thread: main


Initial Priority: 5
Updated Main Thread: Main_Updated
Updated Priority: 10

Thread running for 5 seconds:


1
2
3
4
5
Main Thread Ended.
PRACTICAL – 5

AIM:
Program to illustrate the working of the child threads in concurrence with the
main thread.
CODE:-
class NewThread implements Runnable {
Thread t;
NewThread() {
t = new Thread(this, "Demo Thread");
System.out.println("Child thread: " + t);
t.start();
}
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
class ThreadDemo {
public static void main(String args[ ] ) {
new NewThread(); // create a new thread
try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
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 :-

You might also like