Tuesday, May 18, 2010

Solution for “Kuis 2 DPBO”

Since I won't be able to give back the result of quiz 2 in time, I guess it would be fair in the short time left for the DPBO exam that I provide solution for the quiz. Solution is due to Ms. Ika Alfina

Multiple Choice Problem 1
Perhatikan program berikut:
public class Abc{
   public static void main(String abc[])   {
      System.out.println(abc[2]);
   }
}
Apakah output dari program Abc.java jika dieksekusi dengan perintah berikut: #java Abc Universitas Indonesia ?
A.  Universitas           B.  Indonesia            C. null                  D. Exception occurs: java.lang.ArrayIndexOutOfBoundException
Answer: D -- (Note that the size of array abc is 2, consisting the strings: "Universitas" and "Indonesia")

Multiple Choice Problem 2
Apa output program berikut ini jika seandainya file abc.txt tidak ada?
import java.io.*;
import java.util.Scanner;

public class SoalX {
   public static void main(String[] args) {
      try {
         Scanner s = new Scanner(new File("abc.txt"));
      } catch(FileNotFoundException e){
         System.out.println("File tidak ditemukan");
      } catch(IOException e){
         System.out.println("Terjadi exception");
     }
   }
}
A. File tidak ditemukan        B.  Terjadi exception        C. Tidak berhasil dikompilasi      D. Terjadi runtime-error
Answer: A -- (Obvious)

Multiple Choice Problem 3
Jika pada program SoalX (pada soal nomor 2), pada bagian blok catch, ditukar letak antara catch pertama dan kedua, maka apakah output program tersebut jika seandainya file abc.txt tidak ada?
A. File tidak ditemukan         B. Terjadi exception         C.   Tidak berhasil dikompilasi      D.   Terjadi runtime-error
Answer: C -- (Why? Because FileNotFoundException is a subclass of IOException, thus putting the clause catching IOException first makes the clause catching FileNotFoundException redundant)
Multiple Choice Problem 4
Perhatikan program berikut ini:
public class Outer {
   static class Inner{}
   public static void main(String[] args) {
      //membuat instance Inner
      Outer.Inner oi = new ………………………….;
   }
}
Untuk membuat instance dari class Inner, titik-titik di atas harus dilengkapi dengan:
A. Inner()         B. Outer.Inner()         C.   Outer().new Inner()          D.   Semuanya (A,B dan C) salah
Answer: A or B -- (Note that class Inner is a static inner class and accessible directly from the main method)
Multiple Choice Problem 5
Berapa buah objek yang dapat dibuat dari anonymous inner class?
A. 1           B.  2            C. 3           D.   unlimited
Answer: A or D -- (problem sentence can be interpreted differently)
Multiple Choice Problem 6
Perhatikan cuplikan program di bawah ini:
class UjiGeneric  {
   T var1;
   UjiGeneric(Class var2) {
      try {
         var1 = ______________________;
      }  catch (Exception e) {
         throw new RuntimeException(e);
      }
   }
}
Apakah statement yang tepat pada underlined, sehingga var1 akan berisi objek dari T?
A.   new T();             B.  var2.newInstance();                  C.   var1.newInstance();                     D.  var2.new
Answer: B -- (Note that var2 is an instance of the final class java.lang.Class which is also a generic class. According to API, the method newInstance of java.lang.Class will create a new instance of T, as requested by the assignment. Other answer choices will yield in compilation errors).
Multiple choice problems 7 & 8 refer to the following program:
class Exc1 extends Exception {
   public void f() {
      System.out.println("as object of Exc1 class");
   }
}

public class CobaException {
   public void f() throws Exc1 {
      try {
         throw new Exception ();
      } catch (Exception e) {
         System.out.println("Inside catch in method f()");
         throw new Exc1();
      } finally {
         System.out.println("Inside finally in method f()");
         throw new Exc1() {
            public void f() {
               System.out.println("as object of inner class of Exc1");
            }
         };
      }
   } // end f()

