CSC 171 Exam 2

FALL 2001

 

Name : ___________________________________________

Student Number:____________________________________

 

Please indicate all answers using pen.

 31 questions – one hour

 Questions 1 – 20 are worth 2% each

 Questions 21-30 are worth 6% each

 Question 31 is a bonus/extra-credit question worth 5 points

Closed book

 

Meliora

 

 

1)       Given the following declaration, what is the correct way to get the size of the array, assuming the array has been initialized?

int[] array;

a)       array[].length()

b)       array.length()

c)       array[].length

d)       array.length  <<<

e)       array[].size()

f)        array.size()

 

2)       What will be the result of attempting to compile the following program?

 

public class MyClass {

      long var;

 

      public void MyClass(long param) {var = param;} //(1)

 

      public static void main(String args[]){

            MyClass a, b;

            a = new MyClass();         // (2)

            b = new MyClass(5);        // (3)

      }

}

     

Select the one right answer:

a)       A compilation error will be encountered at (1), since constructors should not specify a return value

b)       A compilation error will be encountered at (2), since the class does not have a default constructor

c)       A compilation error will be encountered at (3),since the class does not have a constructor accepting a single argument of type int.   <<<<< 

d)       The program will compile correctly.

 

 

3)       Write the Binary representation of 4510  __________1011012____________________

 

4)       What will be the result of attempting to compile and run the following class?

 

public class Passing {

     

public static void main(String args[]){

      int a = 0 ; int b = 0;

      int [] bArr = new int[1]; bArr[0] = b;

      inc1(a); inc2(bArr);

      System.out.println(“a=”+a+“ b=”+b+“bArr[0]=”+bArr[0]);

      }

     

public static void inc1(int x) {x++;}

public static void inc2(int[] x) {x[0]++;}

 

}

     

Select the one right answer:

a)       The code will fail to compile, since “x[0]++;” is not a legal statement.

b)       The code will compile and will display “a=1 b=1 bArr[0]=1” when run.

c)       The code will compile and will display “a=0 b=1 bArr[0]=1” when run.

d)       The code will compile and will display “a=0 b=0 bArr[0]=1” when run. <<<

e)       The code will compile and will display “a=0 b=0 bArr[0]=0” when run.

 

 

5)       If he class Alpha inherits from the class Beta, class Alpha is called the ____sub_______ class and class Beta is called the ____super______ class.

 

 

6)       Write the decimal representation of ABC16  __10*256+11*16+12 == 274810_________

 

7)       A _____constructor______ is a special method used to initialize the instance variables of a class.

 

8)       What will be the result of attempting to compile and run the following class?

 

class MyClass {

     

public static void main(String args[]){

      int size = 20;

      int [] arr = new int[size];

      for (int i = 0 ; i<size;i++)

        System.out.println(arr[i]);

      }

}

     

Select the one right answer:

a)       The code will fail to compile, because the in[] array declaration is incorrect.

b)       The program will compile, but will throw an IndexArrayOutOfBoundsException when run

c)       The program will compile and run without error , but will produce no output.

d)       The program will compile and run without error and will type the numbers 0 through 19

e)       The program will compile and run without error and will type 0 twenty times  <<<<

f)        The program will compile and run without error ane will type null twenty times

 

 

 

9)       A “has-a” relationship between classes represents __composition___ and an “is-a” relationship between classes represents ____inheritance____.

 

10)    Write the decimal representation of 1001012  _________32+4+1 == 3710______________

 

 

11)    Which of the following is not considered one of the key logical units of the computer

Select all valid answers

a)       Input unit

b)       Secondary storage unit

c)       Central processing unit

d)       Output unit

e)       Compiler unit <<<<<

f)        Arthimetic logic unit

g)       Memory unit

 

 

12)    Which of these statements concerning the charAt() method of the String class are true?

Select all valid answers

a)       The charAt() method takes a char value as an argument

b)       The charAt() method returns a Character object

c)       The expression (“abcdef”).charAt(3) is illegal

d)       The expression “abcdef”.charAt(3) evaluates to the character ‘d’.<<<<<

e)       The index of the first character is 1.

 

 

13)    Write the binary representation of 110010112+11001112 ______1001100102________

 

 

14)    Which of the following is not a primitive data type in Java?

a)       byte

b)       short

c)       int

d)       long

e)       float

f)        double

g)       array  <<<<

h)       char

i)         boolean

 

 

15)    Write the octal representation of 2810 ________________348_____________________

 

 

16)    Members of a class specified as ______private_____ are accessible only to members of the class.

 

 

17)    Write 1710 in base 5_________________325__________________________

 

 

18)    Polymorphism helps eliminate ____switch____ logic.

 

 

 

19)    The _____new_____ operator dynamically allocates memory for an object of a specified type.

 

 

20)    Which of these expressions will obtain the stubstring “kap” from a string defined by String str = “kakapo”?

a)       str.substring(2,2)

b)       str.substring(2,3)

c)       str.substring(2,4)

d)       str.substring(2,5)<<<

e)    str.substring(3,3)

 

 

21)    Create a method that takes an int as an argument and returns a String object representing the binary representation of the integer. Given the argument 42, it should return “101010”. Given the argument -42, it should return “-101010”.

 

