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];
    

     

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

     

  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]++;
    

     

  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);
    

     

  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?

     

  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);
       }
    }

     

  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;
    A[0] == B[0];
    A[1] == B[1];
    A[2] == B[2];
    

     

  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.