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

Practical OOP

The document contains a series of Java programming exercises that cover basic concepts such as displaying messages, calculating simple interest, checking leap years, adding binary numbers, and implementing classes with constructors and inheritance. Each exercise includes code examples, expected outputs, and explanations of the functionality. The exercises are structured to help learners practice and understand fundamental programming principles in Java.

Uploaded by

apookiedev
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Practical OOP

The document contains a series of Java programming exercises that cover basic concepts such as displaying messages, calculating simple interest, checking leap years, adding binary numbers, and implementing classes with constructors and inheritance. Each exercise includes code examples, expected outputs, and explanations of the functionality. The exercises are structured to help learners practice and understand fundamental programming principles in Java.

Uploaded by

apookiedev
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 72

Practical No:-1

I. Write a Program that displays Welcome to Java, Learning Java Now and Programming is
fun.

Code:
Public class WelcomeMessage
{
Public Static void main(String[] args)
{
System.out.println(“Welcome to Java”);
System.out.println(“Learn Java Now”);
System.out.println(“Programming is fun”);
}
}

Output:

Page | 1
II. Write a Java Program to calculate simple interest.

Code:
import java.unit.Scanner;

public class SimpleInterestCalculator


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

System.out.print(“Enter Principal amount: ”);


double principal = scanner.nextDouble();

System.out.print(“Enter Annual interest Rate (in %): ”);


double rate = scanner.nextDouble();

System.out.print(“Enter time (in years): ”);


double time = scanner.nextDouble();

double simpleinterest = (principa * rate * time)/100;

System.out.println(“Simple Interest: ” + simpleinterest)

Scanner.close();
}
}

Output:

Page | 2
III. Write a Java Program to check Leap Year.

Code:
import java.unit.Scanner;

public class LeapYearChecker


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

System.out.print(“Enter a Year: ”);


Int year = scanner.nextInt();

Boolean isLeap = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);

if(isLeap)
{
System.out.println(year + “is a Leap Year.”);
}
else
{
System.out.println(year + “is NOT a Leap Year.”);
}
Scanner.close();
}
}

Output:

Page | 3
IV. Write a Java Program to add two binary numbers.

Code:
import java.unit.Scanner;

public class BinaryAddition


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

System.out.print(“Enter first binary number: ”);


String binary1 = scanner.next();

System.out.print(“Enter second binary number: ”);


String binary2 = scanner.next();

int num1 = Integer.parseInt(binary1, 2);


int num2 = Integer.parseInt(binary2, 2);

int sum = num1 + num2;

String binarySum = Integer.toBinaryString(sum);

System.out.println(“Sum of binary number: ” + binarySum);

Scanner.close();

}
}

Output:

Page | 4
Practical No:-2
I. Write a Java Program to check if a number is Armstrong from given array.
Code:
import java.util.ArrayList;

public class ArmstrongNumbers


{
public static boolean isArmstrong(int num)
{
int originalNum = num;
int numOfDigits = String.valueOf(num).length();
int sum = 0;

while (num > 0)


{
int digit = num % 10;
sum += Math.pow(digit, numOfDigits);
num /= 10;
}

return sum == originalNum;


}

public static void main(String[] args)


{
int[] numbers = {153, 370, 371, 407, 123, 9};
ArrayList<Integer> armstrongNumbers = new ArrayList<>();

for (int num : numbers)


{
if (isArmstrong(num))
{
armstrongNumbers.add(num);
}
}

System.out.println("Armstrong numbers in the array:");


for (int armstrongNum : armstrongNumbers)
{
System.out.println(armstrongNum);
}
}
}
Output:

Page | 5
Page | 6
II. Write a Java Program to perform bubble sort on Strings.
Code:
import java.util.Arrays;

public class BubbleSortStrings {

public static void bubbleSort(String[] arr) {


int n = arr.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j].compareTo(arr[j + 1]) > 0) {
String temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}

public static void main(String[] args) {


String[] strings = {"Banana", "Apple", "Orange", "Mango", "Pineapple"};
System.out.println("Original Array: " + Arrays.toString(strings));
bubbleSort(strings);
System.out.println("Sorted Array: " + Arrays.toString(strings));
}
}

Output:

Page | 7
III. Write a Java program to perform different methods of string buffer class.

Code:

public class StringBufferExample {


public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello");

sb.append(" World");
System.out.println("After append: " + sb);

sb.insert(5, " Java");


System.out.println("After insert: " + sb);

sb.replace(6, 10, "Code");


System.out.println("After replace: " + sb);

sb.delete(5, 10);
System.out.println("After delete: " + sb);

sb.reverse();
System.out.println("After reverse: " + sb);

System.out.println("Length: " + sb.length());


System.out.println("Capacity: " + sb.capacity());
}
}

Output:

Page | 8
Practical No:-3
I. Create a class named Product with instance variables MRP and QUANTITY
and methods display (), setdata (). In display () method,
display the instance variables value (MRP and QUANTITY). And in setdata ()
method set the instance variable values (MRP and QUANTITY)).

Code:

public class Product {


double MRP;
int QUANTITY;

public void display() {


System.out.println("MRP: " + MRP);
System.out.println("Quantity: " + QUANTITY);
}

public void setdata(double MRP, int QUANTITY) {


this.MRP = MRP;
this.QUANTITY = QUANTITY;
}

public static void main(String[] args) {


Product product = new Product();
product.setdata(499.99, 10);
product.display();
}
}

Output:

Page | 9
II. Create a class named Account with instance variables Ac_No,Name and
Balance and methods display (), setdata (),deposit(). In display () method,
display the instance variables value (Ac_No,Name and Balance). And in
setdata () method set the instance variable values (Ac_No,Name and Balance)
and in deposit() method the amount that user wants to deposit that will be
deposited.

Code:

import java.util.Scanner;

