Self-Review Questions

  1. Which of the following statements is a valid array declaration?
    int[] a = new int(30);
    char[] b = new char[0];
    int[] c = new int[][3];
    int[][] d = new int[5][];
    

     

  2. What is the value of a[1]?
    int[] a = new int[5];
    

    0

  3. What is the value of b[0]?
    int [] a = {1,2,3};
    int [] b = (int[])a.clone();
    if (a == b) b[0]++;
    

    1

  4. What is the value of b[0]?
    int [] a = {1,2,3};
    int [] b = (int[])a.clone();
    if (Arrays.equals(a,b)) b[0]++;
    

    2

  5. What is the value of twin[1]?
    Object[] obj = {new Integer(10), new String("CMU"), new Double(1.23)};
    Object[] twin = (Object[]) obj.clone();
    obj[1] = new Integer(15);
    

    "CMU"

  6. Consider the following code fragment
    int[] a = {1,2,3,4,5};
    foobar(a);
    System.out.println( Arrays.toString(a) );
    
    What will this code print? Does it depend on actual implementation of the foobar() method?

    This code prints the array a after the function foobar is applied to it. It does depend on the actual implementation of foobar().

  7. What is the output of this code segment?
    public class Demo
    {
       public static void main(String[] args)
       {
          int[] A = {5, 2, 4, 1, 3};
          action(A);
          System.out.println(Arrays.toString(A));
       }
       public static void action(int[] X)
       {
          Arrays.sort(X);
       }
    }

    [1, 2, 3, 4, 5]

  8. Given:
    Object[] A = {new Integer(3), new StringBuffer("circle"),  new ArrayList()};
    Object[] B = new Object[3];
    System.arraycopy(A, 0, B, 0, A.length);
    ((StringBuffer) A[1]).append("s");
    ((ArrayList) A[2]).add("CMU");
    
    What are the results of the following comparisons?
    B == A;
    	false: different objects
    A[0] == B[0];
    	true: same object
    A[1] == B[1];
    	true: same object
    A[2] == B[2];
    	true: same object
    

     

  9. Birthday Paradox. Write a method that computes the number of people (by simulation) that must enter a room until two of them share a birthday. Assume that there are 365 possible birthdays, and that birthdays are uniformly distributed throughout the year.

    public int birthdayParadox(){
        Random rand = new Random();
        boolean[] bool = new boolean[356];
        int count = 0;
        while(true){
        	int random = rand.nextInt(356);
            count++;
            if(bool[random])break;
            else
    	    bool[random] = true;
        }
    	return count;
    }