Site Search:

Simulation test 1, 80 question set - answer

Back OCAJP


  1. Q:
  2. What is the output of the following program?
      1 class Test {
      2 private long a;
      3 private int b;
      4 private String c;
      5   public static void main(String...args) {
      6     Test t = new Test();
      7     t.print(a);
      8     t.print(b);
      9     t.print(c);
     10   }
     11   public void print(Object o) {System.out.print(1);}
     12   public void print(long l) {System.out.print(2);}
     13   public void print(int i) {System.out.print(3);}
     14   public void print(String s) {System.out.print(4);}
     15   public void print(Long L) {System.out.print(5);}
     16   public void print(Integer I) {System.out.print(6);}
     17 }

    A. 0.00null
    B. 00null
    C. 0.00
    D. 00
    E. This code doesn't compile

    A: E
    Explain: non-static variable a cannot be referenced from a static context. If the variables are all static, the result will be 234.
    ======
  3. Q:
  4. Which of the following are true?
     11     byte b = 90;
     12     int c = b + 1;
     13     double d = 9;
     14     String var = "test";
     15     var.length();
     16     d.length();

    A. Line 11 generate compiler error.
    B. Line 12 generate compiler error.
    C. Line 13 generate compiler error.
    D. Line 16 generate compiler error.
    E. The code compile as is.

    A: D
    Explain: byte, short, int, and long are used for numbers without decimal points. When byte, short and char are used with java arithmetic operator, the type is automatically converted to int. So A and B is incorrect. It is ok to cast from low precision numeric type to higher precision numeric type. String literal 9 has type int, it can be casted to double, so C is incorrect. String have method length(). Primitive data type don't have length, So D is correct.

    Study:
    ======
  5. Q:
  6. What's the output of the following code?
      1 class Test {
      2 static private float a;
      3 static private Long b;
      4 private String c;
      5   public static void main(String...args) {
      6     Test t = new Test();
      7     t.tester();
      8   }
      9   void tester() {
     10     byte a = 90;
     11     int b = 10L;
     12     double c = 9;
     13     long e = 1;
     14     a = e;
     15     System.out.println(c);
     16   }
     17 }

    A. 9.0
    B. there is no output
    C. Line 10 generate compile error
    D. Line 11 generate compile error
    E. Line 12 generate compile error
    F. Line 14 generate compile error

    A: D, F
    Explain: D, F generate compile error incompatible types: possible lossy conversion from long to int. Local variable a, b, c here hide global variable with the same name, you can access static variable with class name and access instance variable with this keyword. If line 11 and line 14 is removed, the output is 9.0
    Study:
    ======
  7. Q:
  8. Given the following classes, which of the following is needed to make the code compile?
      package animal.fishes;
      public class Fish {}

      3 
      4 package pond;
      5 
      6 public class Trout extends Fish {}

    A. If import animal.fishes; is inserted at line 5, the code will compile.
    B. If import animal.fishes.* is inserted at line 5, the code will compile.
    C. If import animal.fishes.Fish; is inserted at line 5, the code will compile.
    D. If import animal.fishes.*; is inserted at line 3, the code will compile.
    E. None of these can make the code compile.
    F. The code compile as it is.

    A: C
    Explain: Use import animal.fishes.Fish; to import a specific class, use import animal.fishes.*; to import all classed in a package. A is incorrect, C is correct. B is missed ";". D is incorrect because package have to be  the first line of a class code.
    Study: 
    ======
  9. Q:
  10. Given the following classes, which of the following code can replace //INSERT IMPORTS HERE to make the code compile?

    package test;
    public class ClassRoom {
      int count = 10;
    }

    package test.ocajp;
    public class ClassRoom {
      int count = 5;
    }

    package student;
    //INSERT IMPORTS HERE
    public class Student {
      ClassRoom c = new ClassRoom();
    }

    A. import test.*;
    B. import test.ocajp.*;
    C. import test.ClassRoom;
         import test.ocajp.*;
    D. import test.ocajp.ClassRoom;
         import test.*;
    E. import test.*;
        import test.ocajp.*;
    F. import test.ClassRoom;
        import test.ocajp.ClassRoom;

    A: A, B, C, D

    Explain: A import all classes in package test, not include classes in test.ocajp. B import all classes in package test.ocajp. C import one class from package test and all classes from test.ocajp, the explicit import have precedent over wildcard import. D explicit import have precedence over wildcard import. E and F are not correct because the import have ambiguity.

    Study:
    ======
  11. Q:
  12. Given the following class, what is the following calls print out?
      1 public class Test{
      2   public static void main(String...args) {
      3     System.out.println(args[1]);
      4   }
      5 }

    java test a "b c" d 
    A. a
    B. b
    C. b c
    D. d
    E. The code doesn't compile

    A: C
    Explain: the first args is not test, the first args is a, second args is "b c", so C is correct. The args can be String[] args, String...args, String args[], so E is not correct.
    ======
  13. Q:
  14. Which of the following are true?


    A. An instance variable of float default to 0.0
    B. An instance variable of Double default to 0.0
    C. An local variable of int default to 0
    D. An static variable of boolean default to false
    E. An instance variable of int default to null
    F. None of the above

    A: A, D

    Explain: For instance variables and static variables, boolean default to false, double and float default to 0.0, char default to NULL, byte, short, int, long default to 0, object references default to null. A and D is correct. B is incorrect because Double is the wrapper class of double. C is incorrect because local variables don't have default value, they must be initialized before using. 

    Study: 
    ======
  15. Q:
  16. Given the following class in file com/a/corp/A/Class.java, from which directory we can compile it successfully.

    package corp.A;

    public class Class{}

    A. com
    B. com/a
    C. com/a/corp
    D. com/a/corp/A
    E. Do not compile

    A: A, B, C, D

    Explain: see the following proof

    #cat com/a/corp/A/Class.java
    package corp.A;
    public class Class{}
    #javac com/a/corp/A/Class.java 
    #cd com/
    #javac a/corp/A/Class.java 
    #cd a/
    #javac corp/A/Class.java 
    #cd corp/
    #javac A/Class.java 
    #cd A/
    #javac Class.java 
    ======
  17. Q:
  18. Which of the following is true?
    public class Test{
      public static void main(String...args) {
        test t = new test();
      }
    }

    A. test is a class.
    B. t is a reference to an object.
    C. test is a reference to an object.
    D. t is a class.
    E. None of the above.

    A: A, B
    Explain: new test(); created an object, t is a reference with type test.
    ======
  19. Q:
  20. Given the class, which of the following are true.
      1 public class Test{
      2   public static void main(String...args) {
      3     test t = new test();
      4     test t1 = new test();
      5     test t3;
      6     t3 = t;
      7     t1 = null;
      8     System.gc();
      9     t3 = null;
     10   }
     11 }

    A. the test object from line 3 is eligible for garbage collection immediately following line 8.
    B. the test object from line 3 is eligible for garbage collection immediately following line 9.
    C. the test object from line 4 is eligible for garbage collection immediately following line 7.
    D. the test object from line 4 is eligible for garbage collection immediately following line 8.
    E. None of the above.

    A: C
    Explain: A and D is incorrect because System.gc() didn't force a garbage collection. B is incorrect because object reference t and t3 both point to the test object from line 3. t3 is set to null at line 9, however, t is still reference to the test object from line 3. C is correct because t1 is the only object reference pointing to the test object from line 4, once it is set to null, there is no variable reference to test object from line 4, it is eligible for garbage collection. 
    ======
  21. Q:
  22. Which of the following are true?

    A. javac compiles .java file int .class file.
    B. the first argument of the main function is the class name.
    C. more than one classes can be defined in one .java file.
    D. java is an object oriented language
    E. java is a method oriented language

    A: A, C, D

    Explain: B is incorrect. Even though java program takes the class name as the first parameter, the first argument of the main function is not the class name. C is correct. More than one classes can be defined in one .java file, only one class can be public, the class name have to match file name.

    Study: 
    ======
  23. Q:
  24. Which statements at line 8 will allow the following code to compile?
      6     short a = 1;
      7     byte b = 2;
      8 


    A. short c = a + b;
    B. int c = a*b;
    C. long c = a /b;
    D. byte c =0; c += a + b;
    E. short c = (short)(a + b);

    A: B, C, D, E
    Explain: Byte, short are automatically promoted to int when participate to arithmetic operation, a + b have type int. When int is assign to less precise type short, the compile error is possible lossy conversion from int to short. A is incorrect. Explicit type cast from int to short works, E is correct. When assign int to more precise type long, it is ok. C is correct. D is correct, because it's assignment operator is equivalent to byte c = (byte)(c + (a + b)).
    ======
  25. Q:
  26. What is the output of the following code?
      1 public class Counter{
      2   public static void main(String...args) {
      3     for(int a = 0; a < 4; a++) {
      4       if(a <= 1) continue;
      5       System.out.print(a);
      6       break;
      7     }
      8   }
      9 }

    A. 1
    B. 2
    C. 3
    D. 23
    E. 01
    F. 0
    G. The code doesn't compile

    A: B
    Explain: when a is 0 and 1, continue is executed, no output. When a is 2, System.out.print(a) output 2, break; statement at line 6 then breaks the for loop.
    Study: 
    ======
  27. Q:
  28. What is the output of the following code snippet?
      3     int x = 1;
      4     double y = x++ - x*3;
      5     System.out.println(y);

    A. -2.0
    B. -2
    C. -5
    D. -5.0
    E. -4
    F. compiler error at line 4

    A: D
    Explain: double y = x++ - x*3; is equivalent to double y = (x++) - (x*3); Calculate from left to right, x++ return value 1, increase x to 2; x*3 returns 6; 1 - 6 is assigned to y. Since double y has higher precision than int 5, int is promoted to double. The output is -5.0.
    ======
  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     System.out.println(x > 5 ? x < 4 ? 3 : 1 : x == 1 ? -x : x);
      5   }
      6 }

    A. -1
    B. 1
    C. 3
    D. 1
    E. The code doesn't compile

    A: A
    Explain: The equivalent ternary operator expression is: (x > 5) ? (x < 4 ? 3 : 1) : (x == 1 ? -x: x). x > 5 is false, so x == 1 ? -x : x is executed. x == 1is true, -x is the return value, which is -1.
    ======
  31. Q:
  32. What is the output of the following code?
      1 public class Board{
      2   public static void main(String...args) {
      3     boolean b = false & true;
      4     boolean a = false ^ true || (b = true) | (3 > 2) | false;
      5     System.out.print(a);
      6     System.out.print(b);
      7   }
      8 }

    A. falsetrue
    B. truetrue
    C. falsefalse
    D. truefalse
    E. Compiler error at line 4
    F. Compiler error at line 5

    A: D
    Explain: line 3 assign false to b. According to operator precedence, logical operator have higher precedence than short-circuit logical operator. The right side is equivalent to (false ^ true) || ( (b = true) | (3 > 2) | false)). Calculate short-circuit from left to right, false ^ true is true, so the right side of || is skipped (no matter what's the value, the result will be true anyway). Variable a is assigned the value true. Since the right side of || is skipped, b = true is not executed, b remains false. Expression (b=true) is a valid syntax, it assign true to variable b, it returns value true. E is incorrect.
    ======
  33. Q:
  34. Given the following code, what is the right statements?
      1 public class Numbers{
      2   public static void main(String...args) {
      3     int a = 1;
      4     long b = 2;
      5     System.out.println(a == b);
      6     Double d = null;
      7     Float f = null;
      8     System.out.print(d == f);
      9     System.out.print(5.0f == 5.000);
     10   }
     11 }

    A. line 5 generate compile error.
    B. line 5 print out false.
    C. line 8 print out true.
    D. line 8 generate compile error.
    F.  line 9 print out true.
    G. None of the above.

    A: B, D, F
    Explain: when == is applied two numeric primitive types, they are automatically promoted, therefore A is incorrect, B and F are correct. When == is applied to two object reference variables, their type have to match, so C is incorrect and D is correct.
    ======
  35. Q:
  36. What is the output of the following code snippet?
      3     int a = 1, b = 3;
      4     boolean b = a >= 3;
      5     if(b = true) System.out.println("A");
      6     else System.out.println("B");

    A. A
    B. B
    C. line 3 generate compiler error
    D. line 4 generate compiler error
    E. None of the above

    A: A

    Explain: line 5 is a tricky, it is not b == true. b = true assign true to variable b, return value true. C is incorrect because multiple variables with same type can be initialized in the same statement. D is incorrect because boolean b= a >= 3; is equivalent to boolean b = (a>= 3);

    Study: 
    ======
  37. Q:
  38. What's the output of the following program?
      1 public class Test{
      2   public static void main(String...args) {
      3     int i = 0;
      4     OUTER: do{
      5       i++;
      6       for(int j = 1; j <= 3; j++) {
      7         if(j + i % 2 == 2) continue OUTER;
      8         System.out.print(j);
      9       }
     10     }while(i < 3);
     11   }
     12 }

    A. 1
    B. 2
    C. 123
    D. 123123
    E. 12
    F. The code won't compile due to line 7.

    A: A
    Explain: trace the loop. First while loop, i++ set i to 1. For loop first round, j = 1, j + i % 2 = 1 + 1 = 2, 2 == 2 evaluates to true, continue to OUTER. i's value is 1, i++ set i to 2. For loop first round, j = 1, j + i % 2 = 1, 1 == 2 evaluates to false, line 8 print 1. Next while loop, i's value is 2, i++ set it to 3. 1 + 3 % 2 = 2, continue to OUTER. i's value is 3, i<3 is false, since the do-while already ran more than once, the loop exits.
    ======
  39. Q:
  40. What is the output of the following code snippets?
      3     String day = "Monday";
      4     switch(day) {
      5       case "Sunday":
      6       default:
      7         break;
      8       case "Sunday": System.out.print("Sunday");
      9       case "Monday": System.out.print("Monday");
     10       case "Tuesday": System.out.print("Tuesday");
     11       case "Otherday": System.out.print("Otherday");
     12     }

    A. Monday
    B. Tuesday
    C. MondayTuesdayOtherday
    D. no output
    F. The code doesn't compile due to line 5
    G. The code doesn't compile due to line 6

    A: C
    Explain: default don't have to be the last block in switch statements. A case can optionally have statements. When switch found a match, it execute downward until meet a break statement or exausted all the case blocks underneath 

    Study: 
    ======
  41. Q:
  42. What is the output of the following code?

      1 public class Test{
      2   public static void main(String...args) {
      3     int sum = 10;
      4     String name = "apple";
      5     String total = sum + 1;
      6     System.out.println(total + " " + name);
      7     System.out.println(sum + " " + 1 + name);
      8   }
      9 }

    A. 11 apple
    B. 10 1apple
    C. 11
    D. 10
    E. The code does not compile

    A: E
    Explain: the line 5 generate compiler error, can not assign int to String. If line 5 is int total = sum + 1; the result will be A and B.
    ======
  43. Q:
  44. Which of the following statements are true?


    A. An immutable object cannot be modified
    B. An object with only final variables is immutable.
    C. String is immutable
    D. StringBuilder is immutable
    E. ArrayList is immutable

    A: A, B, C

    Explain: Immutable means the state of an object can not change once it is created. String is immutable, during String concatenation, a new String is created, and the reference of the new object is returned. StringBuilder is mutable, the content can change. ArrayList is mutable, both its size and contents can change.

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

    A. ab3
    B. ba3
    C. ab
    D. ba
    E. The code doesn't compile

    A: D
    Explain: after line 4, the content is 123; after line 5, the content is 3; after line 6, 3aa; after line 7, 3abba. sb.substring(3) is ba.
    ======
  47. Q:
  48. 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(s == s);
      8     System.out.print(s == s1);
      9     System.out.print(s == sb);
     10    System.out.print(s1 == sb);

    A. truefalsefalsefalse
    B. truetruefalsefalse
    C. truetruetruetrue
    D. truefalsefalsetrue
    E. The code doesn't compile

    A: E
    Explain: Line 9 and line 10 generate compiler error, since == can not be applied to different object type String and StringBuffer. If s == sb.toString() and s1 == sb.toString() is used, the result will be A.
    ======
  49. Q:
  50. What is the output of the following code?

      4     String s = "table";
      5     StringBuilder sb = new StringBuilder("chair");
      6     s.concat(sb.toString());
      7     sb.append(s);
      8     System.out.print(s + sb.toString());

    A. tablechairchairtable
    B. tablechairtable
    C. tablechairtablechair
    D. tablechair
    E. The code doesn't compile

    A: B
    Explain: String is immutable, line 6 didn't change the content of s. 
    ======
  51. Q:
  52. What are the output of the following code?
    System.out.println("abcde".length());
    System.out.println(new String("abcde").charAt(2));
    System.out.println(new StringBuilder("abcde").deleteCharAt(2).charAt(4));

    A. 5
    B. 4
    C. c
    D. b
    E. e
    F. An exception is throw
    H. The code doesn't compile

    A: A, C, F

    Explain: A is correct, because String's method length() returns 5. C is correct because the charAt(2) returns the char at index 2. F is correct because StringBuilder object's length is 5 at beginning, deleteCharAt(2) decrease the length to 4. charAt(4) try to get char at index 4, which throw 
    java.lang.StringIndexOutOfBoundsException.
    Study: 
    ======
  53. Q:
  54. What's the output of the following code snippets?
      5     String s = new String("1234567   ");
      6     s.trim();
      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: F
    Explain: deleteCharAt() and insert() are StringBuilder's methods not String's methods.
    ======
  55. Q:
  56. 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: A, C
    Explain: String is immutable, invoke String functions doesn't change the original string. A and C is correct. s.replace() have overloaded methods String replace(int a, int b) and String replace(char a, char b), D is incorrect.
    Study: http://xyzcode.blogspot.com/2016/03/creating-and-manipulating-strings.htm
    ======
  57. Q:
  58. What is the output of the following code?
      4     StringBuilder sb = new StringBuilder("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: A
    Explain: abcdefg --> abcdefg- --> abc0defg- --> abc0def- --> -fed0cba
    ======
  59. Q:
  60. Which of the array declarations are legal?


    A. String[][] a = new String[2][];
    B. Object[] a[] = new Object[2][3];
    C. int a[][][] = new int[1][2][];
    D. boolean[] a[][] = new boolean[1][][];
    E. java.util.List[] a = new java.util.ArrayList[2];

    A: A, B, C, D, E

    Explain: When declaring a multiple dimension array, you have to give initial value or specify the size of the first dimension. The [] can follow type name or variable name. A, B, C, D are all correct. E is an array of type List. java.util.List is an interface, java.util.ArrayList implements java.util.List, so there won't be compiler error. E is correct.


    Study: , http://xyzcode.blogspot.com/2016/03/declare-instantiate-initialize-and-use_12.html, 
    ======
  61. Q:
  62. Which of the following statements compile?

    A. char[] a = new char[2]; int l = a.length;
    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: A, D

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

    Study: 
    ======
  63. Q:
  64. Which of the following are true?


    A. An array has fixed size.
    B. An array's initial value have to be supplied in declaration statement.
    C. An ArrayList have an initial capacity.
    D. An ArrayList's size can increase.
    E. An array is immutable.

    A: A, C, D

    Explain: An array has fixed size. When an array is created without initial value, default values are filled. An array's contents can change, so it is not immutable. A is correct, B and E are incorrect. An ArrayList have initial capacity and the size can increase at runtime. C and D are correct.

    Study: 
    ======
  65. Q:
  66. What is the output of the following code snippets?

      6     System.out.print(new int[0] == new int[0]);
      7     System.out.print(new ArrayList().equals(new ArrayList()));
      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: Two arrays with the same content are not equal. Since ArrayList override the equals() method, two ArrayList with the same contents are equal. 

    Study: 
    ======
  67. Q:
  68. 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(1,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: B
    Explain: After line 5, a contains 2; after line 6, a contains 2,3; after line 7, a contains 2,0; after line 8, a contains 0.

    Study: 
    ======
  69. Q:
  70. What is the result of the following code?
      4     List<Integer> list = Arrays.asList(10, 4, -1, 5);
      5     Collections.sort(list);
      6     Integer array[] = list.toArray(new Integer[4]);
      7     System.out.println(array[0]);

    A. -1
    B. 10
    C. compile error at line 4
    D. compile error at line 6
    E. None of the above

    A: A
    Explain: Arrays.asList convert an array to an backup List (not ArrayList), after sort, the order is -1, 4, 5, 10. ArrayList's toArray() method convert an List to array with the same size. 
    Study: 
    ======
  71. Q:
  72. Which of the following statements create a new date of 4/15/2016?


    A. LocalDate.of(2014, 4, 15);
    B. new LocalDate(2014, 4, 15);
    C. new Date(2014, 4, 15);
    D. new LocalDate(2014, Calendar.APRIL, 15);
    E. LocalDate.of(2014, Calendar.APRIL, 15);
    F. LocalDate.of(2014, Month.APRIL, 15);

    A: A, F

    Explain: LocalDate don't have a constructor, it use static method of(year, month, day) to create new date. Month.APRIL creates the month we need.

    Study: 
    ======
  73. Q:
  74. What is the output of the following code?

     1 import java.time.*;
      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: A
    Explain: getYear(), getMonth() and getDayOfMonth() returns the corresponding number.
    ======
  75. Q:
  76. What is the output of the following code?
      1 import java.time.*;
      2 public class Test{
      3   public static void main(String...args) {
      4     LocalDateTime l = LocalDateTime.of(2015, 3, 15, 50, 100, 100);
      5     System.out.println(l.getYear() + " " + l.getMonth() + " " + l.getDayOfMonth());
      6   }
      7 }

    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: The code compiles, but when running, it throw java.time.DateTimeException: Invalid value for HourOfDay (valid values 0 - 23): 50.
    ======
  77. Q:
  78. 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.ofLocalizedDateTime(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. The code doesn't compile
    F. The code throw exception

    A: C
    Explain: LocalDateTime  is immutable, plusYears() and plus() returns a reference variable pointing to a new LocalDateTime object. 
    ======
  79. Q:
  80. 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     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.ofLocalizedDateTime(FormatStyle.SHORT);
     10     System.out.println(l.format(f));
     11   }
     12 }

    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. The code doesn't compile
    F. The code throw exception

    A: C
    Explain: LocalDateTime  is immutable, plusYears() and plus() returns a reference variable pointing to a new LocalDateTime object. 
    ======
  81. Q:
  82. What is the output of the following code?

      5     LocalDate d = LocalDate.parse("2000-01-01", DateTimeFormatter.ISO_LOCAL_    DATE);
      6     d = d.plusYears(2);
      7     d = d.plusMonths(1);
      8     d = d.plusDays(1);
      9     DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate(FormatStyle.SHOR    T);
     10     System.out.println(f.format(d));

    A. 2/2/02
    B. 1/1/00
    C. 2/2/2002
    D. 02/02/2002
    E. The code doesn't compile
    F. The code throw exception
    G. None of the above

    A: A
    Explain: LocalDate  is immutable, plusYears() and plusMonths() and plusDays() returns a reference variable pointing to a new LocalDate object. 
    ======
  83. Q:
  84. What is the output of the following code?
      1 import java.time.*;
      2 public class Test{
      3   public static void main(String...args) {
      4     DateTimeFormatter f = DateTimeFormatter.ofPattern("MM dd yyyy");
      5     LocalDate t = LocalDate.parse("03 10 2011", f);
      6     t.plusDays(30);
      7     System.out.println(f.format(t));
      8   }
      9 }

    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: F
    Explain: The code doesn't compile because it missed import java.time.format.*; If import java.time.format.* is added, E will be the answer, line 6 won't throw exception, it is a valid syntax. The returned reference didn't assign to t.
    ======
    A:
    Which of the following code compiles?


    A. public class Test {final void method() {}}
    B. public class Test {void method() {}}
    C. class Test{private String Test() {return "";}}
    D. class Test{boolean Test() {} }
    E. class Test{private Test() {}}
    F. class Test{default void method(){}}

    A: A, B, C, E

    Explain: A is correct because final is an optional specifier, it is allowed before return type. B is correct because default access modifier is allowed before return type void. C is correct because private access modifier is allowed before return type String and a string is returned in method body. It is ok to have a method with the same name as class name. D is incorrect because the method have no return statement. E is correct because private Test() is a constructor, it don't need return type. F is incorrect because default is not a keyword for method access modifier.

    Study: 
    ======
  85. Q:
  86. Which of the following methods compile?

    A. public int method() {return 1L;}
    B. private int method() {return 9.0;}
    C. void method() {return;}
    D. public void method() {return null;}
    E. public int method() {return null;}
    F. public Integer method() {return null;}

    A: C, F

    Explain: A is incorrect, it will have compiler error: incompatible types: possible lossy conversion from long to int. B is incorrect, because of error: incompatible types: possible lossy conversion from double to int. C is correct because return; statement returns without a type. D is incorrect because return type void can not have any return including null. The error: incompatible types: unexpected return value. E is incorrect, because error: incompatible types: <null> cannot be converted to int. F is correct because null is a legal return value for Integer object.

    Study: 
    ======
  87. Q:
  88. Which method declaration followed javaBeans requirements?

    A. public boolean getCanFly { return canFly;}
    B. private boolean isCanFly {return canFly;}
    C. public boolean isCanFly {return canFly;}
    D. public String getName {return name;}
    E. protected String getName {return name;}
    F. public void setScore(int score} {this.score = score;}
    G. public void setPass(boolean pass) {this.pass = pass;}

    A: C, D, F, G

    Explain: javaBean use private variables and public getter and setter. B, E is incorrect. When return type is boolean, getter need to use is<VariableName>, A is incorrect.

    Study: 
    ======
  89. Q:
  90. 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 = new Test();
     19     System.out.print(count);
     20     Test.add();
     21     System.out.println(count);
     22   }
     23 }

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

    A: C
    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 called, and the constructor is called, the count is 3. When executing line 20, the static initializer no longer get called, count is 4.
    ======
  91. Q:
  92. 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 int count = 0;
     22 }

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

    A: A
    Explain: count is an instance variable, t1.count increased once and t2.count increased twice. Test have an instance initializer, but it never get called since we didn't create new Test().

    ======
  93. Q:
  94. 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 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     c="c";
     17     System.out.println("a="+a+",b="+b+",c="+c+",d="+d);
     18   }
     19 }

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

    A: B, C
    Explain: line 16 don't compile because c is final. If remove line 16, the C is the answer. 
    ======
  95. Q:
  96. Which imports are needed to make the following code compile?
    public class Test{
      public void method(List<String> list) {
        sort(list);
      }

    }

    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. static import java.util.Arrays.*;
    G. static import java.util.Collections.*;
    H. The code compile as it is.

    A: C, E
    Explain: sort is a static method of class Collections. In order to access it without class name, import static java.uti.Collections.*; is needed. Collections.sort are applied to ArrayList and List but not to array, Arrays.sort is applied to array but not List and ArrayList. In order to access List interface, import java.util.*; is needed.

    Study: 
    ======
  97. Q:
  98. 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   static 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: C
    Explain: 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.
    ======
  99. Q:
  100. 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.append(a);
      6   }
      7   public static void main(String...args) {
      8     Test t = new Test();
      9     StringBuilder sb = new StringBuilder("result is ");
     10     int a = 10;
     11     t.add(sb, a);
     12     System.out.println(sb.toString() + ", a=" + a);
     13   }
     14 }

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

    A: A
    Explain: When object is method parameter, the reference 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);
    ======
  101. Q:
  102. Which of the following classes compile and use a default constructor?

    A. public class Test {}
    B. public class Test {public Test() {}}
    C. public class Test {public void Test(){}}
    D. public class Test {public Test(int a) {this();}}
    F. public class Test {private Test(){System.out.println();}}
    G. public class Test {public Test() {this();}}

    A: A, C

    Explain: default constructor only exists when there is no constructor for a class. B, D, F, G is incorrect. C is correct because it has a method with the same name as the class name, but it don't have constructor, so default constructor is used. D won't even compile because this(); is trying to call default constructor but it is not exist, thus have error: constructor Test in class Test cannot be applied to given types; . G won't compile neither, the error: constructor Test() is already defined in class Test.

    Study: 
    ======
  103. Q:
  104. 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) {this(a, 2); System.out.print(1);}
      4   public Test() {this(2); System.out.println(0);}
      5   public static void main(String ...args) {Test t = new Test();}
      6 }

    A. 012
    B. 210
    C. 222
    D. no output
    E. not compile
    F. throw exception

    A: B
    Explain: line 5 calls the constructor with 0 parameter, which calls the constructor with 1 parameter, which calls the constructor with 2 parameter. Line 2 print 2 before return, then line 3 print 1 before return, then line 4 print 0 before return.
    ======
  105. Q:
  106. What is the output of the following code?
      1 public class Test{
      2   public Test(int a) {this(a, 2); System.out.print(1);}
      3   public Test() {System.out.println(0); this(2);}
      4   public static void main(String ...args) {Test t = new Test();}
      5 }

    A. 01
    B. 10
    C. 0
    D. 1
    E. not compile
    F. throw exception

    A: E
    Explain: line 3 doesn't compile, it use this(2); to call another constructor, the call have to be the first statement in the Test() constructor body.
    ======
  107. Q:
  108. What is the output of the following code?
      1 public class Test{
      2   static 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: B
    Explain: 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.
    ======
  109. Q:
  110. 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, t->t.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: E
    Explain: The code is incorrect. Line 9 try to create a lambda expression that returns the 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. However, the variable used in lambda expression conflict with local variable t. We got error: Variable t is already defined in method main(String...). Line 4 uses a Predicate interface, which declares a test() method. If line 9 is t.method(t, t1->t1.isPass()); the answer will be A.
    ======
  111. Q:
  112. What is the output of 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 level = 1; int limit = 10; return le<li;}, 6, 5);
     15   }
     16 }

    A. continuestopcontinue
    B. continuestopstop
    C. stopcontinuestop
    D. not compile
    E. throw exception

    A: B
    Explain: Interface FillCup consumes a lambda with two int parameters, line 12, 13, 14 are all valid lambda expressions. Line 12 omitted the optional parameter type and return keyword with braces. Line 13 uses the optional parameter type and return keywords inside the braces with semicolon. Line 14 defines two irrelevant variables inside lambda body, which is useless but allowed. import java.util.function.*; is not needed because the code supply its own interface instead of using Predicate interface.
    ======
  113. Q:
  114. Which lambda can replace the Predicator class to return the same value at line 9?
      1 import java.util.function.*;
      2 public class Test {
      3   public void print(Test t, Predicate<Test> p) {
      4     System.out.println(p.test(t));
      5   }
      6   public static void main(String...args) {
      7     Test t = new Test();
      8     Predicator p = new Predicator();
      9     t.print(t, p);
     10   }
     11 }
     12 class Predicator implements Predicate<Test>{
     13   public boolean test(Test t) {
     14     return true;
     15   }
     16 }

    A. t.print(t, (m) -> true);
    B. t.print(t, m -> true);
    C. t.print(t, (Test m) -> true);
    D. t.print(t, (m) -> {return true;});
    E. t.print(t, (Test m) -> {return true;});
    F. t.print(t, (m) -> {int a = 0; return true;});
    H. t.print(m -> true);

    A: A, B, C, D, E, F
    Explain: Predicator implements Predicate interface

    public interface Predicate<T> {
      boolean test(T t);
    }
    A lambda expression with single parameter list and returns a boolean will satisfy. F is incorrect because print expect 2 parameters, it failed to supply the first parameter.
    ======
  115. Q:
  116. Given the following code, what statements are true?
      1 public class Test {
      2   public int score = 0;
      3   public Test(int score) {this.score = score;}
      4   public static void main(String...args) {
      5     Test t = new Test(70);
      6     System.out.println(t.score);
      7   }
      8 }
      9 class Test1 extends Test{
     10   public Test1() {
     11     super(10);
     12     super.score = 80;
     13   }
     14 }

    A. The code doesn't compile
    B. run "java Test" output 70
    C. run "java Test1" output 80
    D. run "java Test1" have no output
    E. run "java Test1" throws exception
    F. run "java Test1" output 70 

    A: B, F
    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.
    ======
  117. Q:
  118. which of the following statements can be inserted in the blank line so that the code will compile successfully?

    public interface Changeable{}
    public class Plan implements Changeable {
      public static void main(String ... args) {
        __ plan = new Strategy();
      }
    }
    public class Strategy extends Plan{}
    public class Schema extends Plan{}

    A. Changeable
    B. Strategy
    C. Schema
    D. Plan
    E. Object
    F. Integer

    A: A, B, D, E

    Explain: Any class or interface that is a supertype of Strategy will be ok. C is incorrect because Schema is not a superclass of Strategy.

    Study: 
    ======
  119. Q:
  120. 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 drink() {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: B
    Explain: line 2 is an interface method with default implementation, line 5 override the default implementation.
    ======
  121. Q:
  122. 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   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: C
    Explain: Line 6 will generate compile error attempting to assign weaker access privileges; was public. If add public modifier at line 6, the answer is A. 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.
    ======
  123. Q:
  124. Which of the following statements about polymorphism are true?

    A. A reference to an object may be cast to a superclass of the object without an explicit cast.
    B. If a method takes an object as parameter, then any subclass's objects  may be passed as a parameter to the method.
    C. A method that takes a parameter with type java.lang.Object will take any reference.
    D. All cast exceptions can be detected at compile-time.
    E. a public instance method can be overridden in a subclass and calls to it will be replaced even in the superclass it was defined.

    A: A, B, C, E

    Explain: D is incorrect, some cast exceptions can only be detected at run time.

    Study: 
    ======
  125. Q:
  126. Which of the following is true?

    A. A concrete class implementing an interface must implement all methods declared in the interface.
    B. A concrete subclass must implement all inherited abstract methods.
    C. A class must implement all inherited abstract methods.
    D. A concrete subclass cannot be marked as final.
    E. A subclass can not inherit static methods defined in superclass.

    A: B

    Explain: A is incorrect because methods declared in the interface can be static interface methods or default interface methods, in either case, the concrete class don't have to implement these methods. C is incorrect because abstract class don't have to implement all inherited abstract methods, only concrete subclass have to. D is incorrect because concrete subclass can be marked as final, only abstract class can not be marked as final. E is incorrect because subclass can inherit or hide non-private static methods defined in superclass.

    Study: 
    ======
  127. Q:
  128. 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 1.
    C. The code will not compile because of line 2.
    D. The code will not compile because of line 4.
    E. The code will not compile because of line 5.
    F. The code will not compile because of line 8.

    A: A
    Explain: abstract can define 0 abstract method and 0 or multiple non-abstract method. Student defined a concrete method test, which is overriden by subclass Test.
    ======
  129. Q:
  130. What is the output of the following code?
      1 abstract class Fish {
      2   private void swim() {System.out.print("swim fish");}
      3   public static void main(String... args) {
      4     Fish f = new Trout();
      5     f.swim();
      6   }
      7 }
      8 public class Trout extends Fish {
      9   public void swim() {System.out.print("swim Trout");}
     10 }

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

    A: A
    Explain: superclass Fish have a private method, which can not be overridden by subclass Trout. Polymorphism does not apply here. Answer is A.
    ======
  131. Q:
  132. Which of the following states about try-catch-finally are true?


    A. When there is no catch blocks for a try statement, a finally block must be used.
    B. When there are catch blocks for a try statement, multiple try blocks can be used.
    C. When there are multiple catch blocks, broader exception type must appear before the narrower exception types.
    D. At most only one catch block can be executed.
    E. finally block is always executed, whether or not an exception occurs in the try block. 

    A: A, B, D, E

    Explain: there should be at least one catch block or finally block for a try block. multiple catch blocks can be used for a try block, narrower exception type should go first, otherwise, broader exception type catches the exception first, narrower exceptions are unreachable. At most only one catch block can be executed, finally block is always executed, whether or not an exception occurs in the try block.

    Study: 
    ======
  133. Q:
  134. Which exception will the following throw?
    Object obj = new Boolean(true);
    String s = (String)obj;
    System.out.println(s);

    A. ArrayIndexOutOfBoundsException
    B. ClassCastException
    C. IllegalArgumentException
    D. NumberFormatException
    E. The code doesn't compile
    F. None of the above

    A: B

    Explain: The code compiles, however at run time, an exception is thrown at the second line: java.lang.ClassCastException: java.lang.Boolean cannot be cast to java.lang.String.

    Study: 
    ======
  135. Q:
  136. What is the output of the following code?
      1 import java.io.*;
      2 public class Test {
      3   public void method() throws IOException{
      4     System.out.print("A");
      5     try {
      6       System.out.print(1/0);
      7     } catch (ArithmeticException ae) {
      8       System.out.print("B");
      9       throw new 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. ABCE
    C. ABDE
    D. The code does not compile
    E. ABD then stack-trace of IOException
    F. AB then stack-trace of IOException

    A: C
    Explain: Line 6 throw ArithmeticException, which is caught by line 7. After print B, it throws IOException. The finally block is executed anyway. The IOException throw out of method, line 19 catches it, print E before exit.
    ======
  137. Q:
  138. What is the output of the following code?
      1 public class Test {
      2   public String name;
      3   public void method() {
      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 RuntimeException();
     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("E");
     21   }
     22 }

    A. ABCDE
    B. ABDE
    C. ABD followed by stack-trace
    D. ACDE
    E. The code does not compile

    A: D
    Explain: Name is not initialized, its value is null, line 6 throw NullPointerException, which is caught at line 11. Finally block is executed anyway. Then program exit before print E.
    ======
  139. Q:
  140. Which of the following code can replace //INSERT CODE HERE to make the code compile?

    public void fun() throws IOException {
    // INSERT CODE HERE
    }

    A. String a = null;
    B. int i = 2/0;
    C. throw new Exception();
    D. throw new Error();
    E. throw new java.io.IOException();
    F. throw new IllegalArgumentException();

    A: A, B, D, E, F

    Explain: checked exceptions have to be caught or declared. C is incorrect, because Exception is neither caught nor declared. A is correct because it is ok to not throw any exception. Neither Error nor RuntimeException have to be caught or declared. B is correct because it throws ArithmeticException which is a subclass of RuntimeException. D is correct. E is correct because IOException is declared in method signature. F is correct because IllegalArgumentException is a subclass of RuntimeException.

    Study: http://xyzcode.blogspot.com/2016/04/differentiate-among-checked-exceptions.html
    ======
  141. Q:
  142. 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 Exception;
      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

    Explain: When implementing interface methods that throws checked exception, the class method can choose to throw subclass exceptions, don't throw exception, throw unchecked exception or throw Error. E is incorrect, because it get error: overridden method does not throw Throwable. F is syntax error.

    Study: http://xyzcode.blogspot.com/2016/04/differentiate-among-checked-exceptions.html,
    ======
  143. Q:
  144. What is the output of the following code?
      1 import java.util.*;
      2 public class Test {
      3   public void print(int a) {
      4     if(a > 0) String s = "positive int";
      5     else Sting s = "negative int";
      6     System.out.print(s);
      7   }
      8   public void print(byte a) {
      9     if(a > 0) String s = "positive byte";
     10     else Sting s = "negative byte";
     11     System.out.print(s);
     12   }
     13   public static void main(String...args) {
     14     Test t = new Test();
     15     byte a = 1;
     16     t.print(a--);
     17   }
     18 }


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

    A: F
    Explain: String s is a local variable, it can can not be accessed outside of if else blocks.
    ======
  145. Q:
  146. 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((s, l) -> 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: 
    ======
    Question: which of the following compile?

    A. int[] intArray = new int[]{1,2,3};
    B. int[] intArray = {1,2,3};
    C. int intArray[] = new int[3];
    D. int intArray[]; intArray = new int[3];
    E. int [] intArray; intArray = new int[]{1,2,3};
    F. int [] intArray; intArray = {1,2,3};

    A: A, B, C, D, E

    Explain: [] can be placed before and after variable name, there are 3 ways of specifying initial values: new int[]{1,2,3}, new int[3], and {1,2,3}. The {1,2,3} can only be used in declaration, so F is incorrect.

    Study: 
    ======
  147. Q:
  148. 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   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: D
    Explain: interface can inherit multiple interfaces. Interface method have default access modifier public, at line 9, the abastract method getScore is overriden. However the access modifier is default, which is less accessible. 
    ======
  149. Q:
  150. Which of the following statements are true?

      1 package com.a.company;
      2 import java.lang.*;
      3 import java.util.*;
      4 public class Test {
      5   int a;
      6   int methodA() {return 1;}
      7 }

    A. if line 1 is removed, the code still compile.
    B. if line 2 is removed, the code still compile.
    C. if line 3 is removed, the code still compile.
    D. if line 4 is removed, the code still compile.
    E. if line 5 is removed, the code still compile.
    F. if line 6 is removed, the code still compile.

    A: A, B, C, E, F
    Explain: package declaration is optional, java.lang.* is imported by default, java.util.* classes didn't get used in the program, a class can have 0 instance variable and 0 method. 
    ======
  151. Q:
  152. What's the output of "java Test"?
      1 class TestBase {
      2   public TestBase() {System.out.print("a");}
      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: B
    Explain: Test inherit main method from TestBase, C is not correct. The code compile as it is, D is incorrect. In main method, new Test(); is called. The line 8 calls line 6, which by default calls super() as the first constructor statement. 
    ======
  153. Q:
  154. What is the output of the following code?
      1 public class Test {
      2   static {System.out.print("a");}
      3   public Test() {System.out.print("b");}
      4   {System.out.print("c");}
      5   public static void main(String...args) {
      6     new Test();
      7     {System.out.print("d");}
      8   }
      9 }

    A. abcd
    B. cabd
    C. acbd
    D. cda
    E. The code doesn't compile

    A: C
    Explain: static initializer called first, then instance initializer, then constructor, finally the line 7. In line 7 the {} around print statement is useless but legal syntax.
    ======
  155. Q:
  156. With the following code, what is the output of command "java Test Test Pass"?

      1 public class Test {
      2   public static 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: D
    Explain: "java Test Test Pass" have 2 program parameters, the first Test is the class name. 
    ======
  157. Q:
  158. What import statements are needed in line 1 and 2 to make the following code compile?
      1 ______;
      2 ______;
      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. import java.time.*;
    B. import java.time.LocalDate;
    C. import java.time.format.*;
    D. import java.time.format.DateTimeFormatter;
    E. import java.time.DateTimeFormatter;
    F. import java.util.LocalDate;
    G. import java.date.*;
    H. import java.date.format.*;

    A. A, B, C, D
    Explain: java 8 LocalDate is in package java.time, DateTimeFormatter is in package java.time.format.
    ======
  159. Q:
  160. 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=0;
      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: B
    Explain: at line 3, a is 1, b undefined, c is 0. At line 4, a is 2, b is 1, c is 0. At line 5, a is 2, b is 2, c is 1.
    ======
  161. Q:
  162. 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

    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.
    Study: 

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

      1 public class Test {
      2   public static void main(String...args) {
      3     for(int i=0; i< 5; i++) {
      4       System.out.print(1);
      5       if(i<3) continue;
      6       else break;
      7     }
      8   }
      9 }

    A. 1
    B. 11
    C. 111
    D. 1111
    E. 11111
    F. don't compile

    A: D
    Explain: When i is 0, 1, 2, continue is executed, when i is 3, after print 1, break is executed, the program exits.
    ======
  165. Q:
  166. 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     this("", score);
      6     score = 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: B
    Explain: line 6 and 9 didn't do anything, it assign local variable score to itself, the instance variable score didn't change, it still have default value 0. 
    ======
  167. Q:
  168. Which of the following can overload method public void hello() {}

    A. private void hello(String a) {}
    B. public void hello(int a) {}
    C. protected void hello() {System.out.println();}
    D. private static final void hello(int ... args) {}
    E. String hello() {return null;}

    A: A, B, D

    Explain: Methods in the same class with same name but different parameters are called methods overloading. A, B, D are correct.  C is incorrect because it has the same name and parameters as public void hello() {}. E is incorrect because it has the same name and parameters as public void hello() {}.

    Study: 
    ======
  169. Q:
  170. 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: A
    Explain: a ^ b only true when a, b are different. (yellow = " is the color") is an assignment operation, it have value " is the color".
    ======
  171. Q:
  172. what is the output of the following code?



      1 public class Test {
      2   Test t = new Test();
      3   public static void 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: D
    Explain: line 2 is an instance initializer which call constructor. constructor create a new instance which again calls line 2.
    ======
  173. Q:
  174. 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() {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: B, C, D
    Explain: finalize() method is called with garbage collection happens. 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.
    ======
  175. Q:
  176. 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   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: A
    Explain: line 2 declared a public static final int Time = 180; interface variable, line 3 declared a public abstract void doTest(); interface method.
    ======
    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: D
    Explain: This is a 4x4 array, line 12 defines the array's element values.
    Study: http://xyzcode.blogspot.com/2016/03/declare-instantiate-initialize-and-use_12.html
    ======
  177. Q:
  178. Which of the following statements compile?



    A. throw new NullPointerException();
    B. throw new StackOverflowError();
    C. throw new ArrayIndexOutOfBoundsException();
    D. throws new StackOverflowException();
    E. throws new IOException();

    A: A, B, C
    Explain: keyword throw is used when throw a new Throwable object, keyword throws is used when declare throwable in method signature, NullPointerException, StackOverflowError, ArrayIndexOutOfBoundsException, IOException exist in java.
    ======
  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     List l = new ArrayList();
      5     l.add(true);l.add(2);l.add(1);l.add(0);
      6     l.remove(new Boolean(true));
      7     l.remove(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. truetruefalsefalse
    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 7 is tricky, because List have overloaded remove method that accept both Integer and int, when int is supplied, it act as index. l.remove(0) removed the first array element Integer(2) instead of the 3rd element Integer(0).
    ======
  181. Q:
  182. What is true about the following code?

      1 abstract class SomeTest {
      2   abstract Object doTest();
      3 }
      4 public abstract class Test extends SomeTest{
      5   int doTest() {return 0;}
      6   private void doTest(boolean a) {}
      7   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: A, C
    Explain: SomeTest defined an abstract doTest with return type Object. Line 5 is an override of doTest, however, return type int is not compatible with Object. 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 have method body. Line 8 is a correct override of doTest, Integer is a subclass of Object.
    ======
  183. Q:
  184. 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.ofLocalizedDate(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: B
    Explain: 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. 
    ======
  185. Q:
  186. 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);
      6     Period p = Period.of(1, 1, 1);
      7     d = d.minus(p);
      8     DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG);
      9     System.out.println(f.format(d));
     10   }
     11 }

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

    A: F
    Explain: Line 5 does not compile because the date parameter is missing. If that is corrected, the answer will be D. 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. 
    ======
  187. Q:
  188. Which of the following are always thrown by programmer?

    A. NullPointerException
    B. IOException
    C. NumberFormatException
    D. ArrayIndexOutOfBoundsException
    E. ClassCastException
    F. ExceptionInInitializerError

    A: B, C

    Explain: all throwable can be thrown by programmer, however, IOException and NumberFormatException are not thrown by JVM, they are generated by java program code; NullPointerException ArrayIndexOutOfBoundsException, ClassCastException, ExceptionInInitializerError are generated by JVM.

    Study: 
    ======
  189. Q:
  190. 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     for(String a: list)
      8       System.out.print(a);
      9   }
     10 }

    A. ab
    B. abc
    C. ac
    D. the code does not compile
    E. the code throw exception

    A: C
    Explain: Arrays.asList created a List backed by the original array. The list content can be modified, but the size can not change. Line 6 change the content to a and c, change the List also changes the original array.
    ======
  191. Q:
  192. Which of the following code compile?

    A. StringBuilder sb = new StringBuilder();
    B. StringBuilder sb = new StringBuilder(3);
    C. StringBuilder sb = new StringBuilder("a");
    D. StringBuilder sb = new StringBuilder(30L);
    E. StringBuilder sb = new StringBuilder(true);
    F. StringBuilder sb = new StringBuilder(4.0);

    A: A, B, C

    Explain: constructor of StringBuilder accept int, String and CharSequence as parameter. When int is used, the int value specify the initial capacity.

    Study: 
    ======
  193. Q:
  194. What is the output of the following code?
      1 import java.util.*;
      2 public class Test {
      3   void print(Double d) {System.out.print("D");}
      4   void print(int a) {System.out.print("I");}
      5   void print(Object o) {System.out.print("O");}
      6   public static void main(String...args) {
      7     Test t = new Test();
      8     t.print(1.);
      9     t.print(new Integer(0));
     10     t.print(10L);
     11   }
     12 }

    A. OOO
    B. DOO
    C. OII
    D. OIO
    E. The code does not compile
    F. The code throw exception

    A: B
    Explain: 1. convert to double, which is auto-boxed to Double when call void print(Double d). Line 9 don't have corresponding method except void print(Object o), Integer is not subclass of int or Double. Line 10 don't have corresponding method except void print(Object o), 10L has primitive type long, even though autobox into Long, it is not subclass of Double or int.
    ======
  195. Q:
  196. What is the output of the following code?
      1 class Estimate {
      2   public int getScore() {return 50;}
      3 }
      4 class Estimator extends Estimate {
      5   protected int getScore(int score) {return score;}
      6 }
      7 public class Test extends Estimator {
      8   public boolean isPass() {return true;}
      9   public static void main(String...args) {
     10     Estimator test = new Test();
     11     System.out.print(test.getScore());
     12     System.out.print(test.getScore(90));
     13     System.out.print(test.isPass());
     14   }
     15 }

    A. 9090true
    B. 5090ture
    C. code does not compile because of line 5.
    D. code does not compile because of line 8.
    E. code does not compile because of line 11.
    F. code does not compile because of line 12.
    G. code does not compile because of line 13.

    A: G
    Explain: line 5 is an overload of method getScore, since it is not a method overload, it is ok to have a less visible access modifier protected. The code does not compile, because at line 10, Test object is accessed via a reference of its super type Estimator. Estimator don't have access to method isPass() that is defined in its subclass.
    ======
  197. Q:
  198. Given the following code, what is the output of "java Test Hard Questions for your good"

      1 public static class Test {
      2   public static void main(String...args) {
      3     System.out.println(args[2]);
      4   }
      5 }

    A. Hard
    B. Test
    C. Questions
    D. for
    E. code does not compile
    F. code throw exception

    A: E
    Explain: Test.java:1: error: modifier static not allowed here
    ======
  199. Q:
  200. 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     Tester 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.
    ======