SCJP Sun Certified Java Programmer 2 — Questions and Answers
Question 1: What is the output of: int x = 5; System.out.println(x++ + ++x);
- 11
- 12 (Correct answer)
- 10
- 13
Correct answer: 12
x++ returns 5 (then x becomes 6), ++x increments x to 7 and returns 7, so 5+7=12.
Question 2: Which of the following correctly declares a two-dimensional array in Java?
- int[][] arr = new int[3][]; (Correct answer)
- int arr[][] = new int[][3];
- int[] arr[] = new [3][3]int;
- int arr = new int[3][3][];
Correct answer: int[][] arr = new int[3][];
Java allows the first dimension to be specified without the second in a 2D array declaration.
Question 3: Which access modifier allows a member to be accessible only within its own package and by subclasses?
- private
- public
- protected (Correct answer)
- default (no modifier)
Correct answer: protected
The protected modifier allows access within the same package and by subclasses in any package.
Question 4: What happens when a class implements two interfaces that declare the same default method without overriding it?
- The first interface's method is used
- A compilation error occurs (Correct answer)
- The second interface's method is used
- The method is ignored
Correct answer: A compilation error occurs
Java requires the class to override the conflicting default method; otherwise a compile-time error occurs.
Question 5: Which statement about the String.intern() method is correct?
- It creates a new String object always
- It returns a canonical representation from the string pool (Correct answer)
- It converts the string to uppercase
- It removes whitespace from the string
Correct answer: It returns a canonical representation from the string pool
String.intern() returns the canonical instance from the string pool, or adds it if absent.
Question 6: What is the result of 'instanceof' when applied to a null reference?
- Throws NullPointerException
- Returns true
- Returns false (Correct answer)
- Throws ClassCastException
Correct answer: Returns false
Using instanceof on a null reference always returns false without throwing an exception.
Question 7: Which of the following is true about static initializer blocks?
- They run each time an object is created
- They can throw checked exceptions freely
- They run once when the class is first loaded (Correct answer)
- They can access instance variables
Correct answer: They run once when the class is first loaded
Static initializer blocks execute exactly once when the class is loaded by the JVM.
What is the output of: int x = 5; System.out.println(x++ + ++x);