public class Account {


int Ac_No;
String Name;
double Balance;

public void display() {


System.out.println("Account Number: " + Ac_No);
System.out.println("Name: " + Name);
System.out.println("Balance: " + Balance);
}

public void setdata(int Ac_No, String Name, double Balance) {


this.Ac_No = Ac_No;
this.Name = Name;
this.Balance = Balance;
}

public void deposit(double amount) {


Balance += amount;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
Account account = new Account();

System.out.print("Enter Account Number: ");


int acNo = scanner.nextInt();
scanner.nextLine(); // Consume newline
System.out.print("Enter Name: ");
String name = scanner.nextLine();
System.out.print("Enter Balance: ");
double balance = scanner.nextDouble();

account.setdata(acNo, name, balance);

Page | 10
account.display();

System.out.print("Enter deposit amount: ");


double depositAmount = scanner.nextDouble();
account.deposit(depositAmount);

System.out.println("Updated Account Info:");


account.display();
}
}

Output:

Page | 11
III. Create a class named Student with static variable Enrollment no. and instance
variable Name and methods display (), setdata (). in display () method, display
the variables value (Enrollment no. and Name). And in setdata () method set the
variable values (Enrollment no. and Name).

Code:

public class Student {


static int EnrollmentNo;
String Name;

public void display() {


System.out.println("Enrollment No: " + EnrollmentNo);
System.out.println("Name: " + Name);
}

public void setdata(int EnrollmentNo, String Name) {


this.EnrollmentNo = EnrollmentNo;
this.Name = Name;
}

public static void main(String[] args) {


Student student = new Student();
student.setdata(101, "John Doe");
student.display();
}
}

Output:

Page | 12
Practical No:- 4
I. Create a default constructor of class Product to print- “Welcome to Super-
Market.” And parameterized constructor to get the values of variables. (using
Command Line Arguments)

Code:

public class Product {


double MRP;
int QUANTITY;

public Product() {
System.out.println("Welcome to Super-Market.");
}

public Product(double MRP, int QUANTITY) {


this.MRP = MRP;
this.QUANTITY = QUANTITY;
}

public static void main(String[] args) {


Product product1 = new Product();
Product product2 = new Product(Double.parseDouble(args[0]),
Integer.parseInt(args[1]));

System.out.println("MRP: " + product2.MRP);


System.out.println("Quantity: " + product2.QUANTITY);
}
}

Output:

Page | 13
II. Create a default constructor of class Account to print- “Welcome to Bank.”
And parameterized constructor to get the values of variables. (Using Command
Line Argument).

Code:

public class Account {


int Ac_No;
String Name;
double Balance;

public Account() {
System.out.println("Welcome to Bank.");
}

public Account(int Ac_No, String Name, double Balance) {


this.Ac_No = Ac_No;
this.Name = Name;
this.Balance = Balance;
}

public static void main(String[] args) {


Account account1 = new Account();
Account account2 = new Account(Integer.parseInt(args[0]), args[1],
Double.parseDouble(args[2]));

System.out.println("Account Number: " + account2.Ac_No);


System.out.println("Name: " + account2.Name);
System.out.println("Balance: " + account2.Balance);
}
}

Output:

Page | 14
III. Create a default constructor of class Student to print- “Welcome to Student-
Information system.” And parameterized constructor to get the values of
variables (Enrollment no. and Name). (using Command Line Arguments)

Code:

public class Student {


static int EnrollmentNo;
String Name;

public Student() {
System.out.println("Welcome to Student-Information system.");
}

public Student(int EnrollmentNo, String Name) {


this.EnrollmentNo = EnrollmentNo;
this.Name = Name;
}

public static void main(String[] args) {


Student student1 = new Student();
Student student2 = new Student(Integer.parseInt(args[0]), args[1]);

System.out.println("Enrollment No: " + student2.EnrollmentNo);


System.out.println("Name: " + student2.Name);
}
}

Output:

Page | 15
Page | 16
Practical No:-5
I. Create three inherited classes named-Crockery, Household, Food-items from
Product super class and inherit the instance method(display () and setdata ())
and variables(MRP and QUANTITY) of super class Product.

Code:
class Product {
protected double MRP;
protected int QUANTITY;

public Product(double mrp, int quantity) {


this.MRP = mrp;
this.QUANTITY = quantity;
}

public void setData(double mrp, int quantity) {


this.MRP = mrp;
this.QUANTITY = quantity;
}

public void display() {


System.out.println("MRP: " + MRP + ", Quantity: " + QUANTITY);
}
}

class Crockery extends Product {


private String material;

public Crockery(double mrp, int quantity, String material) {


super(mrp, quantity);
this.material = material;
}

@Override
public void display() {
super.display();
System.out.println("Material: " + material);
}
}

class Household extends Product {


private String usage;

public Household(double mrp, int quantity, String usage) {


super(mrp, quantity);

Page | 17
this.usage = usage;
}

@Override
public void display() {
super.display();
System.out.println("Usage: " + usage);
}
}

class FoodItems extends Product {


private String expiryDate;

public FoodItems(double mrp, int quantity, String expiryDate) {


super(mrp, quantity);
this.expiryDate = expiryDate;
}

@Override
public void display() {
super.display();
System.out.println("Expiry Date: " + expiryDate);
}
}

public class Main {


public static void main(String[] args) {
Crockery crockeryItem = new Crockery(500, 10, "Ceramic");
crockeryItem.display();

Household householdItem = new Household(150, 5, "Cleaning");


householdItem.display();

FoodItems foodItem = new FoodItems(200, 20, "2025-12-31");


foodItem.display();
}
}

Output:

Page | 18
II. Create two inherited classes named-Savings,Current from Account super
class and inherit the instance method(display (),setdata () and deposit()) and
variables(Ac_No,Name and Balance) of super class Account.

Code:
class Account {
protected int Ac_No;
protected String Name;
protected double Balance;

public Account(int ac_No, String name, double balance) {


this.Ac_No = ac_No;
this.Name = name;
this.Balance = balance;
}

public void setData(int ac_No, String name, double balance) {


this.Ac_No = ac_No;
this.Name = name;
this.Balance = balance;
}

public void deposit(double amount) {


if (amount > 0) {
this.Balance += amount;
}
}

public void display() {


System.out.println("Account Number: " + Ac_No + ", Name: " + Name + ", Balance: " +
Balance);
}
}

