0% found this document useful (0 votes)
13 views35 pages

ECE-B21-E2 OOPS Final Record

The document is a lab record for Object Oriented Programming using Java at Rajiv Gandhi University of Knowledge Technologies, Basar. It includes a structured index of weekly lab exercises, each containing Java programs that cover various topics such as solving quadratic equations, implementing a calculator, sorting numbers, and managing employee details. The document serves as a practical guide for students to learn and apply Java programming concepts through hands-on exercises.

Uploaded by

bharatsattem
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views35 pages

ECE-B21-E2 OOPS Final Record

The document is a lab record for Object Oriented Programming using Java at Rajiv Gandhi University of Knowledge Technologies, Basar. It includes a structured index of weekly lab exercises, each containing Java programs that cover various topics such as solving quadratic equations, implementing a calculator, sorting numbers, and managing employee details. The document serves as a practical guide for students to learn and apply Java programming concepts through hands-on exercises.

Uploaded by

bharatsattem
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

1

RAJIV GANDHI UNIVERSITY OF KNOWLEDGE TECHNOLOGIES,BASAR

OBJECT ORIENTED PROGRAMMING SYSTEM THROUGH JAVA – LAB 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

ELECTRONICS AND COMMUNICATION ENGINEERING


2

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();
}
}

ELECTRONICS AND COMMUNICATION ENGINEERING


3

2. Java Program to Implement Calculator Operations


import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter first number: ");
double num1 = input.nextDouble();
System.out.print("Enter operator (+, -, *, /): ");
char operator = input.next().charAt(0);
System.out.print("Enter second number: ");
double num2 = input.nextDouble();
double result;
switch (operator) {
case '+': result = num1 + num2; break;
case '-': result = num1 - num2; break;
case '*': result = num1 * num2; break;
case '/':
if (num2 != 0)
result = num1 / num2;
else {
System.out.println("Error! Division by zero.");
return; }
break;
default:
System.out.println("Invalid operator!");
return; }
System.out.println("Result: " + result); }}

ELECTRONICS AND COMMUNICATION ENGINEERING


4

3. Write a java program to find prime factors of given number


import java.util.Scanner;
public class PrimeFactors {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = input.nextInt();
System.out.print("Prime factors of " + number + " are: ");
for (int i = 2; i <= number; i++) {
while (number % i == 0) {
System.out.print(i + " ");
number /= i;
}
}
input.close();
}
}

ELECTRONICS AND COMMUNICATION ENGINEERING


5

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();
}
}

ELECTRONICS AND COMMUNICATION ENGINEERING


6

2. Java Program to Implement Binary Search


import java.util.Arrays;
import java.util.Scanner;
public class BinarySearch {
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[] arr = new int[n];
System.out.println("Enter the elements:");
for (int i = 0; i < n; i++) {
arr[i] = input.nextInt();
}
Arrays.sort(arr); // Binary search requires a sorted array
System.out.print("Enter the number to search: ");
int key = input.nextInt();
int result = Arrays.binarySearch(arr, key);
if (result >= 0) {
System.out.println("Element found at index " + result);
} else {
System.out.println("Element not found!");
}
input.close();
}
}

ELECTRONICS AND COMMUNICATION ENGINEERING


7

3. Write a java program to multiply two given matrices.


import java.util.Scanner;
public class MatrixMultiplication {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter size of first matrix (rows and columns): ");
int rows1 = input.nextInt(), cols1 = input.nextInt();
System.out.print("Enter size of second matrix (rows and columns): ");
int rows2 = input.nextInt(), cols2 = input.nextInt();
if (cols1 != rows2) {
System.out.println("Matrix multiplication not possible!");
return; }
int[][] matrix1 = new int[rows1][cols1];
int[][] matrix2 = new int[rows2][cols2];
int[][] product = new int[rows1][cols2];
System.out.println("Enter first matrix elements:");
for (int i = 0; i < rows1; i++)
for (int j = 0; j < cols1; j++)
matrix1[i][j] = input.nextInt();
System.out.println("Enter second matrix elements:");
for (int i = 0; i < rows2; i++)
for (int j = 0; j < cols2; j++)
matrix2[i][j] = input.nextInt();
System.out.println("Product of matrices:");
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols2; j++) {
for (int k = 0; k < cols1; k++) {
product[i][j] += matrix1[i][k] * matrix2[k][j]; }
System.out.print(product[i][j] + " ");
} System.out.println();
}}}

ELECTRONICS AND COMMUNICATION ENGINEERING


8

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();
}
}

ELECTRONICS AND COMMUNICATION ENGINEERING


9

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();
}
}

ELECTRONICS AND COMMUNICATION ENGINEERING


