Exercise Overview
How to Use These Exercises
These exercises are designed to reinforce your understanding of Java object-oriented programming including classes, objects, methods, constructors, and encapsulation. Start with the easy exercises and progress to more challenging ones as you build confidence.
Tips for Success:
- Understand the relationship between classes and objects
- Practice proper encapsulation with access modifiers
- Learn to create and use constructors effectively
- Master method overloading and object interaction
- Follow object-oriented design principles
Easy Exercises - Start Here!
Create a Simple Class
EasyCreate a basic class with attributes and methods.
Requirements:
- Create a class called
Student
- Add attributes: name, age, studentId
- Create a constructor to initialize these attributes
- Add getter and setter methods
- Create a method to display student information
- Test the class by creating student objects
Expected Output:
Student Information:
Name: John Doe
Age: 20
Student ID: S001
Student Information:
Name: Jane Smith
Age: 19
Student ID: S002
Hints:
- Use
private
for attributes (encapsulation) - Use
public
for getter and setter methods - Use
this
keyword to refer to instance variables - Create a
displayInfo()
method for output - Test with multiple student objects
Constructor Overloading
EasyPractice creating multiple constructors for the same class.
Requirements:
- Add a default constructor to the Student class
- Add a constructor that only takes name and age
- Add a constructor that only takes name
- Demonstrate how each constructor works
- Show the difference in initialization
Expected Output:
Default Student:
Name: Unknown
Age: 0
Student ID: N/A
Name-only Student:
Name: Alice
Age: 0
Student ID: TBD
Name and Age Student:
Name: Bob
Age: 22
Student ID: TBD
Hints:
- Use
this()
to call other constructors - Default constructor should set default values
- Use meaningful default values like "Unknown" and "N/A"
- Test each constructor with different parameters
- Show how constructors provide flexibility
Basic Encapsulation
EasyPractice proper encapsulation using access modifiers.
Requirements:
- Make all attributes private
- Create public getter methods
- Create public setter methods with basic validation
- Add a private helper method for validation
- Test validation with invalid values
Expected Output:
Setting valid age: 20
Student age: 20
Setting invalid age: -5
Age validation failed. Age not updated.
Student age: 20
Setting valid age: 25
Student age: 25
Hints:
- Use
private
for attributes and helper methods - Use
public
for getters and setters - Validate age range (e.g., 0-120)
- Use
isValidAge()
as a private helper method - Provide feedback when validation fails
Medium Exercises - Build Your Skills!
Method Overloading
MediumPractice creating multiple methods with the same name but different parameters.
Requirements:
- Create a method
study()
with no parameters - Create a method
study(String subject)
with subject parameter - Create a method
study(String subject, int hours)
with both parameters - Demonstrate method overloading
- Show how Java chooses the correct method
Expected Output:
John is studying
John is studying Java
John is studying Mathematics for 3 hours
Method overloading demonstration complete!
Hints:
- Method overloading requires different parameter lists
- Return type alone doesn't distinguish overloaded methods
- Use descriptive messages for each version
- Test all three versions of the study method
- Show how Java automatically selects the right method
Static Methods and Variables
MediumPractice using static methods and variables in classes.
Requirements:
- Add a static variable to track total number of students
- Create a static method to get total student count
- Create a static method to reset student count
- Update constructors to increment student count
- Demonstrate static vs instance methods
Expected Output:
Total students: 0
Creating student 1...
Total students: 1
Creating student 2...
Total students: 2
Creating student 3...
Total students: 3
Resetting count...
Total students: 0
Hints:
- Use
static
keyword for class-level variables - Static methods can be called without creating objects
- Use
Student.getTotalCount()
to access static method - Increment count in constructors
- Static methods can't access instance variables directly
Object Arrays and Collections
MediumWork with arrays and collections of objects.
Requirements:
- Create an array of Student objects
- Create methods to add, remove, and find students
- Create a method to display all students
- Create a method to find students by name
- Demonstrate array operations with objects
Expected Output:
All Students:
1. John Doe (ID: S001)
2. Jane Smith (ID: S002)
3. Bob Johnson (ID: S003)
Searching for "Jane Smith"...
Found: Jane Smith (ID: S002)
Searching for "Alice"...
Student not found.
Hints:
- Use
Student[] students = new Student[10];
- Keep track of current number of students
- Use
equals()
method for string comparison - Handle cases when student is not found
- Use loops to iterate through student array
Hard Exercises - Master the Concepts!
Object Interaction and Relationships
HardCreate multiple classes that interact with each other.
Requirements:
- Create a
Course
class with name, credits, and instructor - Create a
Teacher
class with name and subject - Modify Student class to enroll in courses
- Implement course enrollment and withdrawal
- Demonstrate object relationships and interactions
Expected Output:
Course: Java Programming (3 credits)
Instructor: Dr. Smith
Student: John Doe
Enrolled Courses:
1. Java Programming (3 credits) - Dr. Smith
2. Mathematics (4 credits) - Dr. Johnson
Total Credits: 7
Withdrawing from Mathematics...
Enrolled Courses:
1. Java Programming (3 credits) - Dr. Smith
Total Credits: 3
Hints:
- Use arrays or ArrayLists to store enrolled courses
- Create methods like
enrollCourse()
andwithdrawCourse()
- Use object references to establish relationships
- Calculate total credits from enrolled courses
- Handle duplicate enrollments and invalid withdrawals
Advanced Encapsulation and Validation
HardImplement advanced encapsulation with comprehensive validation.
Requirements:
- Implement comprehensive validation for all attributes
- Create custom exception classes for validation errors
- Add logging for validation failures
- Implement data persistence simulation
- Create a complete student management system
Expected Output:
Creating student with invalid data...
Validation Error: Age must be between 0 and 120
Log: Validation failed for age: -5
Creating student with valid data...
Student created successfully: John Doe (ID: S001)
Saving student data...
Data saved to file: student_data.txt
Loading student data...
Student loaded: John Doe (ID: S001)
Hints:
- Create custom exceptions like
InvalidAgeException
- Use
throw
andthrows
keywords - Implement comprehensive validation rules
- Use try-catch blocks to handle exceptions
- Simulate file operations with print statements