0% found this document useful (0 votes)
6 views15 pages

Java Lab Report

Uploaded by

Sakibul Islam
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)
6 views15 pages

Java Lab Report

Uploaded by

Sakibul Islam
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/ 15

Lab Report

Course name: Programming in Java


Course code: CSC 384
Section: A

Submitted To
Rubayea Ferdows
Assistant Professor,
Department of CSE,
IUBAT.

Submitted By
Nawshin Afifa Afi
ID:20103185

Date of Submission:19th August, 2025


Index

SL No. Questions Date


1 1. Define a Super class named Point containing: - An instance variable named
x of type int.
- An instance variable named y of type int. - Declare a method named
toString()Returns
a string representation of the point. - Constructor that accepts values of all
data members
as arguments. Define a Subclass named Circle. A Circle object stores a radius
(double)
and inherits the (x, y) coordinates of its center from its super class Point. Each
Circle
object should have the following public methods:
● Circle(x, y, radius) Constructs a new circle with a center specified by the
given
coordinators x, y and with the given double radius.
● getArea()
Returns the area occupied by the circle, using the formula πr2.
● getCircumference()
Returns the circle's circumference (distance around the circle), using the
formula
2πr.
● toString()
Returns a string representation of the circle, such as "Circle[center=(75, 20);
radius=30]".
2 Abstract Class A contains array1 and array2 methods where none of them
have definition. Create a child class C that will have the body for the two
array methods of 2 dimensions. And then create a method called multiply
inside Class C that will multiply the two dimensional arrays.
3 Interface A has 2 methods. One of them will take the user input of a number
and another method will identify whether the number is an automorphic
number or not. Interface B also has two methods where in the same way one
of them will take user input another will check whether the number is duck
number or not. class C will implement all 4 methods.
4 Student A has given the admission test. If the mark is less than 40 then the
program will throw arithmetic exceptions. But if the mark is 40 or more then
the numbers of Math and Physics will be checked individually. If the mark is
20 in each subject then the student can get the admission in CSE dept. But for
none of the subjects the student should get 0 or none of the subject questions
should remain unanswered. Otherwise it will show another exception.
5 Imagine a situation where you are driving a car. Your car has an automatic
feature that tells you if any car is approaching your car from the opposite
direction. One day you were running late for the office and started driving very
fast and also took a shortcut on the wrong side of the road. Suddenly a car
approached you from the opposite direction as
you were on the wrong side. But due to the safety feature of your car you could
avoid a life taking accident. Though some scratches were there in your car but
you were not harmed because you got alarmed immediately before the crash
occurred. Now write a program using the OOP feature of java that will have
similarity with the above scenario.
6 ABC Company has two types of employees - Manager and Programmer. Based
on their role they have separate job responsibilities. The company calculates the
salary of their employees. But the calculation formula for employees is different
for different types of roles.
7 Imagine in your home you have a single kitchen which is used by all of your
family members. You like to have bread and butter in your breakfast, your
mother likes bread, vegetables and tea, your sister likes to have noodles and
mango juice. But each of you are using the same kitchen every day, only the
preparation for each person is different .
8 Write a program that prompts a user for a String, counts the number of vowels,
consonants and digits (0-9) contained in the string and prints their number of
occurrence and the percentages (with 2 decimal digits).
Enter a String: testing12345
Number of vowels: 2 (16.67%)
Number of consonants: 5 (41.67%)
Number of digits: 5 (41.67%)
9 Write a program called SharedCounter.java in which 10 threads each increment
a shared int counter 10 times. When all the threads have finished, print the final
value of the counter. If the initial value is zero, do you always get 100? Arrange
for your code to sometimes print the wrong answer. (Hint: try using some well-
placed calls to Thread.yield() or Thread.sleep()).

10 Create your own exception class using the extends keyword. Write a constructor
for this class that takes a String argument and stores it inside the object with a
String reference. Write a method that prints out the stored String. Create a try-
catch clause to exercise your new exception.

Signature
1. Define a Super class named Point containing: - An instance variable named x of type int.
- An instance variable named y of type int. - Declare a method named toString()Returns
a string representation of the point. - Constructor that accepts values of all data members
as arguments. Define a Subclass named Circle. A Circle object stores a radius (double)
and inherits the (x, y) coordinates of its center from its super class Point. Each Circle
object should have the following public methods:
● Circle(x, y, radius) Constructs a new circle with a center specified by the given
coordinators x, y and with the given double radius.
● getArea()
Returns the area occupied by the circle, using the formula πr2.
● getCircumference()
Returns the circle's circumference (distance around the circle), using the formula
2πr.
● toString()
Returns a string representation of the circle, such as "Circle[center=(75, 20);
radius=30]".