   public static void main(String[] args) {
      CobaException ce = new CobaException();
      try {
         ce.f();
      } catch(Exc1 e) {
         e.f();
      }
   } // end main()
} // end class CobaException
Multiple Choice Problem 7
Manakah file bytecode yang tidak ada setelah kompilasi program?
A. Exc1.class                  B. Exc1$1.class                  C. CobaException.class                        D. CobaException$1.class
Answer: B -- (Note that Exc1.class and CobaException.class obviously exist. Another class is the anonymous inner class inside the class CobaException which is created in the "finally" clause starting  from the line containing "throw new Exc1()".  Since it is inside CobaException class, the bytecode file name must be CobaException$1.class)
Multiple Choice Problem 8
Manakah yang bukan keluaran program?
A. Inside catch in method f()                           B. Inside finally in method f()
C.  as object of inner class of Exc1                 D. as object of Exc1 class
Answer: D -- (Choice A is printed first after an exception is thrown in method f(). Throwing a new exception afterwards has no effect, because there is a "finally" clause forcing the control flow to remain in method f(). Next, the "finally" clause is executed, and Choice B is printed. This is followed by throwing a new exception that is anonymous subclass of Exc1. The anonymous subclass overrides the method f(). Since the "finally" clause closes the try-catch-finally block, the last exception was thrown to outside method f(), which is called in the main method. This last exception is then caught by the try-catch block in the main method whose "catch" clause contains a method call to the method f() of the exception. Here the overridden f() method is the one that is executed, yielding the choice C as the output).
Multiple Choice Problem 9
Manakah pernyataan berikut ini yang benar?
A.  Subclass dapat mengoverride method superclass dengan berbeda throws exception.
B.  Inner class dapat mempunyai static inner class.
C.  Field di dalam inner class bila merujuk ke field outer class harus dinyatakan final
D.  Applet tidak mempunyai method main.
Answer: D -- (Choice A is incorrect because the type of checked exceptions thrown by the overriding method is restricted to that of the overridden method, i.e., the same exceptions or their subclasses are required. Choice B is incorrect because a static inner class can only be inside a top-level class or another enclosing static inner class. Choice C is incorrect because no such restriction is required.)
Short Essay Problem 1
Perhatikan cuplikan program berikut ini:
class WithInner { class Inner {} }
public class InheritInner extends WithInner.Inner {
   WithInner wi = new WithInner();
   InheritInner() { wi.super(); }
   public static void main(String[] args) {
      InheritInner ii = new InheritInner(); 
   }
}
Apakah kesalahan pada cuplikan program di atas? Dan apakah yang perlu dilakukan agar tetap mempertahankan statement yang diberi garis bawah / underlined.
Answer:
The error lies on the constructor of InheritInner. More precisely, before even the variable wi can be accessed, the constructor of the superclass of InheritInner, i.e., WithInner.Inner, must be called first.
In order to make the code works without changing the underlined statement, first note that calling a no-arg constructor of an inner class requires an (enclosing) instance of the outer class. Thus, if the no-arg constructor of WithInner.Inner needs to be called, an instance of WithInner is required. However, we cannot use the WithInner instance refered by the variable wi, because the variable wi itself is not even initialized yet.

One way out is thus to make another different instance of WithInner available for the constructor of InheritInner by passing it as a parameter to the constructor. In other words, rewrite InheritInner with two constructors as follows:
   InheritInner(WithInner w) { w.super(); }
   InheritInner() { this(new WithInner()); }
Another possible way out is simply declaring the variable wi as a static variable so that its initialization is done BEFORE the call to the constructor of the superclass WithInner.Inner
Short Essay Problem 2
Perhatikan cuplikan program berikut ini:
public static int[] mergesort(int[] arr1, int[] arr2) {
   int[] arr = new int[arr1.length+arr2.length];
   return arr;
}
Ubahlah cuplikan program tersebut menjadi bentuk generic.
Answer: First, ignore the name mergesort as the name of the method... :-) .
The intention of this problem is to ask you to rewrite the method so that it accepts not only integer arrays but also arrays of other types using generic. The rewritten code is given below:
public static  T[] mergesort(T[] arr1, T[] arr2) {
   T[] arr = (T[]) new Object[arr1.length+arr2.length];
   return arr;
}
Note the way to create array of generic type above. The compiler does not allow array creation of generic type directly, thus the way to do it is create an array of objects and downcast it to the generic type.
Short Essay Problem 3
Tulis ulang program untuk method soalFasilkom berikut ini sedemikian agar anonymous inner class berubah menjadi inner class dengan nama Fasilkom
public void soalFasilkom() {
  addMouseListener(new MouseAdapter() { 
     public void mousePressed(MouseEvent me) {       System.out.println(me);
     }
  }); 
}
Answer: the problem basically asks us to move the anonymous inner class definition out from the method call into its own inner class. As the anonymous inner class is of type MouseAdapter, the inner class that we want to create should also be of type MouseAdapter. This is done as follows:
public void soalFasilkom() {
   class Fasilkom extends MouseAdapter {
      public void mousePressed(MouseEvent me) {
         System.out.println(me);
      }
   }
   addMouseListener(new Fasilkom());
}
The following program is used by Problem 4 to 7.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SoalGUI extends JFrame implements ActionListener{
   JPanel atasPnl;
   JLabel input1Lbl, input2Lbl;
   JTextField input1Txt, input2Txt;
   JButton okBtn;
   public SoalGUI() {
      input1Lbl = new JLabel("Input 1 :");
      input1Txt = new JTextField(10);
      input2Lbl = new JLabel("Input 2 :");
      input2Txt = new JTextField(10);
      atasPnl = new JPanel();
      atasPnl.setLayout(new GridLayout(2,2)); //LINE A
      atasPnl.add(input1Lbl);
      atasPnl.add(input1Txt);
      atasPnl.add(input2Lbl);
      atasPnl.add(input2Txt);
      getContentPane().add(atasPnl,BorderLayout.NORTH);
      okBtn = new JButton("OK");
      getContentPane().add(okBtn,BorderLayout.SOUTH);
      okBtn.addActionListener(this);
   }

   public static void main(String[] args) {
      SoalGUI s = new SoalGUI();
      s.pack();
      s.setVisible(true);
   }

   private String doX(String a){
      return a + a;
   }   public void actionPerformed(ActionEvent arg0) {
      input1Txt.setText(doX(input1Txt.getText()));
      input2Txt.setText(doX(input2Txt.getText()));
   }
}
Short Essay Problem 4
Gambarkan antarmuka dari program di atas
Answer: In Windows, it looks like this. Note the use of GridLayout for the JPanel "atsPanel" which makes a side-by-side arrangement of all the JLabel and JTextField instances.