10

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();
}
}

ELECTRONICS AND COMMUNICATION ENGINEERING


11

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 = {

ELECTRONICS AND COMMUNICATION ENGINEERING


12

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();
}
}

ELECTRONICS AND COMMUNICATION ENGINEERING


13

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

public class BookSell {


public static void main(String[] arg) {
// Creating book objects
Book b1 = new Book("Do Hard Things", "Steve Magnus", 12);
Book b2 = new Book("Yogi", "Yoganand", 5);
Book b3 = new Book("Atomic Habits", "Harry", 13);

// Creating customer object


Customer c = new Customer(144, "Bhupathi", "Ankole");
// Customer ordering books
c.order(b1);
c.order(b2);
c.order(b1);
c.order(b3);
}
}

ELECTRONICS AND COMMUNICATION ENGINEERING


15

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();
}
}

ELECTRONICS AND COMMUNICATION ENGINEERING


16

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: ");

ELECTRONICS AND COMMUNICATION ENGINEERING


17

double money = s.nextDouble();


if (money > 0.0) {
Account A1 = new Account(money);
int k = 3;
while (k == 3) {
System.out.println("Enter 1 for credit, 2 for debit, and 3 for display");
int f = s.nextInt();
switch (f) {
case 1:
double addmoney;
System.out.println("Enter money you want to credit: ");
A1.credit(s.nextDouble());
break;
case 2:
double takemoney;
System.out.println("Enter money you want to debit: ");
takemoney = s.nextDouble();
A1.debit(takemoney);
break;
case 3:
A1.getBalance();
break;
}
System.out.println("Enter 1 to continue and any other number to close: ");
k = s.nextInt();
if (k == 1) {
k = 3;
} else {
k = 2;
}
}
} else {
System.out.println("You don't have enough money for creating an Account");
}
}}
ELECTRONICS AND COMMUNICATION ENGINEERING
18

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

public int add(int a, int b, int c) {


return a + b + c;
}
}
public class lab62 {
public static void main(String[] args) {
// Demonstrating Method Overriding
Animal animal = new Animal();
animal.sound(); // Calls the base class method
Dog dog = new Dog();
dog.sound(); // Calls the overridden method in Dog class
Cat cat = new Cat();
cat.sound(); // Calls the overridden method in Cat class
// Demonstrating Method Overloading
Calculator calculator = new Calculator();
// Overloaded methods in Calculator class
System.out.println("Sum of 2 and 3: " + calculator.add(2, 3)); // Calls add(int, int)
System.out.println("Sum of 2.5 and 3.5: " + calculator.add(2.5, 3.5)); // Calls add(double, double)
System.out.println("Sum of 1, 2, and 3: " + calculator.add(1, 2, 3)); // Calls add(int, int, int)
}
}

ELECTRONICS AND COMMUNICATION ENGINEERING


21

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);
}
}

class ContractEmployee extends Employee {


String department;
String designation;
public void setFirstName(String fname) {
super.firstname = fname;
}
public void setLastName(String lname) {
super.lastname = lname;
}
public void setDepartment(String dept) {
department = dept;
}
public void setDesignation(String desg) {
designation = desg;
}
public void getDepartment() {
System.out.println("Department of contract employee: " + department);
}
public void getDesignation() {
System.out.println("Designation of contract employee: " + designation);
ELECTRONICS AND COMMUNICATION ENGINEERING
22

}
public void displayFullName() {
System.out.println("Full name of Contract employee: " + firstname + " " + lastname);
}
}

class RegularEmployee extends Employee {


String department;
String designation;
int salary;
public void setFirstName(String fname) {
super.firstname = fname;
}
public void setLastName(String lname) {
super.lastname = lname;
}
public void setDepartment(String dep) {
department = dep;
}
public void setDesignation(String desg) {
designation = desg;
}
public void getDepartment() {
System.out.println("Department of regular employee: " + department);
}
public void getDesignation() {
System.out.println("Designation of regular employee: " + designation);
}
public void displayFullName() {
System.out.println("Full name of Regular Employee: " + firstname + " " + lastname);
}
}
public class Employees {
public static void main(String[] arg) {
RegularEmployee r = new RegularEmployee();
ELECTRONICS AND COMMUNICATION ENGINEERING
23

r.setFirstName("Mood");
r.setLastName("Bhupathi");
r.setDepartment("CSE");
r.setDesignation("Student");
r.displayFullName();
r.getDepartment();
r.getDesignation();

ContractEmployee c = new ContractEmployee();


c.setFirstName("Kasimalla");
c.setLastName("Neeraj");
c.setDepartment("CSE");
c.setDesignation("Student");
c.displayFullName();
c.getDepartment();
c.getDesignation();
}
}

