// Jeremy Lipschutz // Short program highlighting how object variables // use reference semantics public class ReferenceSemantics { public static void main(String[] args) { Point p1 = new Point(1,2); Point p2 = p1; Point p3 = new Point(p1.x, p1.y); System.out.println(p1); System.out.println(p2); System.out.println(p3); // Note here that because p1 and p2 both "refer" to the same object, // we see that both of them have the same x and y fields, 25 and 67. p1.x = 25; p2.y = 67; p3.x = 20; System.out.println(p1); System.out.println(p2); System.out.println(p3); // creates an array with null elements Point[] points = new Point[5]; for(int i = 0; i < points.length; i++) { points[i] = new Point(i * 2, i * 2 + 1); } /* // This is the standard way of looping through the array and printing out all // the values for(int i = 0; i < points.length; i++) { System.out.println(points[i]); } */ // Here we are using the "for-each" loop. Each iteration of the loop, // The variable "p" will be set to a different Point in the data structure // "points" you are looping over. You cannot decide the order in which the // points are visited, but it is quite nice when you just want to print all of // them! for(Point p : points) { System.out.println(p); } } }