Short Essay Problem 5
Seandainya diberikan input “1” untuk textfield input1Txt dan input “2” untuk textfield input2Txt, apakah yang terjadi ketika button “OK” diklik 2 kali ?
Answer: Everytime the button is pressed (see the actionPerformed(ActionEvent)) method, it takes the current content of the textfields and pass them to the method doX(String). The result of this method is then put back to the corresponding textfields. Note that the doX method returns the input string concatenated with itself. The result in Windows looks like this

Short Essay Problem 6
Sebutkan pasangan objek yang menjadi event source dan event listener
Answer: Event source is the JButton "okBtn" and the event listener is the class SoalGUI
Short Essay Problem 7
Seandainya baris program yang ditandai dengan LINE A dihapus, perubahan  apakah yang terjadi pada program?
Answer: Layout of the panel "atsPnl" changes from GridLayout to FlowLayout which is the default setting for JPanel. The GUI changes into like this:

The following program is used for problem 8 to 11
1   import java.io.*;
2   public class IOApp {
3      public static void main(String args[])
4   throws ClassNotFoundException, ....., .....
5      {  Data dat = new Data(11, "Bejo");
6         ObjectOutputStream os =
7            new ObjectOutputStream(new FileOutputStream("out.tmp"));
8         os.writeObject(dat);
9         os.close();
10        ObjectInputStream is =
11           new ObjectInputStream(new FileInputStream("out.tmp"));
12        Data d = (Data)is.readObject();
13        System.out.println(d);
14        is.close();
15     }
16  }
17  class Data implements Serializable {
18     private int val;
19     private InnerData in;
20     public Data(int v, String s) { val = v; in = new InnerData(s); }
21     public String toString() { return "Data: " + val + "->" + in; }
22  }
23  class InnerData implements Serializable {
24     private String name;
25     public InnerData(String s) { name = s; }
26     public String toString() { return "innerData: " + name; }
27  }
Short Essay Problem 8
Tuliskan dua exception dari package java.io yang diperlukan pada baris ke-4 agar program dapat berhasil dikompilasi.
Answer: FileNotFoundException, IOException
Short Essay Problem 9
Apabila kita ingin agar baris ke-4 pada program di atas dihapus, perubahan apa saja yang harus dibuat agar program di atas tetap dapat berhasil dikompilasi? (Catatan:  tentunya bukan dengan menuliskan kembali baris ke-4 pada program di atas).
Answer: one way to do it is to enclose line 6 - 14 in a "try" block and then put the appropriate "catch" blocks for each of those exceptions in line 4.
Short Essay Problem 10
Apa output dari program di atas?
Answer: Data: 11->innerData: Bejo
Short Essay Problem 11
Apa output dari program di atas apabila di baris ke-23 class InnerData TIDAK meng-implement interface Serializable?
Answer: an exception will occur (more precisely, the java.io.NotSerializableException) because the writeObject and readObject methods work correctly only on serializable objects.

No comments:

Post a Comment