ELECTRONICS AND COMMUNICATION ENGINEERING


24

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();
}

ELECTRONICS AND COMMUNICATION ENGINEERING


25

class Cube extends Shape_3D {


Cube(int side) {
super(side);
}
double getArea() {
return 6 * length * length;
}
double getVolume() {
return length * length * length;
}
}
class Sphere extends Shape_3D {
Sphere(int radius) {
super(radius);
}
double getArea() {
return 4 * Math.PI * length * length;
}
double getVolume() {
return (4.0 / 3.0) * Math.PI * length * length * length;
}
}
public class ShapeDemo {
public static void main(String[] args) {
Shape_2D sq = new Square(4);
Shape_2D c = new Circle(3);
Shape_3D cu = new Cube(4);
Shape_3D sp = new Sphere(4);

System.out.println("Square area: " + sq.getArea());


System.out.println("Circle area: " + c.getArea());
System.out.println("Cube area: " + cu.getArea());
System.out.println("Cube volume: " + cu.getVolume());
System.out.println("Sphere area: " + sp.getArea());
System.out.println("Sphere volume: " + sp.getVolume()); } }
ELECTRONICS AND COMMUNICATION ENGINEERING
26

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()); }}

ELECTRONICS AND COMMUNICATION ENGINEERING


27

3. Create an Interface StudentFee with methods getAmount(), getFirstName(), getLastName() ,


getAddress(), getContact(). Calculate the amount paid by the Hostler and Non Hostler student
by implementing interface Student Fee
interface Payable {
double getAmount();
}
class Invoice implements Payable {
double amount;
Invoice(double amount) {
this.amount = amount;
}
public double getAmount() {
return amount;
}
}
class Employee2 implements Payable {
double amount;
Employee2(double amount) {
this.amount = amount;
}
public double getAmount() {
return amount;
}
}
public class Payment {
public static void main(String[] args) {
Payable p = new Invoice(500.35);
Payable e = new Employee2(55.45);
System.out.println("Invoice Amount: " + p.getAmount());
System.out.println("Employee Amount: " + e.getAmount());
}}

ELECTRONICS AND COMMUNICATION ENGINEERING


28

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;

public class Department {


public static void main(String arg[]) {
CSE computer = new CSE();
ECE electronics = new ECE();
CE civil = new CE();
ME mechanical = new ME();
System.out.println("Subjects in CSE: " + computer.subjects());
System.out.println();
System.out.println("Subjects in ECE: " + electronics.subjects());
System.out.println();
System.out.println("Subjects in ME: " + mechanical.subjects());
System.out.println();
System.out.println("Subjects in CE: " + civil.subjects());
System.out.println();
}
}

ELECTRONICS AND COMMUNICATION ENGINEERING


29

2. Write a Calculator program : Include all calculator operations as classes in a Package


“Calculator” and import it to the main class.
class Addition {
public float add(float a, float b) {
return a + b;
}
public float add(float a, float b, float c) {
return a + b + c;
}
}
class Subtraction {
public float sub(float a, float b) {
return a - b;
}
public float sub(float a, float b, float c) {
return a - b - c;
}
}
class Multiplication {
public float multiply(float a, float b) {
return a * b;
}
}
class Division {
public float div(int a, int b) {
if (b != 0) {
return a / (float) b;
} else {
System.out.println("Error: Division by zero!");
return Float.NaN;
}
}
}

public class test {

ELECTRONICS AND COMMUNICATION ENGINEERING


30

public static void main(String[] args) {


Addition a1 = new Addition();
Subtraction s = new Subtraction();
Multiplication m = new Multiplication();
Division d = new Division();

// Perform and print calculations


System.out.println("Addition of two and three numbers respectively: " + a1.add(4f, 5f) + " " +
a1.add(5f, 10f, 15f));
System.out.println("Subtraction of two and three numbers respectively: " + s.sub(4.5f, 5.0f) + " " +
s.sub(3.5f, 1.0f, 1.0f));
System.out.println("Multiplication: " + m.multiply(3.0f, 2.0f));
System.out.println("Division: " + d.div(4, 2));
}
}

ELECTRONICS AND COMMUNICATION ENGINEERING


31

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"); }}

ELECTRONICS AND COMMUNICATION ENGINEERING


32

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");
}
}
}

ELECTRONICS AND COMMUNICATION ENGINEERING


33

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();
}
}

ELECTRONICS AND COMMUNICATION ENGINEERING


34

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();
}}

ELECTRONICS AND COMMUNICATION ENGINEERING


35

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 }}}

ELECTRONICS AND COMMUNICATION ENGINEERING

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy