Friday 19 July 2013

OCJP Model Question and Answer - Concept Java Generics

Question 6:

 public class Score implements Comparable<Score> {
 private int wins, losses;
 public Score(int w, int l) { wins = w; losses = l; }
 public int getWins() { return wins; }
 public int getLosses() { return losses; }
 public String toString() {
 return "<" + wins + "," + losses + ">";
 }
 // insert code here
 }

Which method will complete this class?
A. public int compareTo(Object o){/*more code here*/}
B. public int compareTo(Score other){/*more code here*/}
C. public int compare(Score s1,Score s2){/*more code here*/}
D. public int compare(Object o1,Object o2){/*more code here*/}

Things to know :
..............................

java generics concept.

Explanation :
.........................

It comes under the generics concept.
when you try with  public int compareTo(Object o){/*more code here*/} ,
you will come across the following error.
Name clash: The method compareTo(Object) of type Score has the same erasure as compareTo(T) of type Comparable<T> but does not override it


Since given the comparable operates on score , one should use Score type.

hence the answer is option B

-----------------------------------------------------------------------------------------------------------------------------------

Question : 7
....................

11. class Converter {
12. public static void main(String[] args) {
13. Integer i = args[0];
14. int j = 12;
15. System.out.println("It is " + (j==i) + " that j==i.");
16. }
17. }


What is the result when the programmer attempts to compile the code and run it with the
command java Converter 12?


A. It is true that j==i.
B. It is false that j==i.
C. An exception is thrown at runtime.
D. Compilation fails because of an error in line 13.



Explanation:
.......................
compilation fails. with the error
Type mismatch: cannot convert from String to Integer on line no 13

Ans: D

------------------------------------------------------------------------------------------------------------------------------------

Question : 8  
....................

5. import java.util.Date;
6. import java.text.DateFormat;
21. DateFormat df;
22. Date date = new Date();
23. // insert code here
24. String s = df.format(date);

Which code fragment, inserted at line 23, allows the code to compile?

A. df = new DateFormat();
B. df = Date.getFormat();
C. df = date.getFormat();
D. df = DateFormat.getFormat();
E. df = DateFormat.getInstance();


Explanation:
........................

A.Error  : Cannot instantiate the type DateFormat
B.Error  : The method getFormat() is undefined for the type Date
C.Error  : The method getFormat() is undefined for the type Date
D.Error  : The method getFormat() is undefined for the type DateFormat
E. works fine

Ans : E



Please find more in the following posts.

Please feel free to comment.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...