class Savings extends Account {


public Savings(int ac_No, String name, double balance) {
super(ac_No, name, balance);
}
}

class Current extends Account {


public Current(int ac_No, String name, double balance) {
super(ac_No, name, balance);
}
}
Page | 19
public class Main {
public static void main(String[] args) {
Savings savingsAccount = new Savings(1001, "Alice", 5000.00);
savingsAccount.display();
savingsAccount.deposit(1500.00);
savingsAccount.display();

Current currentAccount = new Current(2001, "Bob", 10000.00);


currentAccount.display();
currentAccount.deposit(2000.00);
currentAccount.display();
}
}

Output:

Page | 20
III. Create two inherited classes named-BE,ME from Student super class and
inherit the instance method(display () and setdata ()) and variables(Enrollment
no and Name) of super class Student and make an instance variable Entry_year
and final variable duration for each of the above class
Code:
class Student {
protected int EnrollmentNo;
protected String Name;

public Student(int enrollmentNo, String name) {


this.EnrollmentNo = enrollmentNo;
this.Name = name;
}

public void setData(int enrollmentNo, String name) {


this.EnrollmentNo = enrollmentNo;
this.Name = name;
}

public void display() {


System.out.println("Enrollment No: " + EnrollmentNo + ", Name: " + Name);
}
}

class BE extends Student {


private int EntryYear;
private final int Duration = 4;

public BE(int enrollmentNo, String name, int entryYear) {


super(enrollmentNo, name);
this.EntryYear = entryYear;
}

@Override
public void display() {
super.display();
System.out.println("Entry Year: " + EntryYear + ", Duration: " + Duration + " years");
}
}

class ME extends Student {


private int EntryYear;
private final int Duration = 2;

public ME(int enrollmentNo, String name, int entryYear) {


Page | 21
super(enrollmentNo, name);
this.EntryYear = entryYear;
}

@Override
public void display() {
super.display();
System.out.println("Entry Year: " + EntryYear + ", Duration: " + Duration + " years");
}
}

public class Main {


public static void main(String[] args) {
BE beStudent = new BE(101, "John Doe", 2022);
beStudent.display();

ME meStudent = new ME(201, "Jane Doe", 2023);


meStudent.display();
}
}

Output:

Page | 22
Practical No:-6
I. Create a interface named place with method search() and variable BlockNo and
implement it together on all the above classes. Use binary I/O

Code:
import java.io.*;

interface Place {
int BlockNo = 0;
void search();
}

class Student implements Place, Serializable {


private static final long serialVersionUID = 1L;
protected int EnrollmentNo;
protected String Name;

public Student(int enrollmentNo, String name) {


this.EnrollmentNo = enrollmentNo;
this.Name = name;
}

public void setData(int enrollmentNo, String name) {


this.EnrollmentNo = enrollmentNo;
this.Name = name;
}

public void display() {


System.out.println("Enrollment No: " + EnrollmentNo + ", Name: " + Name);
}

@Override
public void search() {
System.out.println("Searching student in Block: " + BlockNo);
}
}

class BE extends Student {


private static final long serialVersionUID = 1L;
private int EntryYear;
private final int Duration = 4;

public BE(int enrollmentNo, String name, int entryYear) {


super(enrollmentNo, name);
Page | 23
this.EntryYear = entryYear;
}

@Override
public void display() {
super.display();
System.out.println("Entry Year: " + EntryYear + ", Duration: " + Duration + " years");
}
}

class ME extends Student {


private static final long serialVersionUID = 1L;
private int EntryYear;
private final int Duration = 2;

public ME(int enrollmentNo, String name, int entryYear) {


super(enrollmentNo, name);
this.EntryYear = entryYear;
}

@Override
public void display() {
super.display();
System.out.println("Entry Year: " + EntryYear + ", Duration: " + Duration + " years");
}
}

public class Main2 {


public static void main(String[] args) {
BE beStudent = new BE(101, "John Doe", 2022);
ME meStudent = new ME(201, "Jane Doe", 2023);

try (ObjectOutputStream oos = new ObjectOutputStream(new


FileOutputStream("students.dat"));
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("students.dat"))) {

oos.writeObject(beStudent);
oos.writeObject(meStudent);

BE readBeStudent = (BE) ois.readObject();


ME readMeStudent = (ME) ois.readObject();
readBeStudent.display();
readMeStudent.display();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}

Page | 24
}

Output:

Page | 25
II. Create an interface named Branch with method search() and variable IFSC
Code and implement it together on all the above classes.

Code:
import java.io.*;

interface Place {
int BlockNo = 0;
void search();
}

interface Branch {
String IFSC_Code = "DEFAULT_IFSC";
void search();
}

class Student implements Place, Branch, Serializable {


private static final long serialVersionUID = 1L;
protected int EnrollmentNo;
protected String Name;

public Student(int enrollmentNo, String name) {


this.EnrollmentNo = enrollmentNo;
this.Name = name;
}

public void setData(int enrollmentNo, String name) {


this.EnrollmentNo = enrollmentNo;
this.Name = name;
}

public void display() {


System.out.println("Enrollment No: " + EnrollmentNo + ", Name: " + Name);
}

@Override
public void search() {
System.out.println("Searching student in Block: " + BlockNo + ", IFSC Code: " +
IFSC_Code);
}
}

class BE extends Student {


private static final long serialVersionUID = 1L;
private int EntryYear;
Page | 26
private final int Duration = 4;

public BE(int enrollmentNo, String name, int entryYear) {


super(enrollmentNo, name);
this.EntryYear = entryYear;
}

@Override
public void display() {
super.display();
System.out.println("Entry Year: " + EntryYear + ", Duration: " + Duration + " years");
}
}

class ME extends Student {


private static final long serialVersionUID = 1L;
private int EntryYear;
private final int Duration = 2;

public ME(int enrollmentNo, String name, int entryYear) {


super(enrollmentNo, name);
this.EntryYear = entryYear;
}

@Override
public void display() {
super.display();
System.out.println("Entry Year: " + EntryYear + ", Duration: " + Duration + " years");
}
}

