Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
CSCI 1302 Guided Notes: Chapter 9 – Object Referencing Dr. Phelps Passing Objects As Arguments to Methods (Section 9.2) 5. Examine the program that passes a primitive value, num to a method. What happens if you change the value of the num in the method? public static void main (String [] args) { int num = 5; System.out.println( num); // Display the num’s value. changeInteger(num); // Pass the number to the changeInteger method. System.out.println( num); // Display the object's contents again. } public static void changeInteger(int x) { x = 0; } 6. Examine the program that creates an instance of the Rectangle class and then passes a reference to that object as an argument to a method. What happens if you change the value of the rectangle in the method? public static void main(String[] args) { Rectangle box = new Rectangle(12, 5); // Display the object's contents. System.out.println( box.getHeight()+ " X " + box.getWidth()); // Pass a reference to the object to the changeRectangle method. changeRectangle(box); // Display the object's contents again. System.out.println( box.getHeight()+ " X " + box.getWidth()); } public static void changeRectangle(Rectangle r) { r.setHeight(0); r.setWidth(0); } Writing an equals method: (9.5) 7. Examine the program that compares two integers and two rectangles. What is the output? { public class Compare public static void main(String []args) { int num1; int num2; Scanner keyboard = new Scanner(System.in); System.out.print("Enter a number: "); num1 = keyboard.nextInt(); System.out.print("Enter another number: "); num2 = keyboard.nextInt(); Rectangle rectA = new Rectangle(num1, num2); Rectangle rectB = new Rectangle(num1, num2); if (num1 == num2) System.out.println("The numbers are equal"); else System.out.println("The numbers are NOT equal"); if (rectA == rectB) System.out.println("The rectangles are equal"); else System.out.println("The rectangles are NOT equal"); } 1302GuideC9ObjectReferencing Page 1 of 2 CSCI 1302 Guided Notes: Chapter 9 – Object Referencing Dr. Phelps 8. Write an equals method in the Rectangle class that could be used to compare two rectangle objects and returns true if the corresponding instance fields are the same. Write a call statement to compare two rectangles using the equals method. 9. Even if you do not write an equals method for a class, Java provides one. Describe the behavior of the equals method that java automatically provides. The toString Method (9.4) 10. Define a toString method in the Rectangle class that will return a String with the height and width of a rectangle formatted as: 2 X 4. Write a corresponding call statement using the toString method. 1302GuideC9ObjectReferencing Page 2 of 2