PIC20A Final Exam

Instructions

  1. The exam consists of 17 pages(including this page). You are responsible for checking the number of pages
  2. Please read and answer all the questions carefully. The point value for each question in indicated. The total number of points available is 100. If you have trouble with a question, leave it and try another.
  3. Unless otherwise stated, you may assume when code is given that the code compiles and is correct. When you are asked to write code, you are expected to write code in good style and with proper indentation.
  4. Good luck!




Last Name:_________________ First Name:________________
Student ID:_________________






Question MC Short Q1 Short Q2 Short Q3Long Q1 Long Q2Long Q3 Total
Score

























Multiple Choices (2pts each, 24pts total)
Circle the correct answer
1. Consider a String that is constructed by calling
String s = new String("PIC20A is great");
Which of the calls listed here modify the string?
A) s.toUpperCase();
B) s.substring(2);
C) s.indexOf('P');
D) None of the above.

2. What happens when you attempt to compile and execute the following code?
1. class A {
2.   public static void main(String[] args) {
3.     Integer i = new Integer(5);
4.     i.setIntValue(i.intValue()+1);
5.     System.out.println("i = " + i);
6.   }
7. }
A) Compiler error.
B) The code prints out "i=5".
C) The code prints out "i=6".

3. What is the result of attempting to compile and execute the following application?
 1.  public class X {
 2.    int[] intarr;
 3.
 4.    public static void main(String[] args) { new X(); }
 5.
 6.    X() {
 7.      int s = 100;
 8.      intarr = new int[s];
 9.      System.out.println("value = " + intarr[s-1]);
10.      System.out.println("value = " + intarr[s]);
11.    }
12.  }
A) Compiler error on line 8.
B) Compiler error on line 9.
C) Compiler error on line 10.
D) The code compiles, but throws an exception at line 9.
E) The code compiles, but throws an exception at line 10.
F) The code compiles and executes with no exceptions.

4. Which of the following signatures are valid for the main() method entry point of an application?
A) public static void main()
B) public void main(String[] arg)
C) public static void main(String[] args)
D) public static int main(String[] arg)

5. What is the output of this code fragment?
1. int x = 3; int y = 10;
2. System.out.println(y % x);
A) 0
B) 1
C) 2
D) 3

6. What is the minimal modification that will make this code compile correctly?
 1. final class Aaa
 2. {
 3.     int xxx;
 4.     void yyy() { xxx = 1; }
 5. }
 6.
 7.
 8. class Bbb extends Aaa
 9. {
10.     final Aaa finalref = new Aaa();
11.
12.     final void yyy()
13.     {
14.         System.out.println("In method yyy()");
15.         finalref.xxx = 12345;
16.     }
17. }
A) On line 1, remove the final modifier.
B) On line 10, remove the final modifier.
C) Remove line 15.
D) On lines 1 and 10, remove the final modifier.
E) The code will compile as is. No modification is needed.

7. Consider the following code. Which line will not compile?
1. Object ob = new Object();
2. String stringarr[] = new String[50];
3. Float floater = new Float(3.14f);
4.
5. ob = stringarr;
6. ob = stringarr[5];
7. floater = ob;
8. ob = floater;
A) Line 3
B) Line 5
C) Line 6
D) Line 7
E) Line 8

8. Assume this class hierarchy:
                   Animal
                     |
                   Mammal
                     |
  --------------------------------------------
  |           |              |               |
 Dog         Cat          Raccoon       SwampThing
         (implements    (implements
            Washer)       Washer)
Consider the following code:
1. Raccoon rocky;
2. SwampThing pogo;
3. Washer w;
4.
5. rocky = new Raccoon();
6. w = rocky;
7. pogo = w;
Which of the following statements is true? (Choose one.)
A) Line 6 will not compile; an explicit cast is required to convert a Raccoon to a Washer.
B) Line 7 will not compile; an explicit cast is required to convert a Washer to a SwampThing.
C) The code will compile and run.
D) The code will compile but will throw an exception at line 7, because runtime conversion from an interface to a class is not permitted.
E) The code will compile but will throw an exception at line 7, because the runtime class of w cannot be converted to type SwampThing.