public class Main2 {


public static void main(String[] args) {
BE beStudent = new BE(101, "John Doe", 2022);
ME meStudent = new ME(201, "Jane Doe", 2023);

try (ObjectOutputStream oos = new ObjectOutputStream(new


FileOutputStream("students.dat"));
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("students.dat"))) {

oos.writeObject(beStudent);
oos.writeObject(meStudent);

BE readBeStudent = (BE) ois.readObject();


ME readMeStudent = (ME) ois.readObject();

readBeStudent.display();

Page | 27
readMeStudent.display();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}

Output:

Page | 28
III. Create a interface named Result with method getMarks() and variable
percentage and implement it together on all the above classes. in getMarks()
get the marks of 3 subjects and calculate the average inside the method.

Code:
import java.util.Scanner;

interface Result {
double percentage = 0.0;
void getMarks();
}

class StudentA implements Result {


private double percentage;

@Override
public void getMarks() {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter marks for Student A (3 subjects): ");
double sub1 = scanner.nextDouble();
double sub2 = scanner.nextDouble();
double sub3 = scanner.nextDouble();

percentage = (sub1 + sub2 + sub3) / 3;


System.out.println("Student A Percentage: " + percentage + "%");
}
}

class StudentB implements Result {


private double percentage;

@Override
public void getMarks() {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter marks for Student B (3 subjects): ");
double sub1 = scanner.nextDouble();
double sub2 = scanner.nextDouble();
double sub3 = scanner.nextDouble();

percentage = (sub1 + sub2 + sub3) / 3;


System.out.println("Student B Percentage: " + percentage + "%");
}
}

public class ResultDemo {


Page | 29
public static void main(String[] args) {
Result student1 = new StudentA();
student1.getMarks();

Result student2 = new StudentB();


student2.getMarks();
}
}

Output:

Page | 30
Practical No:-7
I. Define three objects for all the classes named- Crockery, Household, Food-items and
store the initial values for all the objects in arraylist or collection.

Code:
import java.util.*;

class Crockery {
String name;
String material;
double price;

public Crockery(String name, String material, double price) {


this.name = name;
this.material = material;
this.price = price;
}

public String toString() {


return "Crockery{" + "name='" + name + '\'' + ", material='" + material + '\'' + ", price=" + price
+ '}';
}
}

class Household {
String itemName;
String category;
int quantity;

public Household(String itemName, String category, int quantity) {


this.itemName = itemName;
this.category = category;
this.quantity = quantity;
}

public String toString() {


return "Household{" + "itemName='" + itemName + '\'' + ", category='" + category + '\'' + ",
quantity=" + quantity + '}';
}
}

class FoodItems {
String itemName;
String expiryDate;
Page | 31
double weight;

public FoodItems(String itemName, String expiryDate, double weight) {


this.itemName = itemName;
this.expiryDate = expiryDate;
this.weight = weight;
}

public String toString() {


return "FoodItems{" + "itemName='" + itemName + '\'' + ", expiryDate='" + expiryDate + '\'' + ",
weight=" + weight + '}';
}
}

public class Store {


public static void main(String[] args) {
List<Crockery> crockeryList = new ArrayList<>();
crockeryList.add(new Crockery("Plate", "Ceramic", 15.99));
crockeryList.add(new Crockery("Cup", "Glass", 5.49));
crockeryList.add(new Crockery("Bowl", "Plastic", 3.99));

List<Household> householdList = new ArrayList<>();


householdList.add(new Household("Vacuum Cleaner", "Electronics", 1));
householdList.add(new Household("Broom", "Cleaning", 2));
householdList.add(new Household("Mop", "Cleaning", 1));

List<FoodItems> foodList = new ArrayList<>();


foodList.add(new FoodItems("Apple", "2025-05-10", 1.5));
foodList.add(new FoodItems("Milk", "2025-04-15", 2.0));
foodList.add(new FoodItems("Bread", "2025-04-05", 0.5));

System.out.println("Crockery Items: " + crockeryList);


System.out.println("Household Items: " + householdList);
System.out.println("Food Items: " + foodList);
}
}

Output:

Page | 32
II. Define three objects for all the classes named- Savings,Current and store the
initial values for all the objects in arraylist or collection.
Example: Class Savings extends Account implements Branch; Define objects.

Code:
import java.util.ArrayList;

class Savings {
String accountHolder;
double balance;

public Savings(String accountHolder, double balance) {


this.accountHolder = accountHolder;
this.balance = balance;
}

public void display() {


System.out.println("Savings Account - Holder: " + accountHolder + ", Balance: $" + balance);
}
}

class Current {
String accountHolder;
double balance;

public Current(String accountHolder, double balance) {


this.accountHolder = accountHolder;
this.balance = balance;
}

public void display() {


System.out.println("Current Account - Holder: " + accountHolder + ", Balance: $" + balance);
}
}

public class BankAccounts {


public static void main(String[] args) {
ArrayList<Object> accounts = new ArrayList<>();

accounts.add(new Savings("Alice", 5000));


accounts.add(new Savings("Bob", 7000));
accounts.add(new Savings("Charlie", 9000));

accounts.add(new Current("David", 15000));

Page | 33
accounts.add(new Current("Emma", 20000));
accounts.add(new Current("Frank", 25000));

for (Object account : accounts) {


if (account instanceof Savings) {
((Savings) account).display();
} else if (account instanceof Current) {
((Current) account).display();
}
}
}
}

Output:

Page | 34
III. Define two objects for all the classes named- BE,ME and store the initial values
for all the objects in arraylist or collection.
Example: Class BE extends Student, implements Result; Define objects of BE.
Code:
import java.util.*;

class BE {
String name;
int duration;

BE(String name, int duration) {


this.name = name;
this.duration = duration;
}

public String toString() {


return "BE{name='" + name + "', duration=" + duration + "}";
}
}

class ME {
String specialization;
int duration;

ME(String specialization, int duration) {


this.specialization = specialization;
this.duration = duration;
}

public String toString() {


return "ME{specialization='" + specialization + "', duration=" + duration + "}";
}
}

public class Main {


public static void main(String[] args) {
List<Object> courses = new ArrayList<>();

courses.add(new BE("Computer Science", 4));


courses.add(new BE("Mechanical Engineering", 4));
courses.add(new ME("Data Science", 2));
courses.add(new ME("Robotics", 2));

for (Object course : courses) {


System.out.println(course);

Page | 35
}
}
}
Output:

Page | 36
Practical No:-8
I. Create a Package and put all the classes mentioned above in package.

Code:
Savings.java
package Bank;
public class Savings{
public void display(){
System.out.println("Savings Account\nBank: AXIS\nBranch: Ahmedabad");
}
}
Current.java
package Bank;
public class Current{
public void display(){
System.out.println("Current Account\nBank: HDFC\nBranch: Surat");
}
}
Practical.java
import java.util.Scanner;
class Crockery1
{
public void display()
{
System.out.println("Crocker includes Plates, jug, bowls, etc.");
}
class Food_items1
{
public void display()
{
System.out.println("Food-items includes Sunflower-oil, Rice,Wheat etc.");
}
}
class Household1
{
public void display()
{
System.out.println("Household product includes spoons, knives,forks, etc.");
}
}

Page | 37
public class Practical
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter 1 for Crockery");
System.out.println("Enter 2 for Household");
System.out.println("Enter 3 for Food_items");
System.out.print("Enter your choice: ");
int ch = sc.nextInt();
System.out.print("\n");
switch(ch)
{
case 1:
Crockery1 cr=new Crockery1();
cr.display();
break;
case 2:
Household1 hr=new Household1();
hr.display();
break;
case 3:
Food_items1 fr= new Food_items1();
fr.display();
break;
default:
System.out.println("Invalid Choice");
}
}
}

