Class 4

Homework 3

Given this class definition of a Mid:

	public static class Mid {
		public int alpha;
		public String firstName;
		public String lastName;
		public int company;
	}

write a program entitled HW3.java with the following attributes:

An example run:

	taylor@albert:~/ic211/HW03/solution$ java HW3
	How many mids? 3
	Alpha? 150006
	First name? George
	Last name? Finklehoffer
	Company? 3
	Alpha? 150012
	First name? John
	Last name? Jingleheimer-Smith
	Company? 4
	Alpha? 150018
	First name? Sterling
	Last name? Hotchkiss
	Company? 3
	What company would you like to print out? 3
	150006 Finklehoffer George 3
	150018 Hotchkiss Sterling 3

Again, your program will be graded by automated script, so your input and output should be exactly as it is above.

Objects in Java: Grouping Data

In the end of IC210, we learned a little bit about structs, classes, and objects. The primary reason we gave for classes and objects is for grouping data together; for instance, a point in 2D space is one concept, even if it is actually made of of two doubles. Classes and objects let us handle this intuitively and easily. Additionally:

  1. Maybe you want a function that returns multiple pieces of data, and you would rather not have to use pass by reference to get that information out.
  2. Maybe you want to work with information the describes the same thing (such as a midshipman) but the data is heterogeneous (such as a String for the name, and int for the alpha code, and a double for the QPR).
  3. Maybe you need to move these chunks around as units, such as nodes in linked lists.

Obviously, there's more to objects than just this, as we're spending a whole semester on them, but that is the basic idea. In C++, we might define a struct like this:

      struct point
      {
        double x,y;
      };
    

and write a function that uses it like this:

      point midPoint(point left, point right)
      {
        point middle;
        middle.x = (left.x + right.x)/2;
        middle.y = (left.y + right.y)/2;
        return middle;
      }
    

and use it like this:

      int main()
      {
        point myPoint1, myPoint2;
        cout << "Enter point 1: ";
        cin >> myPoint1.x >> myPoint1.y;
	cout << "Enter point 2: ";
        cin >> myPoint2.x >> myPoint2.y;
        point r = midPoint(myPoint1,myPoint2);
        cout << "MidPoint is (" << r.x
          << ',' << r.y << ")" << endl;
        return 0;
      }
    

Note how creating the struct created a new type that can be used like any of the built-in types. You can create variables of that type and assign them values like any type.

Java doesn't use the keyword "struct," so instead we'll be talking about "classes." The idea is the same. Of course, there are a couple things different between Java and C++:

  1. Java defines these with the class keyword. This is a good point to talk about the terminology. These struct-like things are defined in classes. When you have a particular instance of this class (i.e. a chunk of memory for a variable, that is called an object. This distinction will make more sense when you know a little more, but for now, just remember: the class is the definition, the object is the variable, or chunk of allocated memory.
  2. A class is usually defined in a new file that defines just that class. This allows for many different programs to access it. (This maximizes Reusability) A class can also be nested in another class. You will need to nest class Mid inside public static class HW3 to complete the homework with only one file.
  3. We may need to add the word public before variables.
  4. There is no ; at the end of the class definition.
  5. You cannot just create a variable of the type of the class, like we did for point above. You must create a pointer to the object, and then create the object with the new keyword.
  6. Pointers in Java are handled differently than in C. Whenever you create a variable that points to a class object, it is automatically a pointer and you do not need to use the * to access it. You can treat it as a regular variable. Java actually uses lots of pointers, but hides the implementation details. Its goal is to make programming easy and fast. By comparison, dealing with pointers in C is slow and error-prone.

So what does our point look like in java? In a new file named Point.java (remember, we always capitalize classes)

	class Point {
	  public double x,y;
	}
      

in the file main:

	import Point;
	public static Point midPoint(Point left, Point right){
          Point middle = new Point();
          //even though a pointer, no *
          middle.x = (left.x + right.x)/2;  
          middle.y = (left.y + right.y)/2;
          return middle;
	}
      

and also in main:

	public static void main(String [] args){
	  Point myPoint1 = new Point();
	  Point myPoint2 = new Point();
	  Scanner in = new Scanner(System.in); //don't forget the import!
	  System.out.print("Enter Point 1: ");
	  myPoint1.x = in.nextDouble();
	  myPoint1.y = in.nextDouble();
	  System.out.print("Enter Point 2: ");
	  myPoint2.x = in.nextDouble();
	  myPoint2.y = in.nextDouble();
	  Point r;
	  r = midPoint(myPoint1,myPoint2); // why no new for r??
	  System.out.println("MidPoint is (" + r.x + "," + r.y + ")");
	}
      

One thing to recognize regarding the "there are no pointers, but actually, there are lots of pointers" is, if you remember in C++, when you passed a pointer to an object to a function, any changes to the object were reflected as if the object has been passed by reference. Java is the same way. So, we can think of objects being passed to functions as being passed by reference.

	public static void movePoint(Point p, double factor) {
	  p.x = p.x * factor;
	  p.y = p.y * factor;
	  return;  //no value needed, modification of point worked.
	}
      

Another subtlety is that assignment of objects is never a copy, but just a pointer change:

	int i = 3;
	int j = i;  //3 is copied into j
	j = 4;  //i still 3

	Point p = new Point();
	p.x = 3;
	Point q = p;  //q points to p
	q.x = 4; //p.x changed to 4, as well!!
      

Finally, although objects can be passed by reference, their pointers cannot (without some trickery anyway).

	public static void swap(Point p, Point q) {
	  //DOES NOT WORK!!
	  Point tmp = p;
	  p = q;
	  q = p;
	  return;  //FAIL!
	}
      

How's that work (or rather not work)? Assume the function was called like this:

	Point r = new Point();
	Point s = new Point();
	swap(r,s);
      

Inside swap(), p and q are copies of the original pointers, so p points to the same thing r does, and q points to the same thing p does. Changing p.x would also change the Point that r points to, but changing p itself just moves that pointer, and doesn't change r.

Problems

  1. Build a simple linked list of chars, with an addToEnd(char c) function, a printList() function, and a find(char c) function.