Sample Exam 2 questions


Sample true/false questions

  1. The following code fragment (inside main) results in a compiler error:
         for (int i=6; i>0; i++) {
          System.out.println (i);
      }
        
  2. It is possible to have method main call method foo, which then calls method bar.
  3. A method declared to return an int type does not have to return anything, but a void method cannot return an int.

Sample multiple-choice questions

  1. The code below
    public class Test {
        public static void main (String[] argv) 
        {
            int i = 5;
            int[] A = {6};
            change (i);
            System.out.println (i);
            change (A[0]);
            System.out.println (A[0]);
        }
    
        static void change (int i) 
        {
            i = i + 1;
        }
    }
    
    prints
    1. 5, 7
    2. 5, 6
    3. 6, 7
    4. 6, 6
  2. For the array A with elements {1,4,9,16,25} the code fragment
       for (int i=1; i<A.length; i++) {
          A[i] = A[i-1];
       }
       System.out.println (Arrays.toString(A));
    
    results in:
    1. {1,1,1,1,1}
    2. {1,1,4,9,16}
    3. {25,1,4,9,16}
    4. An array-out-of-bounds exception
  3. Consider the program below
    public class Test {
        public static void main (String[] argv)
        {
    	char[] letters = {'b','a','d','c','a','f','e'};
    	String s = strangeMethod (letters);
    	System.out.println (s);
        }
    
        static String strangeMethod (char[] A)
        {
    	int base = (int) 'a';
    	String s = "";
    	for (int i=0; i<A.length; i++) {
    	    int k = (int) A[i];
    	    if (k < base+2) {
    		s = s + A[i];
    	    }
    	}
    	return s;
        }
    }
    
    This results in:
    1. badcafe
    2. efacdab
    3. baa
    4. dcfe

Sample programming problems

  1. Given an array of chars of even length like
        char[] letters = {'a','b','c','d','e','f'};
      
    write a method called mixHalves to return a string with all the odd-positioned letters together followed the even-positioned letters. Thus, for the above, with the call
        String s = maxHalves(letters);
        System.out.println (s);
      
    you should get bdface as the printed string.
  2. An int array is palindromic if it looks the same in reverse. Thus,
            int[] A = {1, 2, 3, 2, 1};
            int[] B = {1, 4, 9, 9, 4, 1};
            int[] C = {1, 4, 9, 6, 1};
            System.out.println (checkPalindrome(A));
            System.out.println (checkPalindrome(B));
            System.out.println (checkPalindrome(C));
      
    should print
        true
        true
        false
      
    Write the method checkPalindrome using only while-loops (i.e., without for-loops).