ECE-B21-E2 OOPS Final Record
ECE-B21-E2 OOPS Final Record
INDEX
S.No. Name of lab Page No. Date of lab Submission Date Remarks
01. Week-01 2
02. Week-02 5
03. Week-03 8
04. Week-04 11
05. Week-05 16
06. Week-06 19
07. Week-07 25
08. Week-08 29
09. Week-09 31
10. Week-10 33
WEEK-01
1. Java Program to Solve Quadratic Equation
import java.util.Scanner;
public class QuadraticEquation {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter coefficients a, b, and c: ");
double a = input.nextDouble();
double b = input.nextDouble();
double c = input.nextDouble();
double determinant = b * b - 4 * a * c;
if (determinant > 0) {
double root1 = (-b + Math.sqrt(determinant)) / (2 * a);
double root2 = (-b - Math.sqrt(determinant)) / (2 * a);
System.out.println("Real and Distinct roots: " + root1 + " and " +
root2);
} else if (determinant == 0) {
double root = -b / (2 * a);
System.out.println("Real and Equal roots: " + root);
} else {
double realPart = -b / (2 * a);
double imaginaryPart = Math.sqrt(-determinant) / (2 * a);
System.out.println("Complex roots: " + realPart + " ± " + imaginaryPart
+ "i");
}
input.close();
}
}
WEEK-02
1. Write a Java program to sort a given list of numbers.
import java.util.Arrays;
import java.util.Scanner;
public class SortNumbers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of elements: ");
int n = input.nextInt();
int[] numbers = new int[n];
System.out.println("Enter the numbers:");
for (int i = 0; i < n; i++) {
numbers[i] = input.nextInt();
}
Arrays.sort(numbers);
System.out.println("Sorted numbers: " + Arrays.toString(numbers));
input.close();
}
}
Week –03
1. Write an application that uses String method indexOf to determine the total number of
occurrences of any given alphabet in a defined text.
import java.util.Scanner;
public class CountCharacter {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a text: ");
String text = scanner.nextLine();
System.out.print("Enter a character to count: ");
char ch = scanner.next().charAt(0);
int count = 0;
int index = text.indexOf(ch);
while (index != -1) {
count++;
index = text.indexOf(ch, index + 1);
}
System.out.println("The character '" + ch + "' appears " + count + " times.");
scanner.close();
}
}
2. Write a Java program to print all vowels in given string and count number of vowels and
consonants present in given string
import java.util.Scanner;
public class CountVowelsConsonants {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = scanner.nextLine().toLowerCase();
int vowels = 0, consonants = 0;
System.out.print("Vowels: ");
for (char ch : str.toCharArray()) {
if ("aeiou".indexOf(ch) != -1) {
vowels++;
System.out.print(ch + " ");
} else if (ch >= 'a' && ch <= 'z') {
consonants++;
}
}
System.out.println("\nNumber of Vowels: " + vowels);
System.out.println("Number of Consonants: " + consonants);
scanner.close();
}
}
3. Write an application that finds the substring from any given string using substring method
import java.util.Scanner;
public class SubstringExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = scanner.nextLine();
System.out.print("Enter starting index for substring: ");
int start = scanner.nextInt();
System.out.print("Enter ending index for substring: ");
int end = scanner.nextInt();
if (start >= 0 && end <= str.length() && start < end) {
System.out.println("Substring: " + str.substring(start, end));
} else {
System.out.println("Invalid index range.");
}
scanner.nextLine(); // Consume newline
System.out.print("Enter prefix to check: ");
String prefix = scanner.nextLine();
System.out.print("Enter suffix to check: ");
String suffix = scanner.nextLine();
System.out.println("Starts with \"" + prefix + "\": " + str.startsWith(prefix));
System.out.println("Ends with \"" + suffix + "\": " + str.endsWith(suffix));
scanner.close();
}
}
WEEK-04
1. Write a program to display details of the required employee based on his Id. The details of
employees includes, Emp_name, Emp_age, Emp_gender, Emp_designation, Emp_salary,
Emp_Address etc.
import java.util.Scanner;
class Employee {
int empId;
String name, gender, designation, address;
int age;
double salary;
Employee(int empId, String name, int age, String gender, String designation, double salary, String
address) {
this.empId = empId;
this.name = name;
this.age = age;
this.gender = gender;
this.designation = designation;
this.salary = salary;
this.address = address;
}
void displayDetails() {
System.out.println("\nEmployee Details:");
System.out.println("ID: " + empId);
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Gender: " + gender);
System.out.println("Designation: " + designation);
System.out.println("Salary: " + salary);
System.out.println("Address: " + address);
}
}
public class EmployeeDetails {
public static void main(String[] args) {
// Creating an array of Employee objects
Employee[] employees = {
new Employee(101, "Alice", 30, "Female", "Software Engineer", 60000, "New York"),
new Employee(102, "Bob", 28, "Male", "Data Analyst", 55000, "California"),
new Employee(103, "Charlie", 35, "Male", "Project Manager", 75000, "Texas")
};
Scanner scanner = new Scanner(System.in);
System.out.print("Enter Employee ID to search: ");
int searchId = scanner.nextInt();
boolean found = false;
for (Employee emp : employees) {
if (emp.empId == searchId) {
emp.displayDetails();
found = true;
break;
}
}
if (!found) {
System.out.println("Employee not found!");
}
scanner.close();
}
}
2. Implement the following case study using OOP concepts in Java.E-Book stall : Every book has
Properties i.e. Book_Name, Book_Author, Book_Count ; Every Customer has properties as :
Customer_Id, Customer_Name,Customer_Address and he can buy Books from the E-Book stall
by giving book name, author name and number of books he/she want to buy .Write a Program
which will display the list books bought by the customer and remaining text books in the E-book
stall with the count
class Book {
String Book_Name, Book_Author;
int Book_count;
Book(String name, String author, int count) {
this.Book_Name = name;
this.Book_Author = author;
this.Book_count = count;
}
public void buy() {
if (Book_count > 0) { // Check if there are books available
Book_count--;
System.out.println("Bought " + Book_Name);
System.out.println("Remaining books: " + Book_count);
} else {
System.out.println(Book_Name + " is out of stock.");
}
}
}
class Customer {
int Customer_Id;
String Customer_Name;
String Customer_Address;
Customer(int id, String name, String address) {
this.Customer_Id = id;
this.Customer_Name = name;
this.Customer_Address = address;
}
void order(Book b) {
b.buy();
}
ELECTRONICS AND COMMUNICATION ENGINEERING
14
WEEK-05
1. Write an application that prompts the user for the radius of a circle and uses a method called
circleArea to calculate the area of the circle and uses a method circlePerimeter to calculate the
perimeter of the circle.
import java.util.Scanner;
public class CircleCalculator {
// Method to calculate the area of the circle
public static double circleArea(double radius) {
return Math.PI * radius * radius;
}
// Method to calculate the perimeter (circumference) of the circle
public static double circlePerimeter(double radius) {
return 2 * Math.PI * radius;
}
public static void main(String[] args) {
// Create a Scanner object to read input from the user
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter the radius
System.out.print("Enter the radius of the circle: ");
double radius = scanner.nextDouble();
// Calculate the area and perimeter using the methods
double area = circleArea(radius);
double perimeter = circlePerimeter(radius);
// Display the results
System.out.println("Area of the circle: " + area);
System.out.println("Perimeter (Circumference) of the circle: " + perimeter);
// Close the scanner
scanner.close();
}
}
2. Create a class Account with an instance variable balance (double). It should contain a
constructor that initializes the balance, ensuring that the initial balance is greater than 0.0. Acct
details: Acct_Name, Acct_acctno, Acct_Bal, Acct_Address.Create two methods namely credit
and debit, getBalance. The Credit adds the amount (passed as parameter) to balance and does
not return any data. Debit method withdraws money from an Account. GetBalance displays the
amount. Ensure that the debit amount does not exceed the Account’s balance. In that case the
balance should be left unchanged and the method should print a message indicating“Debit
amount exceeded account balance”.
import java.util.*;
class Account {
String Acct_Name;
long Acct_acctno;
double Acct_Bal;
String Acct_Address;
public void credit(double balance) {
Acct_Bal = Acct_Bal + balance;
}
public Account(double money) {
Acct_Bal = money;
}
public void debit(double money) {
if (money <= Acct_Bal) {
System.out.println("Debited money: " + money);
Acct_Bal = Acct_Bal - money;
System.out.println("Available Balance: " + Acct_Bal);
} else {
System.out.println("Your money exceeds your Account Balance");
}
}
public void getBalance() {
System.out.println("Available Balance is " + Acct_Bal);
}}
public class Bank {
public static void main(String arg[]) {
Scanner s = new Scanner(System.in);
System.out.println("Enter the amount you have: ");
Week-06
1. Write a Java program to find Area and Circle of different shapes using polymorphism concept
import java.util.Scanner;
class Shape {
public double area() {
return 0;
}}
class Square extends Shape {
private double side;
Square(double side) {
this.side = side;
}
@Override
public double area() {
return side * side;
}}
class Circle extends Shape {
private double radius;
Circle(double r) {
this.radius = r;
}
@Override
public double area() {
return Math.PI * radius * radius;
}}
public class AreaUsingPolymorphism {
public static void main(String a[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the side of Square: ");
Square s = new Square(sc.nextDouble());
System.out.println("Area of Square: " + s.area());
System.out.println("Enter the radius of Circle: ");
Circle c = new Circle(sc.nextDouble());
System.out.println("Area of Circle: " + c.area());
}}
ELECTRONICS AND COMMUNICATION ENGINEERING
19
2. Write a Java program which can give example of Method overloading and overriding
// Class 1: Animal (Superclass for Method Overriding)
class Animal {
// Method in the base class
public void sound() {
System.out.println("Animal makes a sound.");
}
}
// Class 2: Dog (Subclass that overrides the sound method)
class Dog extends Animal {
// Overriding the sound() method of Animal class
@Override
public void sound() {
System.out.println("Dog barks.");
}
}
// Class 3: Cat (Another subclass that overrides the sound method)
class Cat extends Animal {
// Overriding the sound() method of Animal class
@Override
public void sound() {
System.out.println("Cat meows.");
}
}
// Class 4: Calculator (For Method Overloading Example)
class Calculator {
// Method overloading by changing the number of parameters
public int add(int a, int b) {
return a + b;
}
// Method overloading by changing the type of parameters
public double add(double a, double b) {
return a + b;
}
// Method overloading by changing the number and type of parameters
ELECTRONICS AND COMMUNICATION ENGINEERING
20
3. Write an application to create a super class Employee with information first name & last name
and methods getFirstName(), getLastName() derive the subclasses ContractEmployee and
RegularEmployee with the information about department, designation & method
displayFullName() , getDepartment(), getDesig() to print the salary and to set department name
& designation of the corresponding sub-class objects respectively.
class Employee {
String firstname;
String lastname;
public void getFirstName() {
System.out.println(firstname);
}
public void getLastName() {
System.out.println(lastname);
}
}
}
public void displayFullName() {
System.out.println("Full name of Contract employee: " + firstname + " " + lastname);
}
}
r.setFirstName("Mood");
r.setLastName("Bhupathi");
r.setDepartment("CSE");
r.setDesignation("Student");
r.displayFullName();
r.getDepartment();
r.getDesignation();
WEEK-07
1. Create an abstract class Shape which calculates the area and volume of 2-d and 3-d shapes
with methods getArea() and getVolume(). Reuse this class to calculate the area and volume of
square ,circle ,cube and sphere
abstract class Shape_2D {
int length;
Shape_2D(int length) {
this.length = length;
}
abstract double getArea();
}
class Square extends Shape_2D {
Square(int side) {
super(side);
}
double getArea() {
return length * length;
}
}
class Circle extends Shape_2D {
Circle(int radius) {
super(radius);
}
double getArea() {
return Math.PI * length * length;
}
}
abstract class Shape_3D {
int length;
Shape_3D(int length) {
this.length = length;
}
abstract double getArea();
abstract double getVolume();
}
2. Create an Interface payable with method getAmount ().Calculate the amount to be paid to
Invoice and Employee by implementing Interface
abstract class Employee {
double amount;
Employee(double amount) {
this.amount = amount;
}
abstract double getAmount();
}
class HourlyEmployee extends Employee {
int hours;
HourlyEmployee(int hours, double amount) {
super(amount);
this.hours = hours;
}
double getAmount() {
return hours * amount;
}
}
class WeeklyEmployee extends Employee {
int weeks;
WeeklyEmployee(int weeks, double amount) {
super(amount);
this.weeks = weeks;
}
double getAmount() {
return weeks * amount;
}
}
public class EmployeeDemo {
public static void main(String[] args) {
Employee h = new HourlyEmployee(5, 100.25);
Employee w = new WeeklyEmployee(4, 150.50);
System.out.println("Hourly Employee Amount: " + h.getAmount());
System.out.println("Weekly Employee Amount: " + w.getAmount()); }}
WEEK-08
1. Write a Java program to create a package called dept. Create four classes as CSE, ECE, ME
and CE adds methods in each class which can display subject names of your respective year.
access this package classes from main class
import dept.CSE;
import dept.ECE;
import dept.ME;
import dept.CE;
WEEK-09
1 Program for demonstrating the use of throw, throws & finally - Create a class with a main( ) that
throws an object of class Exception inside a try block. Give the constructor for Exception a
String argument. Catch the exception inside a catch clause and print the String argument. Add a
finally clause and print a message to prove you were there
import java.util.Scanner;
class LaptopException extends Exception {
LaptopException(String x) {
super(x);
}
static void classCheck(String s) throws ClassNotFoundException {
Class.forName(s);
System.out.println("Class had found");
}}
public class ExceptionHandling {
static void check(String laptop) {
try {
if (laptop.equals("Lenovo")) {
System.out.println(laptop + " I will purchase it");
} else {
throw new LaptopException("Wrong Laptop, I will buy another");
}
} catch (LaptopException e) {
System.out.println(e);
// e.printStackTrace();
} finally {
System.out.println("Check function is completed");
}
}
public static void main(String arg[]) throws ClassNotFoundException {
Scanner sc = new Scanner(System.in);
System.out.println("Owner: Enter the name of Laptop");
String a = sc.nextLine();
check(a);
LaptopException.classCheck("LaptopException"); }}
2. Write a program that shows that the order of the catch blocks is important. If you try to catch a
superclass exception type before a subclass type, the compiler should generate errors.
class NameException extends RuntimeException {
NameException(String name) {
System.out.println(name);
}
}
public class OrderException {
public static void main(String arg[]) {
String name = "Chimtu";
try {
if (name == "Chimtu") {
System.out.println("You are permitted to learn");
} else {
throw new NameException("You are the wrong person and not allowed");
}
} catch (NameException e) {
System.out.println(e);
} catch (RuntimeException e) {
System.out.println(e);
} finally {
System.out.println("Beginning of End");
}
}
}
WEEK-10
1. Write a program to create MyThread class with run() method and then attach a thread to this
MyThread class object.
public class MyThread extends Thread {
public void run() {
System.out.println("In run");
for (int i = 0; i < 5; i++) {
System.out.println("Hanoi");
}
}
public static void main(String arg[]) {
MyThread t = new MyThread();
t.start();
}
}
2. Write a Program using Threads to simulate a traffic light. The Signal lights should glow after
each 10 seconds, one by one. For example: Firstly Red, then after 10 seconds, red will be put off
and yellow will start glowing and then accordingly green
class Red implements Runnable {
public void run() {
System.out.println("Red");
}
}
class Blue implements Runnable {
public void run() {
System.out.println("Blue");
}
}
class Green implements Runnable {
public void run() {
System.out.println("Green");
}
}
public class TrafficThread {
public static void main(String arg[]) throws InterruptedException {
Runnable red = new Red();
Runnable green = new Green();
Runnable blue = new Blue();
Thread redd = new Thread(red);
Thread greenn = new Thread(green);
Thread bluee = new Thread(blue);
redd.start();
redd.sleep(10000); // Sleep for 10 seconds
greenn.start();
greenn.sleep(10000); // Sleep for 10 seconds
bluee.start();
}}
3. Write a Program using Threads for the following case study: Movie Theatre To watch a movie
the following process is to be followed, at first get the ticket then show the ticket. Assume that N
persons are trying to enter the Theatre hall all at once, displaying their sequence of entry into
the theater. Note: The person should enter only after getting a ticket and showing it to the boy
// Class 1: TicketCounter (used to simulate getting a ticket)
class TicketCounter {
public synchronized void getTicket(int personId) {
System.out.println("Person " + personId + " gets the ticket.");
}
}
// Class 2: TheaterEntry (used to simulate showing the ticket and entering the theater)
class TheaterEntry extends Thread {
private TicketCounter ticketCounter;
private int personId;
public TheaterEntry(TicketCounter ticketCounter, int personId) {
this.ticketCounter = ticketCounter;
this.personId = personId;
}
@Override
public void run() {
// First, get the ticket
ticketCounter.getTicket(personId);
// Then, show the ticket to the boy and enter the theater
System.out.println("Person " + personId + " shows the ticket and enters the theater.");
}
}
// Main class to test the program
public class MovieTheatre {
public static void main(String[] args) {
TicketCounter ticketCounter = new TicketCounter(); // Shared resource
// Simulating N persons trying to enter the theater
int N = 5; // Number of people trying to enter
for (int i = 1; i <= N; i++) {
TheaterEntry person = new TheaterEntry(ticketCounter, i);
person.start(); // Start the thread for each person }}}