9. Which one statement is true about the code below?
1. String s1 = "abc" + "def";
2. String s2 = new String(s1);
3. if (s1 == s2)
4.   System.out.println("== succeeded");
5. if (s1.equals(s2))
6.   System.out.println(".equals() succeeded");
A) Lines 4 and 6 both execute.
B) Line 4 executes, and line 6 does not.
C) Line 6 executes, and line 4 does not.
D) D) Neither line 4 nor line 6 executes.

10. How would you set the color of a graphics context g to cyan? A) g.setColor(Color.cyan);
B) g.setCurrentColor(cyan);
C) g.setColor("Color.cyan");
D) g.setColor("cyan");
E) g.setColor(new Color(cyan));

11. What does the following code draw?
1. g.setColor(Color.black);
2. g.drawLine(10, 10, 10, 50);
3. g.setColor(Color.red);
4. g.drawRect(100, 100, 150, 150);
A) A red vertical line that is 40 pixels long and a red square with sides of 150 pixels
B) A black vertical line that is 40 pixels long and a red square with sides of 150 pixels
C) A black vertical line that is 50 pixels long and a red square with sides of 150 pixels
D) A red vertical line that is 50 pixels long and a red square with sides of 150 pixels
E) A black vertical line that is 40 pixels long and a red square with sides of 100 pixels

12.You execute the code below in an empty directory. What is the result?
1. File f1 = new File("dirname");
2. File f2 = new File(f1, "filename");
A) A new directory called dirname is created in the current working directory.
B) A new directory called dirname is created in the current working directory. A new file called filename is created in directory dirname.
C) A new directory called dirname and a new file called filename are created, both in the current working directory.
D) A new file called filename is created in the current working directory.
E) No directory is created, and no file is created.

Short Question
Question 1(8pts)
a). What happens when you try to compile and execute the following application with the command-line argument "1"? Choose all correct options.
 1. class Switcheroo {
 2.   public static void main(String[] args) {
 3.     int i = 0;
 4.     try {
 5.       i = Integer.parseInt(args[0]);
 6.     }
 7.     catch (Exception e) { }
 8.
 9.     switch (i) {
10.       case 0:
11.         System.out.println("zero");
12.       case 1:
13.         System.out.println("one");
14.       default:
15.         System.out.println("default");
16.     }
17.   }
18. }










b) Consider the following class hierarchy and code fragment:
              java.lang.Exception
                        \
                 java.io.IOException
                  /                \
java.io.StreamCorruptedException    java.net.MalformedURLException

 1. try {
 2.   // assume s is previously defined
 3.   URL u = new URL(s);
 4.   // in is an ObjectInputStream
 5.   Object o = in.readObject();
 6.   System.out.println("Success");
 7. }
 8. catch (MalformedURLException e) {
 9.   System.out.println("Bad URL");
10. }
11. catch (StreamCorruptedException e) {
12.   System.out.println("Bad file contents");
13. }
14. catch (Exception e) {
15.   System.out.println("General exception");
16. }
17. finally {
18.   System.out.println("Doing finally part");
19. }
20. System.out.println("Carrying on");

What is the output if the constructor at line 3 throws a MalformedURLException?









c). Consider the following classes, declared in separate source files:

 1. public class Base {
 2.   public void method(int i) {
 3.     System.out.println("Value is " + i);
 4.   }
 5. }

 1. public class Sub extends Base {
 2.   public void method(int j) {
 3.     System.out.println("This value is " + j);
 4.   }
 5.   public void method(String s) {
 6.     System.out.println("I was passed " + s);
 7.   }
 8.   public static void main(String args[]) {
 9.     Base b1 = new Base();
10.     Base b2 = new Sub();
11.     b1.method(5);
12.     b2.method(6);
13.   }
14. }
What output results when the main method of the class Sub is run?









d) For the following program, find out if there is any compiler error. If yes, circle the error and briefly decribe how to fix it. If not, write down the output of the program by running java Test
   1:import java.awt.*;
   2:import javax.swing.*;
   3:
   4:public class Test {
   5:    public static void main(String[] args) {
   6:        try {
   7:            JButton[] buttons = new JButton[10];
   8:            for(int i = 0; i < 20; i++) { 
   9:                buttons[i].setBackground(Color.red);
  10:            }
  11:        } catch(IndexOutOfBoundsException ex) {
  12:            System.out.println("IndexOutOfBoundsException");
  13:        } catch(NullPointerException ex) {
  14:            System.out.println("NullPointerException");
  15:        } catch(Exception ex) {
  16:            System.out.println("Exception");
  17:        }
  18:        
  19:        System.out.println("End of the program");
  20:    }
  21:}