Output:

Page | 38
II. Create a package and put all the classes mentioned above in the package.
Code:
package Bank;
public class Current{
public void display(){
System.out.println("Current Account\nBank: HDFC\nBranch: Surat");
}
}
package Bank;
public class Savings{
public void display(){
System.out.println("Savings Account\nBank: AXIS\nBranch: Ahmedabad");
}
}
Practical8b.java
//File: Practical18b.java
import Bank.*;
import java.util.Scanner;
class Practical8b
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter 1 for Savings");
System.out.println("Enter 2 for Current");
System.out.print("Enter your choice: ");

int ch = sc.nextInt();
System.out.print("\n");
switch(ch)
{

case 1:

Bank.Savings cr=new Bank.Savings();


cr.display();
break;
case 2:
Page | 39
Bank.Current hr=new Bank.Current();
hr.display();
break; default:
System.out.println("Invalid Choice");

Output:

Page | 40
III. Create a Package and put all the classes mentioned above in
package.
Code:
package Student;
public class ME{
public void display(){
System.out.println("ME Student Info\nDegree: IT\nYears: 2 years");
}
}
package Student;
public class BE{
public void display(){
System.out.println("BE Student Info\nDegree: IT\nYears: 4 years");
}
}
Practical8c.java
import Student.BE;
import Student.ME;
import java.util.Scanner;
class Practical8c{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter 1 for BE");
System.out.println("Enter 2 for ME");
System.out.print("Enter your choice: ");
int ch = sc.nextInt();
System.out.print("\n");
switch(ch){
case 1:
BE cr=new BE();
cr.display();
break;

Page | 41
case 2:
ME hr=new ME();
hr.display();
break;
default:
System.out.println("Invalid Choice");
}
}
}

Output:

Page | 42
Practical No:-9
I. Create a method named buy () in the main function performing
exception handling.
Example: Banana = 10; Banana_Buy = 12 Here, Banana_Buy > Banana (throw
exception).
Code:
import java.util.Scanner;

