Lab #1: Getting Started with Java — the Rectangle Class
Objectives
- Get comfortable with the JDK toolchain (
javac,java) and the standard API documentation. - Write your first non-trivial class from scratch: fields, a parameterized constructor, methods,
toString(). - Practice
statichelper methods and keyboard input viaScanner. - Work with arrays of objects and command-line arguments.
1. Finding your way around the JDK
Difficulty: EasyBefore writing any code, get familiar with the tools you’ll use all semester:
- Locate the JDK’s API documentation on your system (or online, for the version you’re using) and bookmark it — you’ll be back here constantly. Learn to navigate it: an alphabetical class index, and a package-by-package tree. Look up a few classes mentioned in the lectures —
Object,String,Scanner— and get a feel for how a class’s documentation is laid out (constructors, method summary, method detail). - Write a tiny program that reads a line of text from standard input and prints it back out (an “echo” program, using
Scannerwrapped aroundSystem.in). Compile it withjavacand run it withjava. This confirms your toolchain works end to end before you write anything bigger.
2. The Rectangle class
Work in a dedicated rectangles directory for this section. (A note before you start: don’t import java.awt.* here — java.awt already has its own Rectangle class, and importing it would silently shadow the one you’re about to write, or clash with it outright if you ever need both. Nothing in this section needs an AWT import.)
2.1 A first version
Difficulty: EasyWrite a Rectangle class (in Rectangle.java) representing a rectangle by two corner points — a top-left origin and a bottom-right corner. Use Point2D.Double from java.awt.geom for the points (check its constructor and accessors in the documentation rather than guessing).
Give Rectangle:
- a constructor taking the four coordinates of the two corners,
- methods
width(),height(),area(), andperimeter().
Then write a small TestRectangle class with a main method that builds a rectangle with fixed coordinates (e.g. new Rectangle(10.0, 10.0, 40.0, 50.0)) and prints its width, height, area, and perimeter.
2.2 toString()
Difficulty: Easy
Add a toString() method to Rectangle that returns a string of the form (origin, corner), where origin and corner are formatted using their own toString() (check what Point2D.Double gives you by default — don’t try to reformat it yourself). Update TestRectangle to print the rectangle directly (System.out.println(r)) and confirm toString() is picked up automatically.
2.3 A static factory method + keyboard input
Difficulty: Easy
Recall that keyboard input goes through System.in, wrapped by a Scanner.
Add a method createRectangle() to TestRectangle that prompts the user for the four coordinates, builds the corresponding Rectangle, and returns it. Since this method is called from main (which is static), it must be static too:
public class TestRectangle {
static Rectangle createRectangle() {
// read the four coordinates from the user, build and return a Rectangle
}
public static void main(String[] args) {
Rectangle r = createRectangle();
System.out.println(r);
}
}
2.4 An array of rectangles
Difficulty: EasyExtend TestRectangle:
- In
main, ask the user how many rectangles to create, allocate an array of that size, and fill it by callingcreateRectangle()in a loop. - Print the resulting array (via each element’s
toString()). - Add
static Rectangle largest(Rectangle[] rectangles), returning the rectangle with the greatest area in the array. Test it frommain.
2.5 Command-line arguments instead
Difficulty: RxInstead of asking for the number of rectangles interactively, pass it as a command-line argument to main.
Command-line arguments always arrive as Strings, even when they represent a number — so "3" needs to become the int value 3 before you can use it as an array size. Java’s primitive wrapper classes (Integer, Double, …) provide static parsing methods for exactly this: Integer.parseInt(String s) returns the int value that s represents.
3. Optional: displaying a rectangle graphically
Difficulty: HardThis section is optional, and previews ideas the course returns to properly in the GUI lecture — treat it as a taste of what’s coming, not something to master now.
In your rectangles directory, write a small Swing program (a JFrame containing a custom JPanel) whose panel overrides paintComponent(Graphics g) to draw a Rectangle instance.
To do this:
- Check the
drawRect(x, y, width, height)method ofjava.awt.Graphicsin the documentation. - Add a method
display(Graphics g)toRectanglethat draws itself viadrawRecton theGraphicsobject it’s given. Note thatgis handed toRectanglefrom the outside — in this exercise it comes from a Swing panel, but it could just as well come from any other graphical environment that hands out aGraphicsobject. This is what makesRectanglereusable: it doesn’t know or care who’s asking it to draw itself. - Once it works, take a moment to identify the objects involved and how they interact: who creates the
Rectangle? Who callsdisplay? Who owns theGraphicsobject, and how did it end up inRectangle’s hands?