Java Classes and OOP Practice Problems
Just reading class syntax does not show you when to use it. Work through these 24 problems in order: group data, add methods, and swap implementations behind an interface.
1. Grouping data together #1–6
Put values that travel together, like a name and a score, into one class.
For a group that only holds values, one line is enough: record Student(String name, int score) {} (since Java 16).
Keep several of them in a List<Student>, and sort by giving the order, as in Comparator.comparing(Student::score).
2. Classes and methods #7–14
Hide fields with private and let only methods change their values.
Set the starting state in the constructor.
Between objects, == asks whether they are the same object, so compare contents with equals (the same goes for strings).
3. enum #15–19
For a fixed handful of values, like days of the week or states, make an enum.
Typos are caught at compile time, and it works well with switch.
Use values() to get all of them, ordinal() to get the position number, and valueOf("MON") to get a value from its name.
4. Interfaces #20–24
An interface is a promise that "this method exists".
Even if each shape computes its area differently, you can hold any of them as a Shape and call area().
Put @Override on the methods you implement, and the compiler tells you when you get a name wrong.
Good to know
- On this site your program starts in
maininsidepublic class Main. Write other classes in the same file withoutpublic. - Read input with
ScannerorBufferedReader. If you callnextLine()afternextInt(), the leftover line break makes it read an empty line.
See also
- 100 Coding Challenges for Beginners — 100 problems
- 100 Python Practice Problems for Beginners — 100 problems
- Learn Java — lessons with explanations and examples
- Other problem sets