Try It Yourself: parameter passing

  1. What gets printed when the method question1 is called?
      public static void question1() {
         int x = 84, y = 59;
    
         System.out.println("In main: x = " + x + "  y = " + y);
         swap(x, y);
         System.out.println("In main: x = " + x + "  y = " + y);
      }
    
      public static void swap(int x, int y) {
         System.out.println("In swap: x = " + x + "  y = " + y);
         int temp = x;
         x = y;
         y = temp;
         System.out.println("In swap: x = " + x + "  y = " + y);
      }
    


  2. Suppose the class Question2 is defined as follows:
    class Question2 {
       private double x;
       private double y;
       private double z;
    
       public Question2(double x, double y) {
          this.x = x;
          this.y = y;
          this.z = 14.6;
          System.out.println("x = " + x + "  y = " + y + "  z = " + z);
       }
    
       public double method1(double x) {
          x = x + y;
          y = 4 * x;
          System.out.println("x = " + x + "  y = " + y + "  z = " + z);
          return x;
       }
    
       public void method2() {
          double z;
          z = method1(y);
          System.out.println("x = " + x + "  y = " + y + "  z = " + z);
       }
    
       public void method3() {
          System.out.println("x = " + x + "  y = " + y + "  z = " + z);
       }
    }
    
    What is the output for the following lines of code?
    Question2 q = new Question2(3.0, 7.0);
    q.method3();
    q.method2();
    q.method3();
    


  3. Suppose the class Question3 is defined as follows:
    class Question3 {
       private int[] arr;
       private int count;
       private String s;
    
       public Question3(int size, String name) {
          arr = new int[size];
          for (int i = 0; i < arr.length; i++) 
             arr[i] = 2 * i;
          count = size - 3;
          s = name;
       }
    
       public void method1(String s) {
          s = "hi";
          arr[s.length()] = 5;
       }
    
       public void method2(int count, int[] a) {
          for (int i = 0; i < a.length; i += 2)
             a[i] = 10;
          arr[count] = arr[s.length()];
       }
    
       public void print() {
          System.out.println("s = " + s);
          System.out.println("count = " + count);
          System.out.print("arr = ");
          for (int i = 0; i < arr.length; i++)
             System.out.print(arr[i] + " ");
          System.out.println();
       }
    }
    
    What is the output for the following lines of code?
    Question3 q = new Question3(5, "name");
    int[] arr = {1, 1, 2, 3, 5}; 
    q.print();
    q.method1("bye");
    q.print();
    q.method2(1, arr);
    q.print();
    System.out.print("arr = ");
    for (int i = 0; i < arr.length; i++) 
       System.out.print(arr[i] + " ");
    System.out.println();