public static String i2s(int x) {

      String sign = “”;

      String binary = “”;

      if (x < 0) {sign = “-“; x *= -1;}

 

      do {

            int low = x % 2;

            binary = low + binary;

            x /= 2;

      } while (x > 0);

 

      return sign + binary;

}

 

 

22)    Write a recursive method to reverse a string NOT using the JAVA library “reverse()” method. Instead, exploit the (recursive) fact that you can reverse a string by talking the first letter off the front and putting it on the end of the reverse of the rest of the string. Your method should take a string as input and return a string. You should use charAt, and substring, and  recursive call. Don’t use StringBuffers, just add a char to a string with “+”.

 

 

    public static String myreverse(String s) {

      if ((s == null) || (s.length() <= 1)) return s;

      else return myreverse(s.substring(1)) + s.charAt(0);

    }

 

 

23)    Write a Java Method that takes in a double representing a numerical grade and returns String indicating if the grade is “passing” or “failing”, over or under 60%.

 

public static String gradeConverter(double numGrade) {

      if(numGrade < 60) return “failing”; //using 0.6 is ok

else return “passing”;

}

 

 

24)    Write a Java Method that builds a triangular multiplication Table. The method takes in a positive integer representing the number of rows in the table and returns a triangular 2-D array of integers containing the appropriate products. Recall: a triangular array has on column in the first row, two columns in the second row, etc.

 

/

// two off if you did’nt fill in the products

public static int[][] arryBuild(int n) {

      int[][] rarry = new int[n][];

      for (int i=0;i<n;i++)       {

            rarry[i] = new int[i+1]

          for (int j=0;j<i+1;j++)

            rarry[i][j] = i * j ;

      }

      return rarry;

}

 

 

25)    Imagine that Java suddenly stopped supporting the “*” operator on ints. Write a java method “mymultiply” that takes two integers and returns the product. DO NOT USE the multiply operator anywhere in the method. (ie use addition/subtraction to implement multiplication). You may use a helper method, but no “*” is allowed in the helper method. The only allowable arithmetic operations are integer addition and subtraction. You may introduce any constants you need.

 

//2% off if you didn’t support negatives

public static int mymultiply(int o1, int o2) {

      int rval = 0, sign = 1;

      if ((o1 < 0) ^ (o2 < 0)) sign = -1;

if (o1 < 0) o1 = negate(o1);

if (o2 < 0) o2 = negate(o2);

 

      for (int i=0;i<o1;i++) rval += o2;

 

if (sign == -1) rval = negate(rval);

 

      return rval;

}

 

public static int negate (int x) {
      int rval = 0;

      rval -= x;

      return rval;

}

 

26)  The simplest kind of encryption is the shift cipher, also known as the Caesar cipher. In Caesar’s case, to encrypt each letter in a message would be moved forward by a number (referred to as the key). So, if the key were 2, ‘a’ would become ‘c’, ‘b’ would become ‘d’, etc. The cipher is said to wrap around from the end – ‘y’ goes to ‘a’, ‘z’ goes to ‘b’. Write a Java method that takes a string and a positive integer key as parameters and returns the string encrypted by the Caesar cipher. The method needs to work on the 26 letter (upper or lower case) . All other characters should remain unchanged. The encrypted message should be returned all upper case.

 

 

 

public static String caesar(String msg, int key) {

      String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

     

      int length = msg.length() ;

      String msg2 = msg.toUpperCase();

      String emsg = "";

 

      for (int i=0;i<length;i++) {

          int indx = alphabet.indexOf(msg2.charAt(i));

            if (indx == -1)

                  emsg += msg2.charAt(i);

            else

                  emsg += alphabet.charAt((indx + key)%length);

      }

 

      return emsg;

}    

 

27)    Declare an interface called Function that has a method named evaluate() that takes an arbitrary int value as a parameter and returns an int value.

 

interface Function { public int evaluate(int arg); }

 

28)    Create a class Half that implements Function. Make the implementation of the method evaluate() return the value obtained by dividing the int argument by 2.

 

class Half implements Function {

      public int evaluate(int arg) {

            return arg/2;

       }

}

 

29)    Create a method that takes an arbitrary array of int values as a parameter and returns an array that has the same length, but the value of an element in the new array is half that of the value in the corresponding element in the array passed as a parameter. Let the implementation of this method create and instance of Half, and use this instance to calculate the values in the array to be returned.

 

public static int[] applyFunctionToArray( int[] arrIn) {

      int length = arrIn.length ;

      int [] arrOut = new int[length];

 

      Function func = new Half();

 

      for (int i=0;i<length;i++)

            ArrOut[i] = func.evaluate(arrIn[i]);

 

      return arrOut;

}

 

30)  Rewrite the method that operated on arrays from the previous exercise: the method should now take a Function reference as an argument and use this instead of creating Half.

 

 

public static int[] applyFunctionToArray(int[] arrIn,

   Function func) {

      int length = arrIn.length ;

      int [] arrOut = new int[length];

 

      for (int i=0;i<length;i++)

            ArrOut[i] = func.evaluate(arrIn[i]);

 

      return arrOut;

}

 

 

31)    Decode the following secret message (2 off if you didn’t get the ‘G’)

BEWARE GHE IDES OF MARCH

DGYCTG IJG KFGU QH OCTEJ