Site Search:

Simulation Test 2 -- 80 question set - answer

Back OCAJP


  1. Q:
  2. Which of the following are valid Java identifiers?
    A. Private
    B. uY#i
    C. _var
    D. 18.0
    E. name$

    Answer: A, C, E

    Explain:

    Study: 
    ======
  3. Q:
  4. Which of the following are valid Java identifiers?

    A. 1990-9-7
    B. $$
    C. final
    D. you.win
    E. _367
    F._$5At$

    A: B, E, F

    Explain:

    Study: 
    ======
  5. Q:
  6. Which of the following are valid Java identifiers?

    A. import
    B. $USD#9
    C. _5rt$
    D. $U5tM
    E. 9M$_5R_

    A: C, D

    Explain:

    Study: 
    ======
  7. Q:
  8. What is the output of the following program?
      1 class test {
      2 private String a;
      3 private int b;
      4 private boolean c;
      5   public static void main(String...args) {
      6     test t = new test();
      7     System.out.print(t.a);
      8     System.out.print(t.b);
      9     System.out.print(t.c);
     10   }
     11 }
    A. There is no output
    B.  0true
    C. null0false
    D. The code don't compile
    E. null0true

    A: C
    Explain: instance variable got default value, object's default value is null, number's default value is 0 or 0.0, boolean's default value is false.
    ======

  9. Q:
  10. What is the output of the following program?
      1 class test {
      2 private long a;
      3 private int b;
      4   public static void main(String...args) {
      5     test t = new test();
      6     System.out.print(t.a);
      7     System.out.print(t.b);
      8   }
      9 }

    A. 00
    B. 0.00
    C. 1.00
    D. Line 3 generate a compiler error
    E. Line 6 generate a compiler error


    A: A

    Explain: long default value is 0, int default value is 0.
    Study: 

    ======

  11. Q:
  12. What is the output of the following program?
      1 class test {
      2 static private float a;
      3 static private int b;
      4 static private String c;
      5   public static void main(String...args) {
      6     System.out.print(a);
      7     System.out.print(b);
      8     System.out.print(c);
      9   }
     10 } 

    A. 0.0f0null
    B. 0.00null
    C. 00null
    D. 0.00
    E. Compilation error at line 9


    A: B

    Explain: instance variable and static variable with type float and double have default value 0.0, int have default value 0, object have default value null.

    ======

  13. Q:
  14. What's the output of the following program?
      1 class test {
      2 static private float a;
      3 static private Long b;
      4 static private String c;
      5   public static void main(String...args) {
      6     System.out.print(a);
      7     System.out.print(b);
      8     System.out.print(c);
      9   }
     10 }

    A. 0.0nullnull
    B. 0nullnull
    C. 0.00
    D. 0.00null
    E. 0.0null
    F. The code doesn't compile


    A: A

    Explain: class variable with type float have default value 0.0, Long and String are objects reference, they have default value null.
    ======

  15. Q:
  16. Given the following class, which of the following is true?
      1 class test {
      2 
      3   String tester() {
      4              
      5     for(int i = 0; i < 10; i++) {
      6 
      7     }
      8     return sum;
      9   }
     10 }

    A. If String sum; is inserted on line 2, the code will compile.
    B. If String sum = 10; is inserted on line 4, the code will compile.
    C. If String sum; is inserted on line 4, the code will compile.
    D. If String sum = 10; is inserted on line 6, the code will compile.
    E. The code compiles as it it.
    F. None of the above changes will make the code compile.


    A: A

    Explain: A is correct, because instance variable can be accessed in all methods. B is a trick one, String sum = 10 will generate compile error: 
    int cannot be converted to String. C is incorrect because local variable have to be initialized before using. D is incorrect because the when sum is defined side for loop, the scope is from line 5 to line 7. 
    ======

  17. Q:
  18. How many imports are optional in the following code?
      1 package test.ocajp;
      2 import java.lang.*;
      3 import java.lang.System;
      4 import java.lang.Error;
      5 import test.*;
      6 import test.ocajp.*;
      7 public class test{
      8   public int score() {
      9     test.ocajp.OCAJP t = new test.ocajp.OCAJP();
     10     return t.takeTest();
     11   }
     12 }

    A. 0
    B. 2
    C. 3
    D. 4
    E. 5
    F. This code don't compile.


    A: E

    Explain: classes in the java.lang.* package don't need to be imported. test.ocajp.OCAJP use full path, so an import statement is not needed. The answer is E.
    ======

  19. Q:
  20. What's the following are valid main method signature?

    A. private static void main(String[] args)
    B. public void main(String...args)
    C. public static void main(String[] args)
    D. public static void main(String...$s)
    E. public static void main(String args[])
    F. public static void main(String ... _$vee)

    A: C, D, E, F

    Explain: main method have to be public static void, the args list can be array or varargs.

    Study:
    ,

    ======

  21. Q:
  22. Which of the following lines compile?

    A. int i = 123_4;
    B. double i = 1_0._00;
    C. int i = 123_;
    D. byte i = 0b11;
    E. int i = 0xA;
    F. boolean i = 0;
    G. double i = 07;
    H. None of the above;

    A: A, D, E, G

    Explain: underscore can be added anywhere in numeric literal except begin and end and left and right of decimal point. A is correct, B and C is incorrect. Numeric literal can also be expressed in binary with 0b or 0B as prefix, octal with 0 as prefix, hexadecimal with 0x or 0X as prefix. D and E are correct. F is incorrect because boolean only have value true or false. G is correct, because 07 is the octal form of numeric literal, 07 have type int, it can be cast to higher pecision type double.

    Study:
    ,

    ======

  23. Q:
  24. Which of the followings are true?

    A. System.gc();  trigger a JVM garbage collection.
    B. garbage collection is guaranteed to be run.
    C. an object have to implement a protected void finalize method.
    D. Finalize method is guaranteed to be run if present.
    E. Finalize method can be run 1 or more times.
    F. None of the above

    A: F


    Explain: system.gc() suggests JVM it is a good point to do garbage collection, but JVM can ignore it. A is incorrect. garbage collection is run when an object have no variable refer to it or when an object is running out of scope, however, a program can exits before there is any need to run the garbage collection. B is incorrect. Java allows objects to optionally implement a method called finalize() with signature protected void finalize(). C is incorrect. Finalize() is only called when the garbage collection try to collect the object the first time. If the garbage collector fails to collect the object and tries to run it again later, the finalize() won't be run twice. D and E are incorrect.

    Study:

    ======

  25. Q:
  26. Which of the following operators can be used with int variables?

    A. >=
    B. !
    C. +=
    D. ==
    E. ||
    F. &
    G. ++

    A: A, C, D, F, G

    Explain: Relational operations can be used with int, A is correct. unary operator ! can only be used with boolean, B is incorrect. Assignment operator += can be used with int, C is correct. Equal to == can be used with int, D is correct. Logical operators can be used with boolean, when it used with int, it do bitwise logical calculation. Short -circuit logical operators || can only be used with boolean, E is incorrect. F is correct. Pre-unary operators ++ can be used with int, G is correct.

    Study:

    ======

  27. Q:
  28. What is the output of the following program?
      1 public class test{
      2   static boolean b;
      3   public static void main(String...args) {
      4     int i = (b)?10:9;
      5     int j = 0;
      6     for(int a = 0; a < i; a++) {
      7       j = a;
      8     }
      9     System.out.println(j++);
     10   }
     11 }

    A. 8
    B. 9
    C. 10
    D. 0
    E. The code doesn't compile


    A: A

    Explain: Static boolean b have default value false, false?10:9 give i the value 9. the for loop became for(int a=0; a < 9; a++). When a is 8, a++ is 9, a < 9 no longer true, the for loop exits. The last value assigned to j is 8. In line 9, j++ return value 8, then increase value by 1, the output is 8.
    ======

  29. Q:
  30. What is the output of the following code?
      1 public class test{
      2   public static void main(String...args) {
      3     int x = 1;
      4     long y = -x++-x--+3;
      5     System.out.print(y);
      6     if(y > 0)
      7     then System.out.print("positive");
      8     else System.out.print("negative");
      9   }
     10 }

    A. -5negative
    B. 1positive
    C. 0negative
    D. 3positive
    E. the code don't compile

    A: E
    Explain: line 7 have compiler error. E is correct. If remove then, the correct answer is C.  -x++-x--+3 is -(x++)-(x--)+3. Calculate from left to right, -(x++) returns -1, increase x to 2; x-- returns 2, decrease x to 1; -1 - 2 + 3 = 0. int 0 is promoted to long, then is assigned to y. y>0 is false, else is executed, the output is 0negative.
    ======

  31. Q:
  32. Which of the followings are valid statement;

    A. byte a = 1, b = 2; byte sum = (byte) (a + b);
    B. byte sum = 1 + 2;
    C. byte a = 1, b = 2; int sum = a + 2;
    D. byte a = 1, b = 2; byte sum = (byte)a + b;
    E. int a = 1, b = 1; int sum = a + b;

    A: A, B, C, D

    Explain: A, C  and E are correct, because byte is automatically promoted to int before arithmetic operations. In order to assign int to less precise type byte, an explicit cast is needed. B is correct because arithmetic literal 1 + 2 don't have a type yet before assigning to byte. D is incorrect because type cast have highest precedence, (byte)a + b is not equivalent to (byte)(a + b).

    Study:
    ,

    ======

  33. Q:
  34. What is the output of the following code snippets?
     10     do{
     11       int i = 0;
     12       System.out.print(i++);
     13     }while(i < 3)

    A. 012
    B. 01
    C. 123
    D. the code have an infinite loop
    E. None of the above


    A: E

    Explain: E is correct because the code doesn't compile, a ; is missing at the end. If the ; is added, the answer is D.
    ======

  35. Q:
  36. What is the output of the following code?
      1 public class Test{
      2   public static void main(String...args) {
      3     String s = "ok", s1 = "ok", s2 = new String("ok");
      4     System.out.print(s == s1);
      5     System.out.print(s.equals(s1));
      6     System.out.print(s == s2);
      7     System.out.print(s.equals(s2));
      8   }
      9 }

    A. falsetruefalsefalse
    B. falsefalsetruefalse
    C. truetruefalsetrue
    D. truefalsetruetrue
    E. line 3 generate compiler error
    F. line 6 generate compiler error


    A: C

    Explain: s and s1 are String type reference variable which both point to the same object in the string pool, s2 is a String type reference pointing to a String object created with new therefore not in string pool. 
    ======

  37. Q:
  38. What is the output of the following code?
      4     StringBuilder sb = new StringBuilder("123");
      5     sb.delete(0);
      6     sb.insert(1, "aa");
      7     sb.insert(2, "bb");
      8     System.out.println(sb.subString(3));

    A. ba
    B. ba3
    C. ab
    D. Line 5 generate compiler error
    E. Line 8 generate compiler error


    A: D, E

    Explain: StringBuffer's delete method signature is StringBuilder delete(int start, int end). StringBuilder deleteCharAt(int index) accept a single number as parameter. D is correct. E is correct because the right syntax is sb.substring(3) or sb.substring(3, sb.length())
    ======

  39. Q:
  40. What is the output of the following code snippets?
      4     String s = new String("xyz");
      5     String s1 = "xyz";
      6     StringBuilder sb = new StringBuilder("xyz");
      7     System.out.print(sb.equals(s));
      8     System.out.print(sb.equals(s1));
      9     System.out.print(s.equals(sb));
     10     System.out.print(s.equals(sb.toString()));

    A. truetruetruetrue
    B. truetruefalsetrue
    C. falsefalsefalsetrue
    D. falsefalsetruetrue
    E. The code doesn't compile


    A: C

    Explain: StringBuilder didn't override equals method inherited from Object class, line 7 and line 8 print false. Line 9 print false because sb is an StringBuilder object. line 10 print true because String override equals method inherited from Object class.
    ======

  41. Q:
  42. What is the output of the following code?
    String s = "abcdefg";
    System.out.print(s.substring(1,s.indexOf(a)));
    System.out.print(s.substring(6,6));
    System.out.print(s.substring(s.length());

    A. no output
    B. throw an Exception
    C. agg
    D. The code doesn't compile

    A: D

    Explain: The third print missed a closing brackets. D is correct. If The compiler error is fixed, B is correct answer, because the first print will throw java.lang.StringIndexOutOfBoundsException: String index out of range: -1.

    Study:
    ,

    ======

  43. Q:
  44. What is the output of the following code?
      8     String s = "1";
      9     s += new Integer(1);
     10     s += s.charAt(0);
     11     s += true;
     12     System.out.println(Long.parseLong(s.substring(0,2)));

    A. 111
    B. 11
    C. Line 9 generate compiler error
    D. Line 10 generate compiler error
    E. Line 11 generate compiler error
    F. throw an exception


    A: B

    Explain: String concatenate to any type get a String. There is no compiler error. C, D, E is incorrect. s.substring(0,2) at line 12 is the char at index 0 and 1, which is 11, so B is correct. At line 9 new Integer(1) is auto-boxing when creating the Integer object, and auto-unboxing when concatenate to s. 
    ======

  45. Q:
  46. What's the output of the following code snippets?
      6     StringBuilder s = new StringBuilder("1234567");
      7     s.deleteCharAt(3);
      8     s.insert(5, '0');
      9     System.out.println(s.substring(0,2));

    A. 23
    B. 123
    C. 124 
    D. 12
    F. Not compile


    A: D

    Explain: after line 7, the StringBuilder object contains 123567; after line 8, 1234507.
    ======

  47. Q:
  48. What are the output of the following code?
      5     String s = "abcdef ";
      6     s.replace('d', '-').replace('a', "=");
      7     s.toUpperCase();
      8     s.trim();
      9     if(s.endsWith(" ")) System.out.println(1);
     10     if(s.startsWith("A")) System.out.println(2);
     11     if(s.contains("d")) System.out.println(3);

    A. 1
    B. 2
    C. 3
    D. compiler error at line 6
    E. compiler error at line 9 and 10
    F. compiler error at line 11


    A: D

    Explain: This is a trick question, s.replace() have overloaded methods String replace(int a, int b) and String replace(char a, char b), however it don't have overloaded method String replace(char a, String b), D is correct. If fix line 6. The answer will be A and C. 
    String is immutable, invoke String functions doesn't change the original string. 
    Study: http://xyzcode.blogspot.com/2016/03/creating-and-manipulating-strings.htm
    ======

  49. Q:
  50. What is the output of the following code?
      4     StringBuilder sb = "abcdefg";
      5     sb.append("-").insert(3, "0").deleteCharAt(sb.length() - 2).reverse();
      6     System.out.println(sb);

    A. -fed0cba 
    B. abcdefg-
    C. abc0defg-
    D. -fedc0ba
    E. The code doesn't compile


    A: E

    Explain: This is a trick question, the first line doesn't compile because assign String to StringBuilder is not allowed. 
    ======

  51. Q:
  52. Which of the following array declaration is illegal?

    A. int[][] a[] = new int[][][] {new int[1][], new int[1][]};
    B. int [] a = new int[0];
    C. int a    [] = new int[]{1, 2, 3};
    D. int    [] a = {1, 2, 3};
    E. Object d[] = new java.util.ArrayList(2).toArray();
    F. None of the above

    Answer: F
    Explain: when declare multi-dimensional array, the initial values should be given or the size of the first dimension should be given. A is legal, because it gives the initial values of the 3D array. The initial values are 2 2-D arrays, each one have the size of the first dimension given in the declaration. B is correct, it declares an empty array. C and D are legal, because they gives the initial values of the array. E is legal, because ArrayList's toArray() method returns an array object.

    Study:
    , http://xyzcode.blogspot.com/2016/03/declare-instantiate-initialize-and-use_12.html,

    ======

  53. Q:
  54. Which of the following statements compile?

    A. int[] a = new int[2]; int l = a.capacity;
    B. char[] a = new char[2]; int l = a.length();
    C. List a = new ArrayList(); int l = a.length;
    D. List a = new ArrayList(); int l = a.size();
    E. cha[] a = new char[2]; int l = a.size();
    F. List a = new ArrayList(); int l = a.capacity();
    G. None of the above

    A: D

    Explain: array have a variable called length, ArrayList have a method called size().

    Study:
    ,

    ======

  55. Q:
  56. Given the following code, which of the following statements are true?
      4     List a = new ArrayList();
      5     int l = a.size();
      6     System.out.println(l);
      7     a.remove(0);

    A. line 6 print 10.
    B. line 6 print 0.
    C. The code doesn't compile due to line 5
    D. The code doesn't compile due to line 7
    E. The code throw an exception.
    F. None of the above

    A: B, E

    Explain: new ArrayList() creates an empty ArrayList, new Array(4) creates an ArrayList with initial capacity 4. A is incorrect, B is correct. line 7 compiles, but throw java.lang.IndexOutOfBoundsException.

    Study:

    ======

  57. Q:
  58. What is the output of the following code snippets?
      6     System.out.print(new int[0].equals(new int[0]));
      7     System.out.print(new int[0].equals(new int[0]));
      8     System.out.print(new ArrayList() == new ArrayList());

    A. falsetruefalse
    B. truetruefalse
    C. truetruetrue
    D. falsefalsefalse
    E. truefalsetrue
    F. The code doesn't compile


    A: A


    Explain: Array didn't override equals() method, two arrays with the same content are not equal. Since ArrayList override the equals() method, two ArrayList with the same contents are equal. 

    Study: 

    ======

  59. Q:
  60. What is the output of the following code?
      4     List<Integer> a = new ArrayList<Integer>();
      5     a.add(2);
      6     a.add(new Integer(3));
      7     a.set(2,0);
      8     a.remove(0);
      9     for(int i: a) System.out.println(i);

    A. 30
    B. 0
    C. 23
    D. 320
    E. do not compile
    F. code throw exception


    A: F

    Explain: The code compiles, line 7 generates 
    java.lang.IndexOutOfBoundsException.
    ======

  61. Q:
  62. What is the output of the following code?
      4     int[] a = {1, 4, 6, 9, 0};

      5     System.out.println(Arrays.binarySearch(a, 5));

    A. 3
    B. 2
    C. -3
    D. the code doesn't compile
    E. the result is uncertian.


    A: E

    Explain: When the array is unsorted, the binary search's result is unpredictable.
    ======

  63. Q:
  64. What is the output of the following code?
      4     int[] a = {1, 4, 6, 9};

      5     System.out.println(Arrays.binarySearch(a, 5));

    A. 3
    B. 2
    C. -3
    D. the code doesn't compile
    E. the result is uncertian.


    A: C

    Explain: When the array is sorted, the binary search's result is calculated as the following: 5 should be put at index 2, negate the value and minus 1, we got C.

    Study: 

    ======

  65. Q:
  66. Which of the following statements used auto-boxing?

    A. Integer i = Integer.parseInt("1");
    B. Integer i = Integer.valueOf("2");
    C. Integer i = 10;
    D. Integer i = null;
    E. None of the above


    A: A, C


    Explain: Integer.parseInt returns an int, Integer.valueOf returns Integer, A and C are correct, B is incorrect. D is incorrect because null is not int value.

    Study:

    ====== 

  67. Q:
  68. What is the output of the following code?
     1 import java.util.*;
      2 public class Test{
      3   public static void main(String...args) {
      4     LocalDate l = LocalDate.of(2015, Month.APRIL, 15);
      5     System.out.println(l.getYear() + " " + l.getMonth() + " " + l.getDayOfMonth());
      6   }
      7 }

    A. 2015 APRIL 15
    B. 2015 4 15
    C. 2015 3 15
    D. The code doesn't compile
    E. None of the above


    A: D

    Explain: getYear(), getMonth() and getDayOfMonth() returns the corresponding number. However, import java.util.* is needed.
    Study: 

    ======

  69. Q:
  70. What is the output of the following code snippets?
      4     LocalDateTime l = LocalDateTime.of(2015, 3, 15, 13, 20, 100);
      5     System.out.println(l.getYear() + " " + l.getMonth() + " " + l.getDayOfMonth());

    A. 2015 3 15
    B. 2015 March 15
    C. The code doesn't compile
    D. The code throw an exception
    E. None of the above


    A: D

    Explain: 
    java.time.DateTimeException: Invalid value for SecondOfMinute (valid values 0 - 59): 100

    Study:

    ======

  71. Q:
  72. What is the output of the following code?
      5     LocalDateTime l = LocalDateTime.of(2015, 3, 15, 13, 20, 10);
      6     Period p = Period.of(1, 1, 1);
      7     l.plusYears(1);
      8     l.plus(p);
      9     DateTimeFormatter f = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT);
     10     System.out.println(l.format(f));

    A. 3/15/15 13:20
    B. 3/15/15 1:20 PM
    C. 4/16/17 1:20 PM
    D. 4/16/17 13:20
    E. 1:20 PM
    F. The code doesn't compile
    G. The code throw exception

    A: C
    Explain: LocalDateTime  is immutable, plusYears() and plus() returns a reference variable pointing to a new LocalDateTime object. 
    Study: http://xyzcode.blogspot.com/2016/03/create-and-manipulate-calendar-data.htm
    ======

  73. Q:
  74. What is the output of the following code?
      4     DateTimeFormatter f = DateTimeFormatter.ofPattern("MM dd yyyy");
      5     LocalDate t = LocalDate.parse("03 10 2011", f);
      6     t = t.plusDays(30);
      7     System.out.println(f.format(t));

    A. 03 40 2011
    B. 03-40-2011
    C. 04 10 2011
    D. 04 09 2011
    E. 03 10 2011
    F. The code doesn't compile
    G. The code throw exception


    A: D

    Explain: line 6 won't throw exception, instead, java calculate the date and output D.
    ======

  75. Q:
  76. Which of the following compile?

    A. final static void method() {}
    B. Public final int method() {}
    C. void static method() {}
    D. void private method() {}
    E. public void final method() {}

    A: A

    Explain: A is correct because optional specifier final and static can be applied before return type void. B is in correct because public is the access modifier, Public is not a keyword. C is incorrect because optional specifier can not be added between return type and method name. D is incorrect because access modifier can not be added between return type and method name. E is incorrect because optional specifier final can not be added between return type and method name.

    Study:

    ======

  77. Q:
  78. Which of the following methods compile?

    A. public long method() {return 1;}
    B. private double method() {return 9.0f;}
    C. void method() {return;}
    D. public void method() {return null;}
    E. public int method() {return new Integer(0);}
    F. public Integer method() {return 5;}

    A: A, B, C, E, F

    Explain: A is correct, because int 1 can be auto cast to higher precision type long. B is correct because float 9.0f can be autocast to higher precision type double. C is correct because return statement didn't return a value. D is incorrect because return type void means no value can be returned including null. E is correct, because returned value new Integer(0) can be autounboxing to int. F is correct because return type int 5 can be autoboxing to Integer.

    Study:
    ,

    ======

  79. Q:
  80. Which of the following compile?

    A. public void method(int...args) {}
    B. public void method(String a, String ... b){}
    C. public void method(String...args, int b){}
    D. public void method(String[] arg1, String...arg2){}
    E. public void method(String ...arg1, String...arg2){}
    F. public void method(String[] arg1, String[] arg2){}

    A: A, B, D, F

    Explain: There can be only 1 varargs as method parameter, and it has to be the last parameter, A, B, D is correct. A method can have more than one arrays as parameters, F is correct.

    Study:

    ======

  81. Q:
  82. Given the following code, what is the output of java Tester.
      1 package test;
      2 public class Test{
      3   static String name;
      4   public int score;
      5   protected int time;
      6   private int[] answer = new int[80];
      7   static void method() {score = answer.length}
      8   int method2() {return score;}
      9 }

      1 package ocajp;
      2 import test.*;
      3 class Tester{
      4   public static void main(String...args) {
      5     Test t = new Test();
      6     System.out.print(Test.name);
      7     t.score = 100;
      8     t.time = 120;
      9     Test.method();
     10     System.out.println(method2());
     11   }

    A. 80
    B. 100
    C. compiler error at Test class line 6
    D. compiler error at Test class line 8
    E. compiler error at Test class line 9
    F. compiler error at Test class line 10

    A: C, D, E, F
    Explain: C is correct because name have default access modifier, which is accessible from the same package. D is correct because time has protected access modifier, but Tester didn't extends Test. E is correct because method have default access modifier. F is correct, because method2 have default access modifier.
    ======

  83. Q:
  84. Which of the following is true?

    A. Encapsulation uses package private instance variables.
    B. Encapsulation uses private instance variables.
    C. Encapsulation allows setters.
    D. Immutability uses private instance variables.
    E. Immutability don't allow setters.
    F. Immutability don't allow getters.

    A: B, C, D, E

    Explain: encapsulation set a variable private, and provide getter and setters, so the owning class can control the access to the variable. Immutability is more strict, it don't allow setters, so that other class can not change the value of the variable, however getter is allowed. So F is incorrect.

    Study:
    ======

  85. Q:
  86. What is the output of the following code?
      1 public class Test{
      2   public static int count;
      3   static {
      4     count++;
      5   }
      6   {
      7     count++;
      8   }
      9   public Test() {
     10     count++;
     11   }
     12   public static void add() {
     13     count++;
     14   }
     15 
     16   public static void main(String[] args) {
     17     System.out.print(count);
     18     Test t = null;
     19     System.out.print(count);
     20     t.add();
     21     System.out.println(count);
     22   }
     23 }

    A. 135
    B. 234
    C. 134
    D. 112
    E. The code doesn't compile
    F. The code throw exception


    A: D

    Explain: When main is called, the class is first time initiated, static initializer is called, count is 1. After line 18, the instance initializer is not called, and the constructor is not called, the count is still 1. When executing line 20, the static initializer no longer get called, count is 2.

    Study: 

    ======

  87. Q:
  88. What is the output of the following code?
      1 public class Test{
      2   public static Tester t1 = new Tester();
      3   public static Tester t2 = new Tester();
      4   {
      5     t1.count ++;
      6   }
      7   public static void add() {
      8     t2.count++;
      9   }
     10 
     11   public static void main(String[] args) {
     12     t1.count ++;
     13     t2.count ++;
     14     add();
     15     System.out.print(t1.count);
     16     System.out.println(t2.count);
     17   }
     18 }
     19 
     20 class Tester{
     21   public static int count = 0;
     22 }

    A. 12
    B. 33
    C. 44
    D. 22
    E. 00
    F. The code doesn't compile


    A: B

    Explain: count is an static variable, t1.count and t2.count both refer to it. Test have an instance initializer, but it never get called since we didn't create new Test().
    ======

  89. Q:
  90. What is the output of the following code?
      1 public class Test{
      2   public static String a;
      3   public static final String b;
      4   public static final String c;
      5   public static final String d;
      6   static {
      7     a = "a";
      8     b = "b";
      9   }
     10   static {
     11     a += "a";
     12     c = "c" + "c";
     13   }
     14   public static void main(String args[]) {
     15     d = "d"; 
     16     System.out.println("a="+a+",b="+b+",c="+c+",d="+d);
     17   }
     18 }

    A. aabcd
    B. the code doesn't compile
    C. if remove the line with compile error, the output is aabcc
    D. aabccd
    F. the code throw exception


    A: B

    Explain: line 16 don't compile because final variable have to be initialized in either static initializer or constructor. initialize final variable in main method is not allowed. Even remove line 15, the code still not compile, because static final variable is not initialized. 
    ======

  91. Q:
  92. Which import can make the following code compile?
      1 public class Test{
      2   public void method(int[] list) {
      3     sort(list);
      4   }
      5 }

    A. import java.util.Arrays;
    B. import java.util.Collections;
    C. import java.util.*;
    D. import static java.util.Arrays.*;
    E. import static java.util.Collections.*;
    F. import static java.util.Arrays.sort(int[] a);
    G. import static java.util.Collections.sort(int[] a);
    H. The code compile as it is.


    A: D

    Explain: sort is a static method of class Arrays. In order to access it without class name, import static java.uti.Arrays.*; is needed. F is not valid syntax. Collections.sort are applied to ArrayList and List but not to array, so E is not correct.
    ======

  93. Q:
  94. What is the output of the following code?
      1 public class Test{
      2   static void method (int a) {System.out.print(1);}
      3   static void method (Double d) {System.out.print(2);}
      4   static void method (Object o) {System.out.print(3);}
      5   byte a = 7;
      6   public static void main(String...args) {
      7     method(a);
      8     method(12.33);
      9     method(14.0f);
     10   }
     11 }

    A. 322
    B. 333
    C. 123
    D. 122
    E. 133
    F. The code doesn't compile


    A: F

    Explain: This is a trick question, instance variable a can not be called in static methods main. If a is static variable, the answer will be C. byte is auto promoted int, so line 2 is called. 12.33 is autoboxed to Double, so line 3 is called. 14.0f is autoboxed to Float, it has nothing to do with Double, so line 4 is called.
    ======

  95. Q:
  96. What is the result of the following code?
      1 import java.util.*;
      2 public class Test{
      3   public void add(StringBuilder sb, long a) {
      4     a = (int)a + a;
      5     sb = new StringBuilder("RESULT is ");
      6     sb.append(a);
      7   }
      8   public static void main(String...args) {
      9     Test t = new Test();
     10     StringBuilder sb = new StringBuilder("result is ");
     11     int a = 10;
     12     t.add(sb, a);
     13     System.out.println(sb.toString() + ", a=" + a);
     14   }
     15 }

    A. result is 20, a=10
    B. result is , a=10
    C. result is 20, a=20
    D. RESULT is 20, a=10
    E. The code doesn't compile
    F. None of the above


    A: B

    Explain: When object is method parameter, a copy of the the reference variable is passed in; when primitive is method parameter, the copy of the value is passed in. line 4 won't throw compile error, because arithmetic operator have higher priority than type cast operator, so it is equivalent to 
    a = (int)(a + a); D is incorrect because sb still point to original object, which didn't change inside the method.
    ======

  97. Q:
  98. What is the output of the following code?
      1 public class Test{
      2   public Test(int a, int b) {System.out.print(2);}
      3   public Test(int a) {System.out.print(1);}
      4   public Test() {Test(2); System.out.println(0);}
      5   public static void main(String ...args) {Test t = new Test();}
      6 }

    A. 012
    B. 210
    C. 10
    D. 01
    E. not compile
    F. throw exception


    A: E

    Explain: line 4 doesn't compile, it should call use this(2); to constructor instead.
    ======

  99. Q:
  100. What is the output of the following code?
      1 public class Test{
      2   String r = "f";
      3   {r += "i";}
      4   static
      5   {r += "s";}
      6   {r += "h";}
      7 
      8   public Test(int a) {System.out.print(1);}
      9   public Test() {this(2);}
     10   public static void main(String ...args) {
     11     System.out.print(r + " ");
     12     System.out.print(new Test().r + " ");
     13     System.out.print(new Test(2).r);
     14   }
     15 }

    A. fs 1fsih 2fsihih
    B. fs 1fsih 1fsihih
    C. fsh 1fshi 1fshii
    D. fish 1fish 1fish
    E. fs fsih1 fsihih1
    F. The code doesn't compile


    A: F

    Explain: F is correct because instance variable r can not be called in static initializer and static method. If r is static, answer will be B, at line 11, the static variable declaration and variable initializer are called, r is fs. At line 12, new Test() run the instance initializer, append i and h to r, however, 1 in the constructor is printed first, then r's value is printed. At line 13, the instance initializer is called agian, append another i and h to r.
    ======

  101. Q:
  102. What's the output of the following code?
      1 import java.util.function.*;
      2 public class Test{
      3   public boolean isPass () {return true;}
      4   public void method(Test t, Predicate<Test> p) {
      5     System.out.println(p.test(t));
      6   }
      7   public static void main(String ...args) {
      8     Test t = new Test();
      9     t.method(t, t1->!t1.isPass());
     10   }
     11 }

    A. true
    B. false
    C. compiler error on line 4
    D. compiler error on line 5
    E. compiler error on line 9
    F. throw exception


    A: B

    Explain: The code is correct. Line 9 create a lambda expression that returns the negate value of function isPass(). Since there is only one parameter and it does not specify a type, the parentheses around the type parameter can be omitted. Line 4 uses a Predicate interface, which declares a test() method.
    ======

  103. Q:
  104. How many compiler error in the following code?
      1 package test;
      2 interface FillCup{
      3   boolean isFull(int level, int limit);
      4 }
      5 public class Test {
      6   public void print(FillCup f, int level, int limit) {
      7     if(f.isFull(level, limit)) System.out.println("continue");
      8     else System.out.print("stop");
      9   }
     10   public static void main(String...args) {
     11     Test t = new Test();
     12     t.print(le,li->le<li, 3, 5);
     13     t.print((int le, int li)->{return le<li}, 5, 5);
     14     t.print((le, li)->{int le = 1; int li = 10; return le<li;}, 6, 5);
     15   }
     16 }

    A. 1
    B. 2
    C. 3
    D. 4
    E. 5
    F. The code compile as it is

    A: C
    Explain: Interface FillCup consumes a lambda with two int parameters, line 12, 13, 14 are all invalid lambda expressions. Line 12 missed parentheses around the parameter list. This is only optional for a single parameter with an inferred type. Line 13 missed semicolon for return statement. Line 14 redefines two variables that is already used by by lambda.
    ======

  105. Q:
  106. Which of the following lamda expression can be passed into List<String>'s removeIf() function?

    A. s->s.size() > 0
    B. s->true
    C. s->{return s.isEmpty();}
    D. (String s)->{s.contains("a");}
    E. (s) -> s.startsWith("a")
    F. String s -> {return false;}
    G. s -> {return s.endsWith("z")}
    H. ()->false

    A: B, C, E

    Explain: List removeIf() function consumes a Predicate. A is a valid lambda expression with single parameter with an inferred type, however, size() is not a String method, length() should be used instead. B is correct, it take a single parameter with an inferred type, returns true without calculation. C is correct, when return keyword is used, braces and semicolon are also needed. D is incorrect because return keyword is missing. E is correct because the parentheses around the parameter list is optional for single parameter with inferred type. F is incorrect, because when parameter list specified the type, so parentheses have to be used. G s incorrect because semicolon is missing. H is incorrect because predicate interface expect a size 1 parameter list, the lambda expression supplied an empty parameter list.

    Study:

    ======

  107. Q:
  108. What modifiers are implicitly applied to all interface methods?

    A. default
    B. final
    C. public
    D. abstract
    E. void
    F. static

    A: C

    Explain: All the interface methods are implicitly public. C is correct. Pre-java 8 interface methods are all implicitly abstract. However, java 8 also support static interface methods and default interface methods, which are not abstract. D is incorrect. In summary, interface methods can have 3 types of modifiers: public static, public default, and public abstract, only public is implicitly applied, static, default and abstract have to be explicitly declared. E is incorrect because void is return type not modifier. B is incorrect, interface variable and static interface methods can be public static final, but interface methods don't implicitly apply it.

    Study:

    ======

  109. Q:
  110. Given the following code in the same file named Test.java, what statements are true?
      1 public class Test {
      2   public int score = 0;
      3   public Test() {this.score = 70;}
      4   public static void main(String...args) {
      5     Test t = new Test();
      6     System.out.println(t.score);
      7   }
      8 }
      9 class Test1 extends Test{
     10   public Test1() {
     11     super.score = 80;
     12     System.out.print("blabla");
     13   } 
     14

    A. "javac Test.java" doesn't compile
    B. run "java Test" output 70
    C. run "java Test1" output 80
    D. run "java Test1" output Test180
    E. run "java Test1" throws exception
    F. run "java Test1" output 70 


    A: A
    Explain: The code compile as it is, A is incorrect. run java Test, the main function at line 4 is called, the output is 70, B is correct. run java Test1, the main function inherited from superclass is executed, again 70 is executed, F is correct. Constructor of Test1 never runs. Since Test's constructor has no parameters, Test1's constructor don't have to call it explicitly.
    ======

  111. Q:
  112. Which of the following statements are true about method overriding?

    A. subclass can define a method with an exception that is a subclass of the exception in the parent method.
    B. subclass can define a method with return type that is a subclass of the return type in the parent method.
    C. subclass can not define a method that is more accessible than the method in the parent class.
    D. Private method in parent class can be override by subclass.
    E. If a nonprivate method in parent class is static, the subclass can only hide it with static method.
    F. If a nonprivate method in parent class is nonstatic, the subclass can override it with either static or nonstatic method.


    A: A, B, E


    Explain: sublcass can define a method with an exception that is subclass of the exception in the parent method, the return type is a subclass of the return type in the parent method, the method in subclass can be more accessible than the method in parent class. Private method in parent class is irrelevant to subclass. For non-private methods in the parent class, both methods must be static (hide) or neither should be static (override).

    Study: 

    ======

  113. Q:
  114. What is the output of the following code?
      1 interface Drinkable {
      2   default void drink() {System.out.print("drink");}
      3 }
      4 public class Test implements Drinkable{
      5   public void drinking() {System.out.print("test drink");}
      6   public static void main(String...args) {
      7     Drinkable  d = (Drinkable)new Test();
      8     d.drink();
      9   }
     10 }

    A. drink
    B. test drink
    C. test drinkdrink
    D. drinktest drink
    E. not compile


    A: A

    Explain: line 2 is an interface method with default implementation, since method drink didn't get override in class Test, the default implementation is used.
    ======

  115. Q:
  116. Which of the following may only be hidden and not overridden?

    A. private instance methods
    B. protected instance methods
    C. public instance methods
    D. static methods
    E. public variables
    F. private variables


    A: A, D, E, F


    Explain: E and F are correct because variables can only be hidden never overridden. A is correct, because private instance methods are always hidden. D is correct because static methods can only be hidden.

    Study: 

    ======

  117. Q:
  118. What is the output of the following code?
      1 interface Testable {
      2   public abstract boolean test();
      3 }
      4 abstract class Student implements Testable {
      5   abstract int getScore();
      6   public boolean test() {return true;}
      7 }
      8 public class Test extends Student{
      9   public int getScore() {if(test())return 80; else return 0;}
     10 
     11   public static void main(String...args) {
     12     Test t = new Test();
     13     System.out.println(t.getScore());
     14   }
     15 }

    A. 80
    B. 0
    C. compile error from line 6
    D. compile error from line 9
    E. compile error from line 13

    A: A
    Explain: abstract class can optionally implement interface method and declare new abstract method, C is incorrect. The non-abstract class inherited overridden method test() from superclass Student, it overridden abstract class getScore(), D is incorrect. 
    ======

  119. Q:
  120. What is the output of the following code?
      1 abstract class Student {
      2   public void test();
      3 }
      4 public class Test extends Student{
      5   public void test() {System.out.println("120 minutes");}
      6   public static void main(String...args) {
      7     Student s = new Test();
      8     s.test();
      9   }
     10 }

    A. 120 minutes.
    B. The code will not compile because of line 2.
    C. The code will not compile because of line 4.
    D. The code will not compile because of line 7.
    E. The code will not compile because of line 8.


    A: B

    Explain: B is correct, 
    Test.java:2: error: missing method body, or declare abstract.
    ======

  121. Q:
  122. What is the output of the following code?
      1 abstract class Fish {
      2   private void swim() {System.out.println("swim fish");}
      3 }
      4 public class Trout extends Fish {
      5   public void swim() {System.out.println("swim Trout");}
      6   public static void main(String... args) {
      7     Fish f = new Trout();
      8     f.swim();
      9   }
     10 }

    A. swim fish
    B. swim Trout
    C. swim Trountswim fish
    D. swim fishswim Trount
    E. The code does not compile


    A: E

    Explain: superclass Fish have a private method, which can not be overridden by subclass Trout. Polymorphism does not apply here. The code does not compile, 
    Trout.java:8: error: swim() has private access in Fish.
    ======

  123. Q:
  124. Which of the following statements are true?

    A. Runtime exception is checked exception.
    B. Runtime exception can be caught.
    C. Runtime exception must be caught.
    D. Runtime exception extends Error.
    E. You can not declared Runtime exceptions.


    A: B

    Explain: Runtime exception is unchecked exception. You can catch Runtime exceptions in catch block or finally block. Runtime exceptions extends Exception which extends throwable; Error extends throwable. You can declare Runtime exceptions.

    Study:

    ======

  125. Q:
  126. Which of the following exceptions can only be thrown programmatically?

    A. java.io.IOException
    B. StatckOverflowError
    C. OutOfMemoryError
    D. NumberFormatException
    E. NullPointerExeption

    A: A, D

    Explain: B, C, E are thrown by JVM, A and D are thrown programmatically.

    Study:

    ======

  127. Q:
  128. Which of the following code will throw ArithmeticException?

    A. System.out.println(5/0);
    B. System.out.println(null/0);
    C. Integer.parseInt("xyz");
    D. throw new ArithmeticException();
    E. System.out.println(null);

    A: A, D

    Explain: A throws Arithmetic Exception. B does not compile for error: bad operand types for binary operator '/'. C throws NumberFormatException. D throws ArithmeticException. E does not compile for error: reference to println is ambiguous.

    Study:

    ======

  129. Q:
  130. What is the output of the following code?
      1 public class Test {
      2   public void method() throws java.io.IOException{
      3     System.out.print("A");
      4     try {
      5       int[] a = new int[0];
      6       System.out.print(a[1]);
      7     } catch (ArithmeticException ae) {
      8       System.out.print("B");
      9       throw new java.io.IOException();
     10     } catch (Exception e) {
     11       System.out.print("C");
     12     } finally {
     13       System.out.print("D");
     14     }
     15   }
     16   public void caller() {
     17     try {
     18       method();
     19     } catch(Exception e) {
     20       System.out.print("E");
     21     }
     22   }
     23   public static void main(String...args) {
     24     Test t = new Test();
     25     t.caller();
     26   }
     27 }

    A. ABCDE
    B. ACE
    C. ACD
    D. ACE
    E. ACDE
    F. The code does not compile


    A: C

    Explain: Line 6 throw 
    IndexOutOfBoundException, which is caught by line 10. The finally block is executed anyway. The IOException didn't throw out of method, line 19 didn't execute.
    ======

  131. Q:
  132. What is the output of the following code?
      1 public class Test {
      2   public String name;
      3   public void method() throws java.io.IOException{
      4     System.out.print("A");
      5     try {
      6       System.out.print(name.toString());
      7       System.out.print(1/0);
      8     } catch (ArithmeticException ae) {
      9       System.out.print("B");
     10       throw new java.io.IOException();
     11     } catch (Exception e) {
     12       System.out.print("C");
     13     } finally {
     14       System.out.print("D");
     15     }
     16   }
     17   public static void main(String...args) {
     18     Test t = new Test();
     19     t.method();
     20     System.out.print("F");
     21   }
     22 }

    A. ADF
    B. ABCDF
    C. ABDF
    D. ABD followed by stack-trace
    E. ACDF
    F. The code don't compile


    A: F

    Explain: This is a trick question, have to call method() in try-catch-finally block otherwise get 
    error: unreported exception IOException; must be caught or declared to be thrown.
    ======

  133. Q:
  134. Which of the following statements are true?

    A. You can declare a method with Exception as the return type.
    B. throws part of a method declaration have to be subclass of Exception.
    C. finally block is guaranteed to be executed in any condition.
    D. a method signature with throws part have to be surrounded by try-catch/finally block.
    E. none of the above

    A: A
    Explain: An instance of Exception is just an object, it can be returned from method call, however, the returned object does not act as exception. A is correct. B is incorrect because throws part of a method declaration have to be subclass of throwable, which includes Exception and Error. C is incorrect because System.Exit(0) will exit the program immediately, skipping any code underneath. D is incorrect because throws part can be subclass of RuntimeException or Error, neither of those need to be handled. 
    ======

  135. Q:
  136. Which of the following method can be inserted to line 7 in order to make the code compile?
      1 interface Fish {
      2   void swim() throws Throwable;
      3 }
      4 class SickException extends Exception{}
      5 class CaughtException extends RuntimeException{}
      6 public class Trout implements Fish {
      7   //code here
      8 }

    A. public void swim() {}
    B. public void swim() throws Error{}
    C. public void swim() throws SickException{}
    D. public void swim() throws CaughtException{}
    E. public void swim() throws Throwable{}
    F. public void swim() throws Object{}

    A: A, B, C, D, E


    Explain: the interface method swim() have throws part, however whatever throws is not a checked exception, there is no restrict to the implementing method's signature.
    F is syntax error, other method declarations are valid syntax and are all correct.

    Study: http://xyzcode.blogspot.com/2016/04/differentiate-among-checked-exceptions.html,

    ======

  137. Q:
  138. What is the output of the following code?
        1 import java.util.*;
      2 public class Test {
      3   public void print(int a) {
      4     String s;
      5     if(a > 0) s = "positive int";
      6     else s = "negative int";
      7     System.out.print(s);
      8   }
      9   public void print(byte a) {
     10     String s;
     11     if(a > 0) s = "positive byte";
     12     else s = "negative byte";
     13     System.out.print(s);
     14   }
     15   public static void main(String...args) {
     16     Test t = new Test();
     17     byte a = 1;
     18     t.print(a-1);
     19     t.print(a--);
     20   }
     21 }

    A. positive intpositive int
    B. negative intpositive int
    C. negative intpositive byte
    D. negative bytenegative byte
    E. no output
    F. The code does not compile

    A: C
    Explain: byte is converted to int before any arithematic operation. a-- is still 1.
    ======

  139. Q:
  140. What is the output of the following code?
      1 import java.util.*;
      2 public class Test {
      3   public static void main(String...args) {
      4     count((int s, int l) -> (return s > 1;), 90);
      5   }
      6   private static void count(Pass pass, int score) {
      7     if(pass.isPass(score, 80))
      8       System.out.println("pass");
      9     else
     10       System.out.println("try again");
     11   }
     12 }
     13 
     14 interface Pass {
     15   boolean isPass(int score, int limit);
     16 }

    A. pass
    B. try again
    C. line 4 doesn't compile
    D. line 7 doesn't compile
    E. throw exception


    A: A

    Explain: interface Pass expect 2 parameters, so the lamda function need to supply two variables. There are 2 ways of expressing the paramter name: (s, l) and (int s, int l), the lamda expression's body is can have several valid expressions: s > l, {return s > l;}. 
    Study: 

    ======

  141. Q:
  142. What is the output of the following code?
      1 interface HasScore {
      2   int getScore();
      3 }
      4 interface HasTime {
      5   void printTime();
      6 }
      7 interface CanTake extends HasScore, HasTime {}
      8 public class Test implements CanTake{
      9   public int getScore() {return 90;}
     10   public void printTime() {System.out.println(180);}
     11   public static void main(String...args) {
     12     System.out.println(new Test().getScore());
     13   }
     14 }

    A. 90
    B. compile error at line 7
    C. compile error at line 8
    D. compile error at line 9
    E. compile error at line 10
    F. none of the above


    A: A

    Explain: interface can inherit multiple interfaces. 
    ======

  143. Q:
  144. What's the output of "java Test"?
      1 class TestBase {
      2   public TestBase(String name) {System.out.print(name);}
      3   public static void main(String...args) {new Test();}
      4 }
      5 public class Test extends TestBase {
      6   public Test(int score) {System.out.print(score);}
      7   public Test() {
      8     this(80);
      9     System.out.print("-");
     10   }
     11 }

    A. 80-
    B. a80-
    C. Error: Main method not found in class Test
    D. The code doesn't compile
    E. None of the above

    A: D
    Explain: In main method, new Test(); is called. The line 8 calls line 6, which by default calls super() as the first constructor statement. However, since TestBase class provided a one parameter constructor, compiler won't generate a default constructor. Line 6 have to explicity call super("some name") in order to compile.
    ======

  145. Q:
  146. With the following code, what is the output of command "java Test Test Pass"?
      1 public class Test {
      2   public void main(String...args) {
      3     for (int i = 1; i<= args.length; i++)
      4       System.out.print(args[i]);}}

    A. TestPass followed by ArrayIndexOutOfBoundsException.
    B. TestTestPass
    C. TestPass
    D. Pass followed by ArrayIndexOutOfBoundsException.
    E. The code does not compile
    F. None of the above

    A: F
    Explain: public void main is not public static void main. The code compiles but at run time complaining miss main function. 
    ======

  147. Q:
  148. What is the output of the following code?
      1 import java.time.*;
      2 import java.time.format.*;
      3 public class Test {
      4   public static void main(String...args) {
      5     LocalDate date = LocalDate.of(2016, Month.MAY, 3);
      6     System.out.println(date.format(DateTimeFormatter.ofPattern("MMMM dd yyyy")));
      7   }
      8 }

    A. 05 03 2016
    B. May 3 2016
    C. the code does not compile
    D. the code throw exceptions
    E. none of the above

    A. B
    Explain: "MM dd yyyy" will print A, "MMM dd yyyy" and "MMMM dd yyyy" will print B.
    ======

  149. Q:
  150. What is the output of the following code?
      1 public class Test {
      2   public static void main(String...args) {
      3     int a = 10 % 3, b, c;
      4     b = a++ + 5/6;
      5     c += b++;
      6     System.out.println(a + b + c);
      7   }
      8 }

    A. 11
    B. 5
    C. 6
    D. 7
    E. 8
    F. not compile


    A: F

    Explain: at line 5, the local variable c have to be initialized before being used in arithemetic expressions.
    ======

  151. Q:
  152. Which of the following statements are true?

    A. {} are required around try block even if there is only one statement inside.
    B. {} are required around catch block event if there is no statement inside.
    C. {} are required around finally block even if there is one statement inside.
    D. {} are required around if block even if there is one statement inside.
    E. {} are required around else block even if there is one statement inside.
    F. {} are required around for block even if there is one statement inside.
    G. {} are required around while block even if there is one statement inside.
    H. {} are required around do-while block even if there is one statement inside.
    I. {} are required around switch block even if there is one statement inside.
    A: A, B, C, I


    Explain: {} are required for try, catch, finally and switch blocks, optional for if, else, else if, for loop, while loop, do-while loop if there is only one statement inside.

    Study:
    ,
    ,
    ,
    ,

    ======

  153. Q:
  154. Which of the following fill in the blank to print out 3?
    String numbers = "12345";
    String s = ______________
    System.out.println(s);

    A. numbers.charAt(2);
    B. numbers[2];
    C. numbers.charAt(3);
    D. numbers.substring(2, 2);
    E. numbers.substring(2, 3);
    F. numbers.substring(3, 3);
    G. numbers.substring(3, 4);

    A: E

    Explain: A is incorrect, since charAt returns a char which is not compatible with type String. E is correct, because substring parameters are inclusive start index and exclusive end index.

    Study:

    ======

  155. Q:
  156. What is the result of the following code?
      1 class Nothing {
      2   public String toString() {return "";}
      3 }
      4 public class Test {
      5   static Nothing nothing;
      6   public static void Main(String...args) {
      7     System.out.println(nothing.toString());
      8   }
      9 }

    A. compile error at line 1
    B. compile error at line 5
    C. compile error at line 7
    D. code compile but output nothing
    E. throw exception
    F. none of the above


    A: E

    Explain: the code compile as it is, line 7 compiles. Since variable nothing didn't get initialized, it has default value null, it will throw NullPointerException at runtime if runs. However there is no main function, Main is not main, when running the code, we will encounter 
    Error: Main method not found in class Test, please define the main method.
    Study: 

    ======

  157. Q:
  158. Which of the following statements are true?

    A. !(5>0) ^ false
    B. true & false
    C. true || false ^ false & false
    D. 3 > 2 && 2 < 0
    E. false ^ 1 >0

    A: C, E

    Explain: a^b is only true when a, b are different, A is incorrect. a&b is only true when both a, b are true, B is incorrect. || have lower precedence than &, |, ^, a || b is true if a is true regardless of the value of b, C is correct. && have lower precedence than >, <, a &&b is true when both a, b are true, d is incorrect. |, &, ^ have lower precedence than >, <, false ^ true is true, E is correct.

    Study:

    ======

  159. Q:
  160. What is the output of the following code?


      1 public class Test {
      2   private String name;
      3   private int score;
      4   public Test(int score) {
      5     score = score;
      6     this("", score);
      7   }
      8   public Test(String name, int score) {
      9     score = score;
     10     this.name = name;
     11   }
     12   public static void main(String...args) {
     13     Test t = new Test(55);
     14     System.out.println(t.score + "" + t.name);
     15   }
     16 }

    A. 55
    B. 0
    C. 550
    D. code dosen't compile
    E. code throw exception

    A: D
    Explain: When call another constructor inside a constructor, the constructor call have to be the first line. 
    Study:

    ======


  161. Q:
  162. What is the output of the following code?

      1 public class Test {
      2   public static void main(String...args) {
      3     String red = "RED";
      4     String yellow = "Yellow";
      5     final String color = false ^ false ? red : yellow = " is the color";
      6     System.out.println(color);
      7   }
      8 }

    A. is the color
    B. RED
    C. Yellow
    D. Yellow is the color
    E. not compile


    A: E

    Explain: = have lowest precedence. line 5 is final String color = (false ^ false ? red: yellow) = (" is the color"), which is not valid syntax.
    Study: 
    , http://xyzcode.blogspot.com/2016/03/create-if-and-ifelse-and-ternary.htm
    ======

  163. Q:
  164. what is the output of the following code?


      1 public class Test {
      2   Test t = new Test();
      3   static void public main(String...args) {
      4     new Test();
      5   }
      6   public void test() {
      7     Test t = new Test();
      8     if (t == t) {System.out.println("pass");}
      9   }
     10 }


    A:
    pass
    B. null
    C. no output
    D. the code have an infinite loop
    E. not compile


    A: E

    Explain: trick question, line 3 does not compile, because public came after return type.

    ======

  165. Q:
  166. Which of the following statements are true?
    StringBuilder sb1 = new StringBuilder("test"); StringBuilder sb2 = new StringBuilder("test");

    A. sb1 == sb2;
    B. sb1.equals(sb2);
    C. sb1 == "test";
    D. sb1.toString() == "test";
    E. sb1.toString().equals("test");
    F. None of the above


    A: E


    Explain: sb1 and sb2 are two different objects, A is incorrect. StringBuilder didn't implement equals method, B is incorrect. The code in C does not compile, because == can not be used to compare objects with different type. D is incorrect, because sb1.toString() returned a new String object which is not in string pool, however String literal "test" is in string pool. E is correct because sb1.toString() returns a String object and String class implemented equals method.

    Study: 

    ======

  167. Q:
  168. Which are the possible output of the following code?

      1 public class Test {
      2   public static void main(String...args) {
      3     Test t1 = new Test();
      4     Test t2 = new Test();
      5     t1 = t2;
      6     t2 = null;
      7     t1 = null;
      8     System.gc();
      9   }
     10   protected void finalize(Object obj) {System.out.print("do finalize");}
     11 }

    A. The code does not compile
    B. do finalizedo finalize
    C. do finalize
    D. no output
    E. none of the above


    A: D

    Explain: This is a trick question, protected void finalize(Object obj) is a normal method, while protected void finalize() method is called with garbage collection happens. If protected void finalize() is used, the answer would be B, C, D. Programmer can not control when garbage collection happening or whether or not garbage collection happens at all. At line 5, t1 is no longer reference to the Test object created at line 3, which makes is garbage collectable, the Test object created at line 4 now have two references to it, namely t1 and t2. After line 7, both Test objects are garbage collectable. If a garbage collection happened after line 5, C is the answer; if a garbage collection happened after line 7, B is the answer; if no garbage collection happened at all, D is the answer. System.gc() can not force JVM to do garbage collection.

    ======

  169. Q:
  170. What is the output of the following code?
      1 interface Testable {
      2   int TIME;
      3   void doTest();
      4 }
      5 public class Test implements Testable{
      6   public void doTest(){};
      7   public static void main(String...args) {
      8     System.out.println(new Test().TIME);
      9   }
     10 }

    A. 180
    B. code does not compile because of line 2
    C. code does not compile because of line 3
    D. code does not compile because of line 8
    E. code compile but throw exception


    A: B

    Explain: line 2 declared a public static final int Time; interface variable, however didn't give it the initial value. line 3 declared a public abstract void doTest(); interface method.

    ======


  171. Q:
  172. What is the output of the following code?
      1 interface Testable {
      2   int TIME = 180;
      3   void doTest();
      4 }
      5 public class Test implements Testable{
      6   void doTest(){};
      7   public static void main(String...args) {
      8     System.out.println(new Test().TIME);
      9   }
     10 }

    A. 180
    B. code does not compile because of line 2
    C. code does not compile because of line 3
    D. code does not compile because of line 6
    E. code does not compile because of line 8
    F. code compile but throw exception


    A: D

    Explain: line 2 declared a public static final int Time; interface variable, line 3 declared a public abstract void doTest(); interface method. Line 6 does not compile, the error is 
    attempting to assign weaker access privileges; was public.

    ======
    What is the output of the following code snippets?


      9     int[] array [] = new int[4][4];
     10     for (int i = 0; i < array.length; i++)
     11       for (int j = 0; j < array.length; j++)
     12         array[i][j] = i*j;
     13         System.out.println(array[4][4]);

    A. 3
    B. 4
    C. 1
    D. 9
    E. code does not compile
    F. code throws exception


    A: F

    Explain: This is a 4x4 array, the index is from 0 to 3, line 13 throws ArrayIndexOutOfBoundsException.

    Study: http://xyzcode.blogspot.com/2016/03/declare-instantiate-initialize-and-use_12.html
    ======
    What is the output of the following code snippets?


      9     int[] array [] = new int[4][4];
     10     for (int i = 0; i < array.length; i++)
     11       for (int j = 0; j < array.length; j++)
     12         array[i][j] = i*j;
     13         System.out.println(array[i][j]);

    A. 3
    B. 4
    C. 1
    D. 9
    E. code does not compile
    F. code throws exception


    A: E

    Explain: This is a 4x4 array, the index is from 0 to 3. Since local variable i and j is out of scope at line 13, it won't compile.


    Study: http://xyzcode.blogspot.com/2016/03/declare-instantiate-initialize-and-use_12.html, 

    ======

  173. Q:
  174. What is the output of the following code?
      1 import java.util.*;
      2 public class Test {
      3   public static void main(String...args) {
      4     List l = new ArrayList();
      5     l.add(true);l.add(2);l.add(1);l.add(0);
      6     l.remove(true));
      7     l.remove(new Integer(0));
      8     System.out.print(l.contains(0));
      9     System.out.print(l.contains(1));
     10     System.out.print(l.contains(2));
     11     System.out.print(l.contains(true));
     12   }
     13 }

    A. falsetruetruefalse
    B. falsetruetruefalse
    C. truetruefalsetrue
    D. falsetruetruetrue
    E. code does not compile
    F. code throw exception


    A: B

    Explain: The List didn't specify element type with generics, so the element type is the default one -- Object, means any object can be accepted. When primitive types are added, they will be auto-boxed. 

    line 6 auto-boxing true to new Boolean(true), then search and remove the corresponding array element. line 7 is tricky, because List have overloaded remove method that accept both Integer and int, when int is supplied, it act as index. When Integer is supplied, it removes the matching object in the array.
    ======

  175. Q:
  176. What is true about the following code?
      1 abstract class SomeTest {
      2   abstract int doTest();
      3 }
      4 public abstract class Test extends SomeTest{
      5   protected int doTest() {return 0;}
      6   private void doTest(boolean a) {}
      7   private abstract void doTest(Integer a);
      8   public Integer doTest() {return null;}
      9 }

    A. The code does not compile due to line 5
    B. The code does not compile due to line 6
    C. The code does not compile due to line 7
    D. The code does not compile due to line 8
    E. The code compiles as it is


    A: C, D

    Explain: SomeTest defined an abstract doTest with return type int. Line 5 is an override of doTest, the access modifier is less strict, which is allowed
    . Line 6 overloaded method doTest with different parameter list, since it is not an overriding, change access modifier from default to private is ok. Line 7 is another overloaded version of method doTest, however, abstract method can not be private, private method can not be override. Line 8 is an override of doTest, however Integer is not a subclass of primitive type int.
    ======

  177. Q:
  178. What is the output of the following code?
      1 import java.time.*;
      2 import java.time.format.*;
      3 public class Test {
      4   public static void main(String...args) {
      5     LocalDate d = LocalDate.of(2016, 5, 1);
      6     Period p = Period.of(1, 1, 1);
      7     d = d.minus(p);
      8     DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT);
      9     System.out.println(f.format(d));
     10   }
     11 }

    A. 2016-05-01
    B. 3/31/15
    C. 2015-03-31
    D. 5/1/16
    E. 03/31/2015
    F. code does not compile
    G. code throw exception

    A: G
    Explain: Line 8 throw RuntimeException java.time.temporal.UnsupportedTemporalTypeException, it should use ofLocalizedDate instead of ofLocalizedDateTime. If that is corrected, the answer will be B. Line 6 defined a period of 1 year 1 month and 1 day. Line 7 minus 1 year 1 month and 1 day from date 2016-05-01, which is 2015-03-31. Since FormatStyle.SHORT is used, the output is 3/31/15. For FormatStyle.MEDIUM, the output is Mar 31, 2015. For FormatStyle.Long, the output is March 31, 2015. For default without and format, the output is 2016-05-01. 
    ======

  179. Q:
  180. What is the output of the following code?
      1 import java.util.*;
      2 public class Test {
      3   public static void main(String...args) {
      4     String[] list = {"a", "b"};
      5     List<String> l = Arrays.asList(list);
      6     l.set(1, "c");
      7     l.add("d");
      8     for(String a: list)
      9       System.out.print(a);
     10   }
     11 }

    A. abd
    B. acd
    C. abcd
    D. the code does not compile
    E. the code throw exception


    A: E

    Explain: Arrays.asList created a List backed by the original array. The list content can be modified, but the size can not change. Line 7 will generate 
    java.lang.UnsupportedOperationException.
    ======
    What is the output of the following code snippets?


      9     int[] array [] = new int[4][4];
     10     for (int i = 0; i < array.length; i++)
     11       for (int j = 0; j < array.length; j++)
     12         array[i, j] = i*j;
     13         System.out.println(array[3, 3]);

    A. 3
    B. 4
    C. 1
    D. 9
    E. code does not compile
    F. code throws exception


    A: E

    Explain: This is a 4x4 array, line 12 used illegal syntax array[i, j], the correct syntax is array[i][j]. Line 13 also used wrong syntax array[3, 3], it should be array[3][3]
    Study: http://xyzcode.blogspot.com/2016/03/declare-instantiate-initialize-and-use_12.html
    ======

  181. Q:
  182. What is the output of the following code?
      1 interface canScore{}
      2 abstract class SomeTest{
      3   public int scores;
      4 }
      5 class Tester extends SomeTest implements canScore{}
      6 public class Test {
      7   public void doTest(SomeTest t) {t.scores += 50;}
      8   public static void main(String...args) {
      9     Test t = new Test();
     10     SomeTest tr = new Tester();
     11     t.doTest(tr);
     12     System.out.println(tr.scores);
     13   }
     14 }

    A. 0
    B. 50
    C. code does not compile due to line 5
    D. code does not compile due to line 7
    E. code does not compile due to line 11
    F. code does not compile due to line 12


    A: B

    Explain: line 11 set scores value to 50. Line 12 print out the changes scores value.

    ======

Back OCAJP