Tutorial 4 Classes and Objects
MUST READ - Put all the source code and answers into a word file, NAME: Hicham Ouikrim
and upload the word file (just ONE Word file! name it with “your
ID+date”, e.g. 202512340001_20250930.doc). 312024704044
STU ID:
Note: there’s a deadline for uploading.
DATE: 01/11/2025
Attempt ALL questions.
1. Java API has the GregorianCalendar class in the [Link] package, which
you can use to obtain the year, month, and day of a date. The no-arg
constructor constructs an instance for the current date, and the methods
get([Link]), get([Link]), and
get(GregorianCalendar.DAY_OF_MONTH) return the year, month, and day.
Write a program to perform two tasks:
■ Display the current year, month, and day.
■ The GregorianCalendar class has the setTimeInMillis(long), which can be
used to set a specified elapsed time since January 1, 1970. Set the value to
1234567898765L and display the year, month, and day.
SOURCE CODE (TEXT)
import [Link];
public class hello {
public static void main(String[] args) {
// Task 1: Display current year, month, and day
[Link]("=== Current Date ===");
displayCurrentDate();
[Link](); // Empty line for separation
// Task 2: Set time to 1234567898765L and display year, month, and day
[Link]("=== Date for 1234567898765L ===");
displaySpecifiedDate();
}
// Method to display current date
public static void displayCurrentDate() {
// Create GregorianCalendar instance with no-arg constructor (current date)
GregorianCalendar currentDate = new GregorianCalendar();
// Get year, month, and day
int year = [Link]([Link]);
int month = [Link]([Link]) + 1; // Adding 1
because months are 0-based
int day = [Link](GregorianCalendar.DAY_OF_MONTH);
// Display the results
[Link]("Current Year: " + year);
[Link]("Current Month: " + month);
[Link]("Current Day: " + day);
}
// Method to display date for specified elapsed time
public static void displaySpecifiedDate() {
// Create GregorianCalendar instance
GregorianCalendar specifiedDate = new GregorianCalendar();
// Set the elapsed time since January 1, 1970
[Link](1234567898765L);
// Get year, month, and day
int year = [Link]([Link]);
int month = [Link]([Link]) + 1; // Adding 1
because months are 0-based
int day = [Link](GregorianCalendar.DAY_OF_MONTH);
// Display the results
[Link]("Year for 1234567898765L: " + year);
[Link]("Month for 1234567898765L: " + month);
[Link]("Day for 1234567898765L: " + day);
// Optional: Display the complete date for better understanding
[Link]("Complete Date: " + [Link]());
}
}
EXECUTION RESULTS (TEXT OR SNAPSHOTS)
DISCUSSION AND CONCLUSION
The program successfully demonstrates date manipulation using GregorianCalendar. Key learning:
months are 0-based in Java's Calendar class, requiring +1 adjustment for conventional display. The
conversion from milliseconds to date works accurately for both current and historical timestamps.
2. Design a class according to the UML class diagram shown below:
Rectangle
-length: double
-width: double
+Rectangle()
+Rectangle(len:double,
wid:double)
+getArea(): double
+getPerimeter(): double
+drawRect(): void
Where:
- the default constructor (without any parameters) set the length
and width of the rectangle both to be 10.0
- the constructor with parameters will set the length and width of
that rectangle with the given value (if the given value are larger
than 0, otherwise set both to be 10.0)
- getArea() returns the area of that rectangle if the range of the
length and width are between 10 to 50 (inclusive), otherwise
return value -1
- getPerimeter() returns the perimeter of the rectangle
- drawRect() draws a shape of that rectangle using asterisk (*) with
the length and width change to integer if the length and width
are between 10~50 (inclusive), otherwise draw a shape of 10*10
Write a program (another class) called TestRectangle with the
main() to test all methods within class Rectangle.
SOURCE CODE (TEXT)
public class Rectangle {
private double length;
private double width;
// Default constructor - sets both length and width to 10.0
public Rectangle() {
[Link] = 10.0;
[Link] = 10.0;
}
// Constructor with parameters
public Rectangle(double len, double wid) {
// Set to given values if positive, otherwise set both to 10.0
if (len > 0 && wid > 0) {
[Link] = len;
[Link] = wid;
} else {
[Link] = 10.0;
[Link] = 10.0;
}
}
// Returns area if dimensions are between 10-50 (inclusive), otherwise -1
public double getArea() {
if (length >= 10 && length <= 50 && width >= 10 && width <= 50) {
return length * width;
} else {
return -1;
}
}
// Returns perimeter of the rectangle
public double getPerimeter() {
return 2 * (length + width);
}
// Draws rectangle using asterisks (*)
public void drawRect() {
int intLength, intWidth;
// Use actual dimensions if between 10-50, otherwise use 10x10
if (length >= 10 && length <= 50 && width >= 10 && width <= 50) {
intLength = (int) length;
intWidth = (int) width;
} else {
intLength = 10;
intWidth = 10;
}
// Draw the rectangle
for (int i = 0; i < intWidth; i++) {
for (int j = 0; j < intLength; j++) {
[Link]("* ");
}
[Link]();
}
}
// Additional getter methods for testing purposes
public double getLength() {
return length;
}
public double getWidth() {
return width;
}
}
EXECUTION RESULTS (TEXT OR SNAPSHOTS)
DISCUSSION AND CONCLUSION
The Rectangle class effectively implements encapsulation with proper validation. The area
calculation and drawing methods correctly handle boundary conditions, demonstrating robust error
handling and conditional logic in object-oriented design.
3. Write a program. In which,
Define a class called Vehicle, with
Properties:
- speed, size, brand, and so on (whatever you think is needed);
Methods:
- Constructor method – initiate the variables with given value
(from parameters)
- move() – print a string with current speed, eg. “The vehicle is
running with speed xxx”,
- setSpeed(int speed) – reset the speed to specific value,
- speedup() – increase the speed with 5,
- speedDown() – decrease the speed with 5,
- getSpeed() – return the speed,
- The main method – by instantiating an object of a vehicle, use
the Constructor methods to initiate the value of speed, size
and brand (and the others if necessary). And print the speed
of the vehicle object. Use the methods to reset and change
the speed, and then print the information.
SOURCE CODE (TEXT)
public class Vehicle {
private int speed;
private String size;
private String brand;
// Constructor method
public Vehicle(int speed, String size, String brand) {
[Link] = speed;
[Link] = size;
[Link] = brand;
}
// move() method
public void move() {
[Link]("The vehicle is running with speed " + speed);
}
// setSpeed method
public void setSpeed(int speed) {
[Link] = speed;
}
// speedup method
public void speedup() {
[Link] += 5;
[Link]("Speed increased to: " + speed);
}
// speedDown method
public void speedDown() {
[Link] -= 5;
[Link]("Speed decreased to: " + speed);
}
// getSpeed method
public int getSpeed() {
return speed;
}
// Main method
public static void main(String[] args) {
// Instantiate a vehicle object
Vehicle myCar = new Vehicle(60, "Medium", "Toyota");
// Print initial speed
[Link]("Initial speed: " + [Link]());
// Use move method
[Link]();
// Reset speed
[Link](70);
[Link]("After reset - Speed: " + [Link]());
// Speed up twice
[Link]();
[Link]();
// Speed down once
[Link]();
// Final information
[Link]("Final speed: " + [Link]());
[Link]();
}
}
EXECUTION RESULTS (TEXT OR SNAPSHOTS)
DISCUSSION AND CONCLUSION
This exercise successfully demonstrates core OOP principles - encapsulation with private fields and
public methods. The Vehicle class models real-world behavior with speed management, showing how
objects maintain state and provide controlled access through methods.
4. On some phone keypads, the alphabets are mapped to digits as
follows: ABC(2), DEF(3), GHI(4), JKL(5), MNO(6), PQRS(7), TUV(8),
WXYZ(9). Write a program called PhoneKeyPad, which prompts user
to input a string (case insensitive), and converts to a sequence of
digits (numbers).
Hints: You can use [Link]().toLowerCase() to read a string
and convert all characters to lowercase (where input is an object of
the Scanner class) to reduce your cases (in switch-case
statements); charAt(index) is a method from String class that you
can invoke with an string object to get the character from certain
index, e.g.
String str = “hello”; //index starts from 0, ends at
[Link]()
char ch = [Link](1); //character ‘e’ stores in
variable ch
SOURCE CODE (TEXT)
import [Link];
public class PhoneKeyPad {
public static void main(String[] args) {
Scanner input = new Scanner([Link]);
[Link]("Enter a string: ");
String str = [Link]().toLowerCase();
[Link]("Digit sequence: ");
for (int i = 0; i < [Link](); i++) {
char ch = [Link](i);
switch (ch) {
case 'a': case 'b': case 'c':
[Link](2);
break;
case 'd': case 'e': case 'f':
[Link](3);
break;
case 'g': case 'h': case 'i':
[Link](4);
break;
case 'j': case 'k': case 'l':
[Link](5);
break;
case 'm': case 'n': case 'o':
[Link](6);
break;
case 'p': case 'q': case 'r': case 's':
[Link](7);
break;
case 't': case 'u': case 'v':
[Link](8);
break;
case 'w': case 'x': case 'y': case 'z':
[Link](9);
break;
default:
[Link](ch); // Keep non-alphabet characters as is
}
}
[Link]();
}
}
EXECUTION RESULTS (TEXT OR SNAPSHOTS)
DISCUSSION AND CONCLUSION
The program efficiently converts text to phone keypad digits using switch-case logic. The case-
insensitive approach and character-by-character processing demonstrate effective string
manipulation and mapping algorithms in practical applications.
5. (Algebra: quadratic equations) Design a class named QuadraticEquation for
a quadratic equation ax2 + bx + c = 0. The class contains:
■ Private data fields a, b, and c that represent three coefficients.
■ A constructor for the arguments for a, b, and c.
■ Three getter methods for a, b, and c.
■ A method named getDiscriminant() that returns the discriminant, which is
b2 - 4ac.
■ The methods named getRoot1() and getRoot2() for returning two roots of
the equation
These methods are useful only if the discriminant is nonnegative. Let these
methods return 0 if the discriminant is negative.
Draw the UML diagram for the class and then implement the class. Write a
test
program that prompts the user to enter values for a, b, and c and displays the
result based on the discriminant. If the discriminant is positive, display the two
roots. If the discriminant is 0, display the one root. Otherwise, display “The
equation has no roots.”
SOURCE CODE (TEXT)
import [Link];
public class TestQuadraticEquation {
public static void main(String[] args) {
Scanner input = new Scanner([Link]);
[Link]("Enter a, b, c: ");
double a = [Link]();
double b = [Link]();
double c = [Link]();
QuadraticEquation equation = new QuadraticEquation(a, b, c);
double discriminant = [Link]();
[Link]("Discriminant: " + discriminant);
if (discriminant > 0) {
[Link]("The equation has two roots:");
[Link]("Root 1: " + equation.getRoot1());
[Link]("Root 2: " + equation.getRoot2());
} else if (discriminant == 0) {
[Link]("The equation has one root:");
[Link]("Root: " + equation.getRoot1());
} else {
[Link]("The equation has no real roots.");
}
[Link]();
}
}
EXECUTION RESULTS (TEXT OR SNAPSHOTS)
DISCUSSION AND CONCLUSION
The QuadraticEquation class provides a complete mathematical solution with proper discriminant
handling. It demonstrates mathematical computation in OOP, error handling for imaginary roots, and
clean separation between data storage and calculation logic.