public class Main {


public static void buy() {
Scanner scanner = new Scanner(System.in);
try {
System.out.print("Enter the item you want to buy: ");
String item = scanner.nextLine();

System.out.print("Enter the quantity: ");


int quantity = Integer.parseInt(scanner.nextLine());

System.out.print("Enter the price per unit: ");


double price = Double.parseDouble(scanner.nextLine());

if (quantity < 0 || price < 0) {


throw new IllegalArgumentException("Quantity and price must be non-
negative.");
}

double totalCost = quantity * price;


System.out.printf("You bought %d %s(s) for a total of $%.2f\n", quantity, item,
totalCost);
} catch (NumberFormatException e) {
System.out.println("Invalid input: Please enter valid numbers for quantity and
price.");
} catch (IllegalArgumentException e) {
System.out.println("Error: " + e.getMessage());
} catch (Exception e) {
System.out.println("An unexpected error occurred: " + e.getMessage());
} finally {
scanner.close();
}
}

public static void main(String[] args) {


buy();
}}

Page | 43
Output:

Page | 44
II. Create a method named Withdraw () in the main function
performing exception handling.
Example: Balance = 1000; Withdraw = 12000 Here, Balance<Withdraw (throw
exception)
Code:
import java.util.Scanner;

public class BankAccount {


public static void main(String[] args) {
double balance = 500.00; // Initial balance
balance = withdraw(balance);
}

public static double withdraw(double balance) {


Scanner scanner = new Scanner(System.in);

try {
System.out.print("Enter the amount to withdraw: ");
double amount = scanner.nextDouble();

if (amount <= 0) {
throw new IllegalArgumentException("Withdrawal amount must be greater
than zero.");
}
if (amount > balance) {
throw new IllegalArgumentException("Insufficient balance.");
}

balance -= amount;
System.out.printf("Withdrawal successful! New balance: $%.2f%n", balance);

} catch (IllegalArgumentException e) {
System.out.println("Error: " + e.getMessage());
} catch (Exception e) {
System.out.println("An unexpected error occurred: " + e.getMessage());
} finally {
scanner.close(); // Close the scanner to prevent memory leaks
}

return balance;
}
}

Page | 45
Output:

Page | 46
III. Create a method named searchStudent() in the main () Function
performing exception handling.
Example: if we search the student name and if it is present in the list then it will
represent the details else it will throw an exception.
Code:
import java.util.HashMap;
import java.util.Scanner;

class StudentNotFoundException extends Exception {


public StudentNotFoundException(String message) {
super(message);
}
}

public class StudentSearch {


public static void main(String[] args) {
HashMap<String, String> students = new HashMap<>();
students.put("Alice", "Alice - ID: 101, Age: 20, Grade: A");
students.put("Bob", "Bob - ID: 102, Age: 22, Grade: B");
students.put("Charlie", "Charlie - ID: 103, Age: 21, Grade: A-");

Scanner scanner = new Scanner(System.in);


System.out.print("Enter student name to search: ");
String studentName = scanner.nextLine();

try {
searchStudent(studentName, students);
} catch (StudentNotFoundException e) {
System.out.println("Error: " + e.getMessage());
} finally {
scanner.close();
}
}

public static void searchStudent(String name, HashMap<String, String> students)


throws StudentNotFoundException {
if (students.containsKey(name)) {
System.out.println("Student Found: " + students.get(name));
} else {
throw new StudentNotFoundException("Student with name '" + name + "' not
found.");
}
}
}

Page | 47
Output:

Page | 48
Practical No:-10
I. Save object data in the file using File Writer class, using
parameterized constructor.

Code:
import java.io.FileWriter;
import java.io.IOException;

class Person {
String name;
int age;

Person(String name, int age) {


this.name = name;
this.age = age;
}

public String toString() {


return name + ", " + age;
}
}

public class FileWriterExample {


public static void main(String[] args) {
Person person = new Person("John Doe", 30);

try (FileWriter writer = new FileWriter("person.txt")) {


writer.write(person.toString());
}
catch (IOException e) {
e.printStackTrace();
}
}
}
Output:

Page | 49
II. Save object data in the file using File Writer class, using
parameterized constructor.

Code:
import java.io.FileWriter;
import java.io.IOException;

class Person {
String name;
int age;

Person(String name, int age) {


this.name = name;
this.age = age;
}

public String toString() {


return name + ", " + age;
}
}

public class FileWriterExample {


public static void main(String[] args) {
Person person = new Person("John Doe", 30);

try (FileWriter writer = new FileWriter("person.txt")) {


writer.write(person.toString());
}
catch (IOException e) {
e.printStackTrace();
}
}
}
Output:

Page | 50
III. Save object data in the file using File Writer class, using
parameterized constructor.

Code:
import java.io.FileWriter;
import java.io.IOException;

class Person {
String name;
int age;

Person(String name, int age) {


this.name = name;
this.age = age;
}

public String toString() {


return name + ", " + age;
}
}

public class FileWriterExample {


public static void main(String[] args) {
Person person = new Person("John Doe", 30);

try (FileWriter writer = new FileWriter("person.txt")) {


writer.write(person.toString());
}
catch (IOException e) {
e.printStackTrace();
}
}
}
Output:

Page | 51
Page | 52
Practical No:-11
I. Create customer class which extends thread class and contains two
instance variables name, ProductName and static variable Product
Quantity. For example if two customers are trying to buy the same
product at once then follow synchronization of two customers
extending thread class.

Code:
class Customer extends Thread {
String name;
String productName;
static int productQuantity = 10;

Customer(String name, String productName) {


this.name = name;
this.productName = productName;
}

public void run() {


if (productQuantity > 0) {
System.out.println(name + " purchased " + productName);
productQuantity--;
} else {
System.out.println(name + " tried to purchase " + productName + " but it's out
of stock.");
}
}

public static void main(String[] args) {


Customer c1 = new Customer("Alice", "Laptop");
Customer c2 = new Customer("Bob", "Laptop");

c1.start();
c2.start();
}
}
Output:

Page | 53
II. Create Customer class which extends thread class and contains two
instance variables name, BankName and static variable Product
Balance. if two customers are trying to Withdraw from the same
Account at once then then follow synchronization of two customers
extending thread class.

Code:
class Customer extends Thread {
String name;
String bankName;
static int accountBalance = 100;
static Object lock = new Object();

Customer(String name, String bankName) {


this.name = name;
this.bankName = bankName;
}

public void run() {


withdraw(50);
}

void withdraw(int amount) {


synchronized (lock) {
if (accountBalance >= amount) {
System.out.println(name + " is withdrawing " + amount + " from " +
bankName);
accountBalance -= amount;
System.out.println("Remaining balance: " + accountBalance);
} else {
System.out.println(name + " tried to withdraw " + amount + " but insufficient
funds.");
}
}
}

public static void main(String[] args) {


Customer c1 = new Customer("Alice", "XYZ Bank");
Customer c2 = new Customer("Bob", "XYZ Bank");

c1.start();
c2.start();
}
}

Page | 54
Output:

Page | 55
III. Create Number class which extends thread class and create two
objects a1, a2 displaying the number having even Enrollment no.
and odd Enrollment no.
Code:
class Number extends Thread {
int enrollmentNo;

Number(int enrollmentNo) {
this.enrollmentNo = enrollmentNo;
}

public void run() {


if (enrollmentNo % 2 == 0) {
System.out.println("Enrollment No " + enrollmentNo + " is Even.");
} else {
System.out.println("Enrollment No " + enrollmentNo + " is Odd.");
}
}

public static void main(String[] args) {


Number a1 = new Number(1024);
Number a2 = new Number(1023);

a1.start();
a2.start();
}
}
Output:

Page | 56
Practical No:-12
I. Create the above system using a menu and implement it using switch
statement. For example, in the above system implement the menu
driven like..
1. For setting a value of MRP and QUANTITY for the product.
2. For buying a product.
3. For searching a product.
4. To delete a product from storage.
5. To show stored object data

Code:
import java.util.ArrayList;
import java.util.Scanner;

class Product {
String name;
double mrp;
int quantity;

Product(String name, double mrp, int quantity) {


this.name = name;
this.mrp = mrp;
this.quantity = quantity;
}

public String toString() {


return "Product: " + name + ", MRP: " + mrp + ", Quantity: " + quantity;
}
}

public class ProductSystem {


static ArrayList<Product> products = new ArrayList<>();
static Scanner scanner = new Scanner(System.in);

public static void main(String[] args) {


while (true) {
System.out.println("\nMENU:");
System.out.println("1. Set Product MRP and Quantity");
System.out.println("2. Buy a Product");
System.out.println("3. Search a Product");
System.out.println("4. Delete a Product");
System.out.println("5. Show Stored Products");

Page | 57
System.out.println("6. Exit");
System.out.print("Enter your choice: ");

int choice = scanner.nextInt();


scanner.nextLine();

switch (choice) {
case 1:
setProduct();
break;
case 2:
buyProduct();
break;
case 3:
searchProduct();
break;
case 4:
deleteProduct();
break;
case 5:
showProducts();
break;
case 6:
System.out.println("Exiting...");
return;
default:
System.out.println("Invalid choice! Try again.");
}
}
}

static void setProduct() {


System.out.print("Enter Product Name: ");
String name = scanner.nextLine();
System.out.print("Enter MRP: ");
double mrp = scanner.nextDouble();
System.out.print("Enter Quantity: ");
int quantity = scanner.nextInt();
scanner.nextLine();
products.add(new Product(name, mrp, quantity));
System.out.println("Product added successfully!");
}

static void buyProduct() {


System.out.print("Enter Product Name to Buy: ");
String name = scanner.nextLine();

Page | 58
for (Product p : products) {
if (p.name.equalsIgnoreCase(name) && p.quantity > 0) {
p.quantity--;
System.out.println("Product purchased successfully!");
return;
}
}
System.out.println("Product not found or out of stock!");
}

static void searchProduct() {


System.out.print("Enter Product Name to Search: ");
String name = scanner.nextLine();
for (Product p : products) {
if (p.name.equalsIgnoreCase(name)) {
System.out.println(p);
return;
}
}
System.out.println("Product not found!");
}

static void deleteProduct() {


System.out.print("Enter Product Name to Delete: ");
String name = scanner.nextLine();
for (Product p : products) {
if (p.name.equalsIgnoreCase(name)) {
products.remove(p);
System.out.println("Product deleted successfully!");
return;
}
}
System.out.println("Product not found!");
}

static void showProducts() {


if (products.isEmpty()) {
System.out.println("No products available!");
} else {
for (Product p : products) {
System.out.println(p);
}
}
}
}

Page | 59
Output:

Page | 60
II. Create the above system using a menu and implement it using switch
statement. For example, in the above system implement the menu
driven like.
1. For Setting a value of Ac_No,Name and Balance for the Bank
2. For Withdraw from a Account.
3. For Searching a Account.
4. To delete an Account from Bank.
5. To show stored object data

Code:
import java.util.ArrayList;
import java.util.Scanner;

class BankAccount {
int accountNumber;
String name;
double balance;

BankAccount(int accountNumber, String name, double balance) {


this.accountNumber = accountNumber;
this.name = name;
this.balance = balance;
}

public String toString() {


return "Account No: " + accountNumber + ", Name: " + name + ", Balance: " +
balance;
}
}

public class BankSystem {


static ArrayList<BankAccount> accounts = new ArrayList<>();
static Scanner scanner = new Scanner(System.in);

public static void main(String[] args) {


while (true) {
System.out.println("\nMENU:");
System.out.println("1. Set Account Details");
System.out.println("2. Withdraw from Account");
System.out.println("3. Search an Account");
System.out.println("4. Delete an Account");
System.out.println("5. Show All Accounts");
System.out.println("6. Exit");

Page | 61
System.out.print("Enter your choice: ");

int choice = scanner.nextInt();


scanner.nextLine();

switch (choice) {
case 1:
setAccount();
break;
case 2:
withdraw();
break;
case 3:
searchAccount();
break;
case 4:
deleteAccount();
break;
case 5:
showAccounts();
break;
case 6:
System.out.println("Exiting...");
return;
default:
System.out.println("Invalid choice! Try again.");
}
}
}

static void setAccount() {


System.out.print("Enter Account Number: ");
int accNo = scanner.nextInt();
scanner.nextLine();
System.out.print("Enter Name: ");
String name = scanner.nextLine();
System.out.print("Enter Balance: ");
double balance = scanner.nextDouble();
scanner.nextLine();
accounts.add(new BankAccount(accNo, name, balance));
System.out.println("Account added successfully!");
}

static void withdraw() {


System.out.print("Enter Account Number: ");
int accNo = scanner.nextInt();

Page | 62
System.out.print("Enter Amount to Withdraw: ");
double amount = scanner.nextDouble();
scanner.nextLine();
for (BankAccount acc : accounts) {
if (acc.accountNumber == accNo) {
if (acc.balance >= amount) {
acc.balance -= amount;
System.out.println("Withdrawal successful! Remaining Balance: " +
acc.balance);
} else {
System.out.println("Insufficient funds!");
}
return;
}
}
System.out.println("Account not found!");
}

static void searchAccount() {


System.out.print("Enter Account Number: ");
int accNo = scanner.nextInt();
scanner.nextLine();
for (BankAccount acc : accounts) {
if (acc.accountNumber == accNo) {
System.out.println(acc);
return;
}
}
System.out.println("Account not found!");
}

static void deleteAccount() {


System.out.print("Enter Account Number: ");
int accNo = scanner.nextInt();
scanner.nextLine();
for (BankAccount acc : accounts) {
if (acc.accountNumber == accNo) {
accounts.remove(acc);
System.out.println("Account deleted successfully!");
return;
}
}
System.out.println("Account not found!");
}

static void showAccounts() {

Page | 63
if (accounts.isEmpty()) {
System.out.println("No accounts available!");
} else {
for (BankAccount acc : accounts) {
System.out.println(acc);
}
}
}
}

Output:

Page | 64
III. Create the above system using a menu and implement it using switch
statement. For example, in the above system implement the menu
driven like..
1. Add Student details.
2. Update student Details.
3. For Searching a Student.
4. Delete Student Details.
Code:
import java.util.ArrayList;
import java.util.Scanner;

class Student {
int id;
String name;
int age;
String course;

Student(int id, String name, int age, String course) {


this.id = id;
this.name = name;
this.age = age;
this.course = course;
}

public String toString() {


return "ID: " + id + ", Name: " + name + ", Age: " + age + ", Course: " + course;
}
}

public class StudentSystem {


static ArrayList<Student> students = new ArrayList<>();
static Scanner scanner = new Scanner(System.in);

public static void main(String[] args) {


while (true) {
System.out.println("\nMENU:");
System.out.println("1. Add Student Details");
System.out.println("2. Update Student Details");
System.out.println("3. Search a Student");
System.out.println("4. Delete Student Details");
System.out.println("5. Show All Students");
System.out.println("6. Exit");
System.out.print("Enter your choice: ");

Page | 65
int choice = scanner.nextInt();
scanner.nextLine();

switch (choice) {
case 1:
addStudent();
break;
case 2:
updateStudent();
break;
case 3:
searchStudent();
break;
case 4:
deleteStudent();
break;
case 5:
showStudents();
break;
case 6:
System.out.println("Exiting...");
return;
default:
System.out.println("Invalid choice! Try again.");
}
}
}

static void addStudent() {


System.out.print("Enter Student ID: ");
int id = scanner.nextInt();
scanner.nextLine();
System.out.print("Enter Name: ");
String name = scanner.nextLine();
System.out.print("Enter Age: ");
int age = scanner.nextInt();
scanner.nextLine();
System.out.print("Enter Course: ");
String course = scanner.nextLine();
students.add(new Student(id, name, age, course));
System.out.println("Student added successfully!");
}

static void updateStudent() {


System.out.print("Enter Student ID to Update: ");
int id = scanner.nextInt();

Page | 66
scanner.nextLine();
for (Student s : students) {
if (s.id == id) {
System.out.print("Enter New Name: ");
s.name = scanner.nextLine();
System.out.print("Enter New Age: ");
s.age = scanner.nextInt();
scanner.nextLine();
System.out.print("Enter New Course: ");
s.course = scanner.nextLine();
System.out.println("Student details updated successfully!");
return;
}
}
System.out.println("Student not found!");
}

static void searchStudent() {


System.out.print("Enter Student ID to Search: ");
int id = scanner.nextInt();
scanner.nextLine();
for (Student s : students) {
if (s.id == id) {
System.out.println(s);
return;
}
}
System.out.println("Student not found!");
}

static void deleteStudent() {


System.out.print("Enter Student ID to Delete: ");
int id = scanner.nextInt();
scanner.nextLine();
for (Student s : students) {
if (s.id == id) {
students.remove(s);
System.out.println("Student deleted successfully!");
return;
}
}
System.out.println("Student not found!");
}

static void showStudents() {


if (students.isEmpty()) {

Page | 67
System.out.println("No students available!");
} else {
for (Student s : students) {
System.out.println(s);
}
}
}
}

Output:

Page | 68
Practical No:-13
I. Create the above system use interface of menu using JAVAFX.
Code:
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

class Student {
int id;
String name;
int age;
String course;

Student(int id, String name, int age, String course) {


this.id = id;
this.name = name;
this.age = age;
this.course = course;
}

public String toString() {


return "ID: " + id + ", Name: " + name + ", Age: " + age + ", Course: " + course;
}
}

public class StudentSystemGUI extends Application {


ObservableList<Student> students = FXCollections.observableArrayList();
ListView<Student> studentListView = new ListView<>(students);

public static void main(String[] args) {


launch(args);
}

@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Student Management System");

Button addButton = new Button("Add Student");


Button updateButton = new Button("Update Student");

Page | 69
Button searchButton = new Button("Search Student");
Button deleteButton = new Button("Delete Student");
Button showButton = new Button("Show All Students");

addButton.setOnAction(e -> addStudent());


updateButton.setOnAction(e -> updateStudent());
searchButton.setOnAction(e -> searchStudent());
deleteButton.setOnAction(e -> deleteStudent());
showButton.setOnAction(e -> showStudents());

VBox layout = new VBox(10);


layout.setAlignment(Pos.CENTER);
layout.getChildren().addAll(addButton, updateButton, searchButton,
deleteButton, showButton, studentListView);

Scene scene = new Scene(layout, 400, 400);


primaryStage.setScene(scene);
primaryStage.show();
}

private void addStudent() {


TextInputDialog dialog = new TextInputDialog();
dialog.setTitle("Add Student");
dialog.setHeaderText("Enter Student Details (ID, Name, Age, Course)");
dialog.setContentText("Example: 1, John, 20, CS");
dialog.showAndWait().ifPresent(input -> {
String[] parts = input.split(",");
if (parts.length == 4) {
students.add(new Student(Integer.parseInt(parts[0].trim()), parts[1].trim(),
Integer.parseInt(parts[2].trim()), parts[3].trim()));
}
});
}

private void updateStudent() {


Student selected = studentListView.getSelectionModel().getSelectedItem();
if (selected != null) {
TextInputDialog dialog = new TextInputDialog(selected.name + ", " +
selected.age + ", " + selected.course);
dialog.setTitle("Update Student");
dialog.setHeaderText("Modify Student Details");
dialog.setContentText("Enter Name, Age, Course");
dialog.showAndWait().ifPresent(input -> {
String[] parts = input.split(",");
if (parts.length == 3) {
selected.name = parts[0].trim();

Page | 70
selected.age = Integer.parseInt(parts[1].trim());
selected.course = parts[2].trim();
studentListView.refresh();
}
});
}
}

private void searchStudent() {


TextInputDialog dialog = new TextInputDialog();
dialog.setTitle("Search Student");
dialog.setHeaderText("Enter Student ID to Search");
dialog.showAndWait().ifPresent(input -> {
int id = Integer.parseInt(input.trim());
for (Student s : students) {
if (s.id == id) {
Alert alert = new Alert(Alert.AlertType.INFORMATION, s.toString(),
ButtonType.OK);
alert.show();
return;
}
}
new Alert(Alert.AlertType.ERROR, "Student not found!",
ButtonType.OK).show();
});
}

private void deleteStudent() {


Student selected = studentListView.getSelectionModel().getSelectedItem();
if (selected != null) {
students.remove(selected);
}
}

private void showStudents() {


studentListView.refresh();
}
}

Output:

Page | 71
Page | 72

You might also like