JAVA 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.