Answer:

Algorithm:
Step 1: Start.
Step 2: Define a superclass Point with:
→ Two integer variables x and y.
→ A constructor to initialize x and y.
→ A method toString() to return (x, y).
Step 3: Define a subclass Circle that extends Point with:
→ One double variable radius.
→ A constructor to initialize x, y, and radius using super().
→ A method getArea() to calculate area = πr².
→ A method getCircumference() to calculate circumference = 2πr.
→ An overridden method toString() to return circle details.
Step 4: In the main() method:
→ Create a Circle object with given x, y, and radius.
→ Display the circle details using toString().
→ Calculate and display the area and circumference.
Step 5: End.
2. Abstract Class A contains array1 and array2 methods where none of them have
definition. Create a child class C that will have the body for the two array methods of 2
dimensions. And then create a method called multiply inside Class C that will multiply
the two dimensional arrays.
Answer:
Algorithm:
Step 1: Start.
Step 2: Create an abstract class A containing two abstract methods:
→ array1()
→ array2()
(both return 2D arrays but have no body).
Step 3: Create a child class C that extends A.
→ Define array1() method to return a 2D array.
→ Define array2() method to return another 2D array.
Step 4: Inside class C, define a method multiply():
→ Take array1 and array2.
→ Initialize a result 2D array with size [rows of array1][columns of array2].
→ Use three nested loops to multiply matrices:
• Outer loop → iterate rows of array1.
• Middle loop → iterate columns of array2.
• Inner loop → calculate sum of products.
Step 5: Return the result matrix.
Step 6: In the main() method:
→ Create an object of class C.
→ Call multiply() method.
→ Print the result matrix.
Step 7: End.
3. Interface A has 2 methods. One of them will take the user input of a number and another
method will identify whether the number is an automorphic number or not. Interface B
also has two methods where in the same way one of them will take user input another
will check whether the number is duck number or not. class C will implement all 4
methods.
Answer:
Algorithm:
Step 1: Start.
Step 2: Create Interface A with methods:
inputAutomorphic() → takes number from user
checkAutomorphic() → checks if number is automorphic
Step 3: Create Interface B with methods:
inputDuck() → takes number from user
checkDuck() → checks if number is duck
Step 4: Create Class C implementing both interfaces.
Define all 4 methods in Class C.
Step 5: For Automorphic check:
Calculate square of number
Convert square to string
If string ends with original number → Automorphic
Step 6: For Duck check:
Convert number to string
If string contains '0' and first digit ≠ 0 → Duck number
Step 7: In main() method:
Create object of C
Call input and check methods for Automorphic
Call input and check methods for Duck
Step 8: End.
4. Student A has given the admission test. If the mark is less than 40 then the program will
throw arithmetic exceptions. But if the mark is 40 or more then the numbers of Math and
Physics will be checked individually. If the mark is 20 in each subject then the student
can get the admission in CSE dept. But for none of the subjects the student should get 0
or none of the subject questions should remain unanswered. Otherwise it will show
another exception.