Question 2(10pts)
Consider the following class
public class Citizen {
    public String name;
    public String SSN; //  9 digit social security number
        
    public Citizen(String name, String SSN) {
        this.name = name;
        this.SSN = SSN;
    }
        
    public boolean equals(Object obj) {
        if(obj instanceof Citizen) { // if obj is of type citizen
            return ((Citizen)obj).SSN.equals(this.SSN);
        } else {
            return false;
        }
    }
    
    public String toString() {
        return "name : " + name + "\n" 
	         + "SSN : " + SSN;
    }
}
Write down the output of the following program
import java.util.*;

public class CitizenTest {
    public static void main(String[] args) {
        LinkedList list = new LinkedList();
        Citizen c1 = new Citizen("Amy", "111223333");
        Citizen c2 = new Citizen("Ben", "222334444");
        list.add(c1);
        list.add(c2);
        list.add(new Citizen("Charles", "333445555"));
        list.add(new Citizen("David", "444556666"));
        list.add(new Citizen("Eve", "555667777"));
        
        list.remove(c2);
        list.add(2, new Citizen("Florence", "666778888"));
        System.out.println("Output1:");
        System.out.println(list.get(1));
        
        list.set(1, new Citizen("Charles", "777889999"));
        list.removeLast();
        System.out.println("Output2:");
        for(int i = 1; i <=3; i++) {
            System.out.println(list.get(i));
        }
        
        System.out.println("Output3:");
        System.out.println(list.contains(new Citizen("Unknown","111223333")));
        
        System.out.println("Output4:");
        System.out.println(list.indexOf(new Citizen("Amy", "777889999")));
    }
}















b) What is the advantage of using BufferedInputStream and BufferedOutputStream?














c) Write a function Color random(). The function randomly returns a new color.
Hint: Use constructor Color(float r, float g, float b) with r,g,b between 0 and 1.
Also use static double random() method in Math class. it returns a random number between 0 and 1.
Assume all the necessary packages are imported, fill in your codes.
Color random() {
    // your code
    














}
Question 3(10pts)
Write a method return the number of files in a given folder with the given extension.
The method int count(File f, String extension) returns You can assume there is no other folders inside the folder f Example
In a folder named hw4, there are 6 files 
a1.jpg, a2,jpg, a3.jpg, a4.jpg,  hw4.java, hw4.class
Hint : use endsWith method in String class.
Assume all the necessary packages are imported, fill in your codes
int count(File f, String ext) {
    //  your codes
    



















}

Long Questions
Question 1(16pts)
a) Write a method char encrypt(char ch). The table below shows us how to evaluate the function
chreturns
av
bd
cs
da
sb
vc
other charactersreturns the same character
Example encrypt('a') returns 'v', encrypt('H') returns 'H'.
b) write a function boolean encrypt(File in, File out) encrypt the content of File in by the above encrypt function and write the content to the File out.
Example: if content of the input file is
a, b, c, d are the first 4 letters.
Then the content of File out will be
v, d , s, a vre the firbt 4 letterb.
The function returns true if there is no exception. Returns false otherwise. Fill in your answer below
public class Question1 {
   public static char encrypt(char ch) {
        // your codes















} public boolean encrypt(File in, File out) { // your codes


































} }

Question 2(16pts) Write a class named DoubleVector. The class represents a list of doubles. Here is a constructor and methods Here is part of the code
import java.util.*;

public class DoubleVector {
    private Vector v;
    // your codes
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    

    }
}

Question 3(16pts)

Create a JFrame, with 4 JButtons and 1 JLabel.

homer.gif

marge.gif

bart.gif

lisa.gif
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class Simpson extends JFrame  implements ActionListener              
{
    // write your codes here
    // variables 
    









// constructors public Simpson() {









} public void actionPerformed(ActionEvent e) {









} // other codes (if any)









public static void main(String[] args) { JFrame f = new Simpson(); f.setSize(200,100); f.setVisible(true); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }