JAVA EXERCISES READING ------- Notes for lectures 21 and 22. EXERCISES --------- 1. What is the primary difference between Java classes and C structures? 2. Describe the following code: class Interval { private double a, b; Interval(double aval, double bval) { a = aval; b = bval; if (a > b) { b = aval; a = bval; } } double length() { return b - a; } } 3. Give an expression using the class in exercise 2 that creates an Interval representing [1.0, 2.5] and whose value is the length of the interval. 4. Using the class in exercise 2, write a java class Rect for axis-oriented rectangles in the plane, with a method that computes the area of rectangles. 5. Using the class in exercise 4, give an expression that creates an Rect representing the rectangle with lower left corner (1.0, 2.0) and upper right corner is at (2.5, 4.0), whose value is the area of the rectangle. 6. What is the primary reason to make a method "private" in Java? 7. What is the primary reason to make a method "public" in Java? 8. In Java, suppose that a linked list is made up of nodes of type class Node { public int key; public Node next; Node(int t) { key = t; next = null; } } that you are given a Node "list" which refers to the first node of the list; that the last node has a null link; and that there are at least two nodes on the list. Write a code fragment to delete the second node of the list. 9. Under the same conditions as the previous question, write a code fragment to add a new node with key 5 just after the second node of the list. . . . ANSWERS TO JAVA EXERCISES 1. Java classes provide language support for us to associate functions (methods) with our data; C structures do not. 2. A java class for intervals on the line, with a method that computes the length of intervals. 3. new Interval(1.0, 2.5).length() In this usage, we create the object only to get at the length method. If we have other uses for the interval, we might declare and name a variable, e.g. Interval t = new Interval(1.0, 2.5); Then we could use "t.length()" in expressions. 4. class Rect { private Interval x, y; Rect(Interval xval, Interval yval) { x = xval; y = yval; } double area() { return x.length() * y.length(); } } 5. new Rect(new Interval(1.0, 2.5), new Interval(2.0, 4.0)).area() 6. To hide it from clients. Otherwise, we would not be free to change the implementation because clients might use it. 7. To define it as a part of the class that is for use by clients. 8. list.next = list.next.next; 9. Node t = new Node(5); t.next = list.next.next; list.next.next = t;