Answer:
Algorithm:
Step 1: Start.
Step 2: Take input marks for total, Math, and Physics.
Step 3: If total marks < 40 → throw ArithmeticException("Total marks too low for admission").
Step 4: Else (total marks ≥ 40):
→ Check Math & Physics marks individually:
• If Math < 20 or Physics < 20 → print "Not eligible for CSE"
• If Math = 0 or Physics = 0 → throw Exception("Invalid marks: subject not answered")
Step 5: Else → print "Eligible for CSE admission".
Step 6: End.
5. Imagine a situation where you are driving a car. Your car has an automatic feature that
tells you if any car is approaching your car from the opposite direction. One day you
were running late for the office and started driving very fast and also took a shortcut on
the wrong side of the road. Suddenly a car approached you from the opposite direction as
you were on the wrong side. But due to the safety feature of your car you could avoid a
life taking accident. Though some scratches were there in your car but you were not
harmed because you got alarmed immediately before the crash occurred.
Now write a program using the OOP feature of java that will have similarity with the
above scenario.
Answer:
Algorithm:
Step 1: Start the program.
Step 2: Create a superclass Car with:
Instance variable: carName (name of the car)
Method drive() → prints that the car is driving
Step 3: Create an interface SafetyFeature with two abstract methods:
detectOppositeCar() → method to detect if a car is approaching from opposite direction
alertDriver() → method to alert the driver about danger
Step 4: Create a subclass MyCar that:
Extends Car
Implements SafetyFeature
Implements the two interface methods:
• detectOppositeCar() → prints warning about opposite car
• alertDriver() → prints that driver took emergency action
Adds a method driveFastWrongSide() → simulates driving fast on wrong side
Step 5: In the main method:
Create an object of MyCar with a car name
Call the following methods in order:
1. drive() → car starts driving
2. driveFastWrongSide() → simulate driving fast on wrong side
3. detectOppositeCar() → safety feature detects danger
4. alertDriver() → driver gets alerted and takes action
Print final message → driver is safe, car scratched
Step 6: End
6. ABC Company has two types of employees - Manager and Programmer. Based on their
role they have separate job responsibilities. The company calculates the salary of their
employees. But the calculation formula for employees is different for different types of
roles.
Answer:
Algorithm:
Step 1: Start the program.
Step 2: Create a superclass Employee with:
Instance variables: name, id, basicSalary
Constructor to initialize the variables
A method displayInfo() → prints employee information
An abstract method calculateSalary() → to be defined in subclasses
Step 3: Create subclass Manager that extends Employee:
Override calculateSalary() → formula: basicSalary + 10000 (example: bonus for
manager)
Add method managerResponsibilities() → prints Manager responsibilities
Step 4: Create subclass Programmer that extends Employee:
Override calculateSalary() → formula: basicSalary + 5000 (example: bonus for
programmer)
Add method programmerResponsibilities() → prints Programmer responsibilities
Step 5: In main method:
Create objects of Manager and Programmer
Call displayInfo(), calculateSalary(), and responsibility methods for each object
Step 6: End program.
7. Imagine in your home you have a single kitchen which is used by all of your family
members. You like to have bread and butter in your breakfast, your mother likes bread,
vegetables and tea, your sister likes to have noodles and mango juice. But each of you are
using the same kitchen every day, only the preparation for each person is different.
Answer:
Algorithm:
Step 1: Start program.
Step 2: Create superclass Kitchen with:
Method prepare() → prints generic message about using kitchen
Step 3: Create subclasses for each family member:
Me → override prepare() to make bread + butter
Mother → override prepare() to make bread + vegetables + tea
Sister → override prepare() to make noodles + mango juice
Step 4: In main method:
Create objects of each family member
Call prepare() for each object to simulate using the kitchen
Step 5: End program.
8. Write a program that prompts a user for a String, counts the number of vowels,
consonants and digits (0-9) contained in the string and prints their number of
occurrence and the percentages (with 2 decimal digits).
Enter a String: testing12345
Number of vowels: 2 (16.67%)
Number of consonants: 5 (41.67%)
Number of digits: 5 (41.67%)
Answer:
Algorithm:
Step 1: Start program.
Step 2: Prompt the user to enter a string.
Step 3: Initialize counters:
vowels = 0
consonants = 0
digits = 0
Step 4: Loop through each character of the string:
If character is a vowel → increment vowels
Else if character is a letter → increment consonants
Else if character is a digit (0-9) → increment digits
Step 5: Calculate percentages:
vowelPercentage = (vowels / length) * 100
consonantPercentage = (consonants / length) * 100
digitPercentage = (digits / length) * 100
Step 6: Print number and percentage of vowels, consonants, and digits with 2 decimal places.
Step 7: End program.
9. Write a program called SharedCounter.java in which 10 threads each increment a shared
int counter 10 times. When all the threads have finished, print the final value of the
counter. If the initial value is zero, do you always get 100? Arrange for your code to
sometimes print the wrong answer. (Hint: try using some well-placed calls to
Thread.yield() or Thread.sleep().)
Answer:
Algorithm:
Step 1: Start program.
Step 2: Create a shared variable counter = 0.
Step 3: Create a Thread class (or Runnable) that increments the counter 10 times:
Inside the loop:
Read the current counter value
Increment by 1
Assign back to counter
Introduce Thread.sleep() or Thread.yield() to simulate race condition
Step 4: Create 10 threads of this Runnable and start them.
Step 5: Wait for all threads to finish using join().
Step 6: Print the final value of the counter.
Step 7: End program.
10. Create your own exception class using the extends keyword. Write a constructor for this class
that takes a String argument and stores it inside the object with a String reference. Write a
method that prints out the stored String. Create a try-catch clause to exercise your new exception.
Answer:
Algorithm:
Step 1: Start program.
Step 2: Create a custom exception class by extending Exception:
Instance variable: message (String)
Constructor → accepts a String and stores it
Method printMessage() → prints the stored String
Step 3: In the main method:
Use try block → throw an instance of the custom exception
Use catch block → catch the exception and call printMessage()
Step 4: End program.

You might also like