Sun Certified Java Programmer (SCJP) - Java SE 6 (CX-310-065) — Questions and Answers
Question 1: What happens when the following code is compiled? void test() { return; System.out.println("hello"); }
- It fails to compile due to unreachable code (Correct answer)
- It compiles and throws a RuntimeException
- It prints 'hello' because println is always executed
- It compiles and 'hello' is never printed
Correct answer: It fails to compile due to unreachable code
The Java compiler detects unreachable statements and reports a compile-time error. The `System.out.println` after an unconditional `return` can never execute, so the class will not compile.
Question 2: Which of the following is a correct way to create a new thread in Java?
- Extend Runnable class
- Extend Thread class or implement Runnable interface (Correct answer)
- Use the Process class
- Implement Callable interface only
Correct answer: Extend Thread class or implement Runnable interface
In Java, threads can be created by extending `Thread` or implementing `Runnable` and passing it to a `Thread` constructor.
Question 3: What is the correct syntax to create an instance of the non-static inner class `Inner` defined inside class `Outer`?
- Outer o = new Outer(); Outer.Inner i = o.new Inner(); (Correct answer)
- Outer.Inner i = Outer.new Inner();
- Outer.Inner i = new Outer.Inner();
- Inner i = new Inner();
Correct answer: Outer o = new Outer(); Outer.Inner i = o.new Inner();
A non-static inner class is tied to an instance of its enclosing class. You must first create an Outer instance, then use the `outerRef.new Inner()` syntax. The other forms are not valid Java.
Question 4: Which of the following creates a String object in the string pool?
- String s = new String("hello")
- String s = new String()
- String s = "hello" (Correct answer)
- new String("hello")
Correct answer: String s = "hello"
String literals (String s = "hello") are stored in the string pool, while using new String() always creates an object on the heap.
Question 5: What is the IS-A relationship in Java OOP?
- Composition
- Inheritance (Correct answer)
- Aggregation
- Encapsulation
Correct answer: Inheritance
The IS-A relationship is established through inheritance — a subclass IS-A type of its superclass.
Question 6: What does the following code print? outer: for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (j == 1) break outer; System.out.print(i + "" + j + " "); } } System.out.print("done");
- 00 01 02 done
- done
- 00 done (Correct answer)
- 00 10 20 done
Correct answer: 00 done
`break outer` terminates the entire outer for-loop when j==1. The only iteration that prints before that happens is i=0, j=0, producing '00'. Then j becomes 1, break outer fires, and execution jumps to the `System.out.print("done")` line.
Question 7: Which assignment causes a compile-time error?
- int i = 'A';
- float f = 100L;
- long l = 100;
- byte b = 100L; (Correct answer)
Correct answer: byte b = 100L;
Assigning a long literal to a byte requires an explicit cast because it is a narrowing conversion. long→byte cannot be done implicitly. The other assignments are widening conversions (int→long, long→float) or a char-to-int widening, all of which are implicit.
Question 8: Which of the following best describes the order in which a component is redrawn as a result of method calls?
- invoke paint() directly
- invoke repaint() which invokes update(), which in turn invokes paint() (Correct answer)
- invoke repaint() which invokes paint directly
- invoke update which calls paint()
Correct answer: invoke repaint() which invokes update(), which in turn invokes paint()
When a component needs to be redrawn, the `repaint()` method is typically invoked. This method does not draw directly but schedules an update request. The AWT event dispatcher then calls the `update()` method, which by default clears the component's background and then calls the `paint()` method to perform the actual drawing.
Question 9: Which statement about abstract classes in Java is TRUE?
- Abstract classes cannot have concrete methods
- Abstract classes cannot have constructors
- Abstract classes can be instantiated directly
- A class with at least one abstract method must be declared abstract (Correct answer)
Correct answer: A class with at least one abstract method must be declared abstract
If a class contains any abstract method, the class itself must also be declared abstract.
Question 10: What is the output of `System.out.println(1 + 2 + "3" + 4 + 5);`?
- 12345
- 3345 (Correct answer)
- 15
- 33 + 45
Correct answer: 3345
Evaluation is left-to-right. `1 + 2` = 3 (int addition), then `3 + "3"` = "33" (string concatenation), then "33" + 4 = "334", then "334" + 5 = "3345".
Question 11: What happens when you assign a larger numeric type to a smaller one without casting in Java?
- Java auto-narrows it
- Runtime exception
- Data is silently truncated
- Compile-time error (Correct answer)
Correct answer: Compile-time error
Narrowing conversions require an explicit cast; without one, the compiler produces an error.
Question 12: Which thread state indicates that a thread is eligible to run but waiting for CPU time?
- WAITING
- RUNNABLE (Correct answer)
- BLOCKED
- NEW
Correct answer: RUNNABLE
A thread in the `RUNNABLE` state is ready to execute and waiting for the CPU scheduler to assign it processor time.
Question 13: What is thread starvation in Java?
- A thread that never calls wait()
- A thread being perpetually denied CPU access due to other higher-priority threads (Correct answer)
- A thread waiting for I/O indefinitely
- A thread consuming too much memory
Correct answer: A thread being perpetually denied CPU access due to other higher-priority threads
Thread starvation occurs when a thread cannot gain regular access to shared resources because other threads are always prioritized.
Question 14: Can a non-static inner class declare static members?
- No, non-static inner classes cannot have any static members
- Yes, but only static final constant fields (Correct answer)
- Yes, it can declare both static fields and static methods
- Yes, but only static methods, not static fields
Correct answer: Yes, but only static final constant fields
In Java, a non-static inner class may declare static final constant fields (compile-time constants) but cannot declare other static members. This is because the inner class is associated with an outer instance and full static context would be ambiguous.
Question 15: What is the effect of casting a superclass reference to a subclass type when the actual object is of the superclass type?
- The cast succeeds and the object gains subclass methods
- Compile error
- ClassCastException at runtime (Correct answer)
- null is returned
Correct answer: ClassCastException at runtime
Downcasting a reference to a subclass type when the actual object is not of that subclass results in a ClassCastException at runtime.
Question 16: Which interface should be implemented to return a result from a thread's execution?
- Callable (Correct answer)
- Executor
- Runnable
- Thread
Correct answer: Callable
`Callable<V>` is similar to `Runnable` but its `call()` method returns a result of type V and can throw checked exceptions.
Question 17: Which class should you use to efficiently write characters to a file using a buffer?
- CharArrayWriter
- PrintWriter
- FileWriter
- BufferedWriter (Correct answer)
Correct answer: BufferedWriter
BufferedWriter wraps a Writer and uses an internal buffer to reduce I/O operations, improving performance.
Question 18: What is the role of the `Executor` framework in Java concurrency?
- It is used exclusively for scheduling periodic tasks
- It automatically detects and resolves deadlocks
- It provides a higher-level API for managing thread creation and execution (Correct answer)
- It replaces the synchronized keyword with a faster alternative
Correct answer: It provides a higher-level API for managing thread creation and execution
The `Executor` framework decouples task submission from thread management, enabling thread pooling and flexible execution policies.
Question 19: Which of the following is a valid way to restrict a generic method to only accept subtypes of Number?
- <T super Number> void method(T t)
- <T extends Number> void method(T t) (Correct answer)
- <? extends Number> void method(Number n)
- <T> void method(T t)
Correct answer: <T extends Number> void method(T t)
`<T extends Number>` is a bounded type parameter that restricts T to Number and its subclasses.
Question 20: An interface I declares a method m(). Class A implements I and provides m(). Class B extends A. Which statement is true about B?
- B must also implement m() explicitly
- B must re-declare that it implements I
- B inherits A's implementation of m() and satisfies the interface contract (Correct answer)
- B cannot extend A because A is concrete
Correct answer: B inherits A's implementation of m() and satisfies the interface contract
B inherits A's concrete implementation of m(), which satisfies the interface contract without B needing to redeclare it.
Question 21: What is the output of the following code? for (int i = 0; i < 5; i++) { if (i % 2 == 0) continue; System.out.print(i + " "); }
- 0 1 2 3 4
- 1 2 3 4
- 0 2 4
- 1 3 (Correct answer)
Correct answer: 1 3
`continue` skips the rest of the loop body for that iteration and moves to the next. When i is even (0, 2, 4), `continue` fires and the print is skipped. When i is odd (1, 3), the print executes. Output is '1 3'.
Question 22: Which of the following is true about abstract classes in Java?
- An abstract class cannot implement interfaces
- An abstract class must have at least one abstract method
- An abstract class cannot have constructors
- An abstract class can have both abstract and concrete methods (Correct answer)
Correct answer: An abstract class can have both abstract and concrete methods
An abstract class can contain any combination of abstract and concrete methods, and it can also have constructors.
Question 23: What identifiers are valid?
- r2d2
- _xpoints
- bBb$
- all of the above (Correct answer)
Correct answer: all of the above
In Java, identifiers (names for variables, methods, classes, etc.) must adhere to specific rules. They must start with a letter, an underscore (`_`), or a dollar sign (`$`). Subsequent characters can include letters, digits, underscores, or dollar signs. All the given options—`r2d2`, `bBb$`, and `_xpoints`—follow these rules, making them valid Java identifiers.
Question 24: Which of the following is a checked exception in Java?
- IOException (Correct answer)
- ClassCastException
- NullPointerException
- ArrayIndexOutOfBoundsException
Correct answer: IOException
`IOException` is a checked exception that must be declared with `throws` or handled with a `try-catch` block.
Question 25: What is the purpose of `Thread.join()` in Java?
- To make the current thread wait until the specified thread finishes (Correct answer)
- To merge two threads into one
- To synchronize two threads
- To add a thread to a thread pool
Correct answer: To make the current thread wait until the specified thread finishes
`Thread.join()` causes the calling thread to block until the thread on which `join()` was called completes its execution.
Question 26: Which of the following is true about constructors in Java?
- Constructors can be synchronized
- Constructors are inherited by subclasses
- Constructors can be marked as abstract
- Constructors do not have a return type, not even void (Correct answer)
Correct answer: Constructors do not have a return type, not even void
Constructors have no return type — not even void — which distinguishes them from regular methods.
Question 27: What does the 'volatile' keyword guarantee in Java?
- Atomic compound operations on the variable
- Only one thread can access the variable at a time
- The variable is stored in CPU cache
- Visibility of changes across threads (Correct answer)
Correct answer: Visibility of changes across threads
volatile ensures that reads and writes to a variable are visible to all threads immediately.
Question 28: If a component needs to resize vertically but not horizontally, it should go in a:
- BorderLayout in the North or South location
- BorderLayout in the East or West location (Correct answer)
- BorderLayout in the Center location
- FlowLayout as the first component
Correct answer: BorderLayout in the East or West location
In a `BorderLayout`, components placed in the `EAST` or `WEST` regions will automatically resize vertically to fill the available height of the container. However, their horizontal width is typically fixed or determined by their preferred size, allowing them to resize vertically without changing horizontally. Components in `NORTH` or `SOUTH` resize horizontally, and `CENTER` resizes both ways.
Question 29: What is the result of `System.out.println(5 >> 1);`?
- 10
- 1
- 3
- 2 (Correct answer)
Correct answer: 2
The >> operator is the signed right-shift. Shifting 5 (binary 101) right by 1 position gives 010, which is 2. Each right-shift by 1 is equivalent to integer division by 2.
Question 30: What is the character class `[\\w&&[^\\d]]` equivalent to in Java regex?
- All digits
- All non-word characters
- Word characters excluding digits (i.e., letters and underscore) (Correct answer)
- All whitespace
Correct answer: Word characters excluding digits (i.e., letters and underscore)
`[\w&&[^\d]]` uses intersection: word characters (`\w`) intersected with non-digits (`[^\d]`), yielding letters and the underscore.
Question 31: What does the 'super' keyword refer to when used inside a constructor?
- A static parent method
- The parent class constructor (Correct answer)
- The current class instance
- The outermost class in a nested structure
Correct answer: The parent class constructor
super() in a constructor explicitly calls the parent class's constructor.
Question 32: Which exception is thrown when a program attempts to cast an object to an incompatible type?
- ClassCastException (Correct answer)
- IllegalArgumentException
- InvalidCastException
- TypeMismatchException
Correct answer: ClassCastException
`ClassCastException` is thrown at runtime when an object is cast to a class it is not an instance of.
Question 33: Which collection class is synchronized and considered the thread-safe version of ArrayList?
- ArrayDeque
- LinkedList
- Vector (Correct answer)
- TreeList
Correct answer: Vector
`Vector` is a synchronized, thread-safe dynamic array, essentially the legacy thread-safe counterpart to `ArrayList`.
Question 34: What is the default value of an instance variable of type boolean in Java?
- null
- true
- false (Correct answer)
- 0
Correct answer: false
The default value for an instance boolean variable is false in Java.
Question 35: Which interface must be implemented to submit a task to an `ExecutorService` that returns a result?
- Runnable
- Thread
- Callable (Correct answer)
- Future
Correct answer: Callable
`Callable<V>` is like `Runnable` but its `call()` method returns a value and can throw checked exceptions.
Question 36: What is the result of the expression `6 & 3` in Java?
- 2 (Correct answer)
- 9
- 5
- 7
Correct answer: 2
The & operator performs a bitwise AND. 6 in binary is 110 and 3 is 011. ANDing each bit: 110 & 011 = 010, which equals 2.
Question 37: What happens when a subclass constructor does not explicitly call a superclass constructor?
- Compilation error always occurs
- The superclass constructor is skipped
- The default no-arg superclass constructor is called implicitly (Correct answer)
- NullPointerException at runtime
Correct answer: The default no-arg superclass constructor is called implicitly
Java automatically inserts a call to the superclass no-arg constructor (`super()`) as the first statement if not explicitly provided.
Question 38: Given `TreeSet<Integer> ts = new TreeSet<>(); ts.add(5); ts.add(1); ts.add(3);`, what does `ts.first()` return?
- A NoSuchElementException
- 3
- 1 (Correct answer)
- 5
Correct answer: 1
TreeSet stores elements in ascending natural order, so first() returns the smallest element, which is 1.
Question 39: What is the result of comparing two String objects with == in Java?
- Throws NullPointerException
- Always true if contents are equal
- Causes a compile error
- Compares object references, not content (Correct answer)
Correct answer: Compares object references, not content
== on objects checks reference equality (same memory address), not the content of the strings.
Question 40: Given `StringBuilder sb = new StringBuilder("Hello"); sb.insert(2, "XY");`, what is `sb.toString()`?
- "HelloXY"
- "HXYello"
- "XYHello"
- "HeXYllo" (Correct answer)
Correct answer: "HeXYllo"
`insert(offset, str)` inserts the string before the character currently at `offset`, so inserting at index 2 places "XY" between 'e' and 'l'.
Question 41: Which statement about a static nested class is TRUE?
- It can access the instance variables of its enclosing class directly
- It can only contain static members
- It must be instantiated through an instance of the outer class
- It can be instantiated without an instance of the outer class (Correct answer)
Correct answer: It can be instantiated without an instance of the outer class
A static nested class is associated with the outer class itself, not with an instance. You instantiate it as `new Outer.Nested()` without needing an Outer instance. It cannot access instance members of the outer class directly.
Question 42: What is the correct way for an inner class to reference the enclosing class's instance variable `x` when the inner class has its own variable `x`?
- outer.x
- Outer.this.x (Correct answer)
- this.outer.x
- super.x
Correct answer: Outer.this.x
`Outer.this` is the qualified `this` reference that refers to the enclosing outer class instance. `super.x` refers to a superclass field, `outer.x` requires an explicit reference variable named `outer`, and `this.outer.x` is not valid Java syntax.
Question 43: Which of the following is the correct way to create an unmodifiable view of a List in Java?
- Arrays.readOnly(myList)
- Collections.unmodifiableList(myList) (Correct answer)
- myList.lock()
- List.freeze(myList)
Correct answer: Collections.unmodifiableList(myList)
`Collections.unmodifiableList()` wraps a List so that any mutating operations throw `UnsupportedOperationException`.
Question 44: What is the effect of declaring a variable as `volatile` in Java?
- It ensures that changes to the variable are immediately visible to all threads (Correct answer)
- It guarantees that reads and writes to the variable are atomic for all types
- It prevents multiple threads from reading the variable simultaneously
- It makes the variable immutable across threads
Correct answer: It ensures that changes to the variable are immediately visible to all threads
`volatile` ensures that every read of the variable reflects the most recently written value, preventing CPU cache inconsistencies between threads.
Question 45: What is a race condition in Java concurrency?
- Two threads competing for CPU speed
- A deadlock between three threads
- Unpredictable behavior caused by multiple threads accessing shared data without proper synchronization (Correct answer)
- A thread running faster than expected
Correct answer: Unpredictable behavior caused by multiple threads accessing shared data without proper synchronization
A race condition occurs when the program's outcome depends on the non-deterministic ordering of unsynchronized thread operations.
Question 46: What does a wildcard `?` represent in Java generics?
- A null type
- Any unknown type (Correct answer)
- An optional type parameter
- The Object class specifically
Correct answer: Any unknown type
The wildcard `?` in generics represents an unknown type, used when you don't know or care about the specific type argument.
Question 47: A method-local inner class defined inside an instance method can access which variables from the enclosing method?
- No variables from the enclosing method
- Only local variables declared final (or effectively final in Java 8+) (Correct answer)
- Only static variables of the enclosing class
- All local variables of the enclosing method
Correct answer: Only local variables declared final (or effectively final in Java 8+)
A method-local inner class can access the enclosing class's instance/static members freely, but can only access local variables that are final (Java 6 SCJP rule). This is because the class instance may outlive the method's stack frame.
Question 48: What is the `ordinal()` method in a Java enum?
- Returns the zero-based position of the constant in the enum declaration (Correct answer)
- Returns a hash code for the constant
- Returns the total number of enum constants
- Returns the enum constant's string name
Correct answer: Returns the zero-based position of the constant in the enum declaration
`ordinal()` returns the position of the enum constant in its declaration order, starting from 0.
Question 49: What does the compound assignment `x += 1.5;` do when x is declared as `int x = 3;`?
- Causes a compile-time error due to loss of precision
- Assigns 5 to x by rounding up
- Assigns 4 to x after an implicit narrowing cast (Correct answer)
- Assigns 4.5 to x
Correct answer: Assigns 4 to x after an implicit narrowing cast
Compound assignment operators include an implicit narrowing cast. `x += 1.5` is equivalent to `x = (int)(x + 1.5)`, so 3 + 1.5 = 4.5 is truncated to 4. A plain `x = x + 1.5` would fail to compile.
Question 50: Which of the following correctly declares a two-dimensional array in Java?
- int[][] arr; (Correct answer)
- int[2][3] arr;
- int arr[2][3];
- int arr = new int[2,3];
Correct answer: int[][] arr;
The correct syntax for declaring a 2D array reference is int[][] arr;
Question 51: What is the purpose of the `super` keyword when used inside a method body?
- To access superclass methods or fields hidden by the subclass (Correct answer)
- To call a superclass constructor only
- To create a new superclass instance
- To declare a superclass reference variable
Correct answer: To access superclass methods or fields hidden by the subclass
`super` in a method body refers to the superclass, allowing access to its overridden methods or hidden fields.
Question 52: Which statement about the enhanced for-loop (for-each) is TRUE?
- It requires the collection to implement java.lang.Iterable (Correct answer)
- It maintains an explicit index variable you can access
- It can iterate over a Map directly without calling entrySet()
- It can be used to modify the elements of a primitive array in place
Correct answer: It requires the collection to implement java.lang.Iterable
The enhanced for-loop works with arrays and any object that implements java.lang.Iterable. It provides no index variable, cannot structurally modify the underlying collection, and Map does not implement Iterable so you must use keySet(), values(), or entrySet().
Question 53: What does the `NavigableMap` interface add over `SortedMap`?
- Thread-safety guarantees
- Methods like floorKey(), ceilingKey(), higherKey(), and lowerKey() (Correct answer)
- Support for null keys
- Automatic resizing
Correct answer: Methods like floorKey(), ceilingKey(), higherKey(), and lowerKey()
NavigableMap extends SortedMap with navigation methods that return the closest matches for given search targets, such as floor, ceiling, higher, and lower.
Question 54: What exception is thrown when you try to modify a collection while iterating over it with a for-each loop?
- ConcurrentModificationException (Correct answer)
- IndexOutOfBoundsException
- UnsupportedOperationException
- IllegalStateException
Correct answer: ConcurrentModificationException
Modifying a collection's structure during iteration triggers `ConcurrentModificationException` via the fail-fast iterator mechanism.
Question 55: In Java, which exception type must be declared in a method's throws clause or handled with try-catch?
- Error
- Checked exception (Correct answer)
- Unchecked exception
- RuntimeException
Correct answer: Checked exception
Checked exceptions (subclasses of Exception but not RuntimeException) must be declared or handled explicitly.
Question 56: Which of the following is a valid way to create an anonymous class in Java?
- Runnable r = Runnable() { public void run() {} };
- anonymous Runnable r = new Runnable() { public void run() {} };
- Runnable r = new class() implements Runnable { public void run() {} };
- Runnable r = new Runnable() { public void run() {} }; (Correct answer)
Correct answer: Runnable r = new Runnable() { public void run() {} };
Anonymous classes are created with `new InterfaceOrClass() { /* body */ }`. There is no `anonymous` keyword, no `class` keyword in the syntax, and no parentheses-only form without `new`.
Question 57: Which of the following statements about Java arrays is true?
- Arrays can grow dynamically
- Arrays in Java are objects stored on the heap (Correct answer)
- Arrays can hold multiple types simultaneously
- Array indices start at 1
Correct answer: Arrays in Java are objects stored on the heap
Java arrays are objects allocated on the heap with a fixed size determined at creation.
Question 58: Which Map implementation maintains keys in their insertion order?
- Hashtable
- LinkedHashMap (Correct answer)
- HashMap
- TreeMap
Correct answer: LinkedHashMap
`LinkedHashMap` extends `HashMap` and maintains a linked list of entries in insertion order.
Question 59: In Java, can a class implement more than one interface?
- Only if interfaces share a common parent
- No, only one interface is allowed
- Only in Java 8+
- Yes, with a comma-separated list (Correct answer)
Correct answer: Yes, with a comma-separated list
A Java class can implement multiple interfaces by listing them with commas: `class Foo implements A, B, C`.
Question 60: Which of the following is true about abstract classes in Java?
- They must have at least one abstract method
- They can contain both abstract and concrete methods (Correct answer)
- They cannot have constructors
- They can be instantiated directly
Correct answer: They can contain both abstract and concrete methods
Abstract classes can have both abstract methods (no body) and concrete methods (with body).
Question 61: If a variable-width font is used to create the string text for a column, the column's starting size is:
- exclusively determined by the number of characters in the string
- determined by the number of characters in the string, multiplied by the width of a character in this font
- determined by the number of characters in the string, multiplied by the average width of a character in this font (Correct answer)
- undetermined
Correct answer: determined by the number of characters in the string, multiplied by the average width of a character in this font
For variable-width fonts, each character can have a different width. Therefore, simply multiplying by a single character width would not accurately determine the column's size. Instead, the starting size is estimated by considering the total number of characters in the string and multiplying it by the average width of a character in that specific font, providing a more realistic approximation.
Question 62: Which of the following data types can be used as a switch expression in Java SE 6?
- boolean
- int (Correct answer)
- long
- String
Correct answer: int
In Java SE 6, switch expressions are limited to byte, short, char, and int (and their wrappers, plus enum). String support was added in Java 7. long and boolean are never valid switch types.
Question 63: Given `List<Integer> list = new ArrayList<>(); list.add(5);`, which call demonstrates autoboxing?
- list.clear()
- list.get(0)
- list.add(5) (Correct answer)
- list.size()
Correct answer: list.add(5)
`list.add(5)` autoboxes the int literal 5 into an Integer object before adding it to the List<Integer>.
Question 64: Which of the following correctly defines a constructor in Java?
- It cannot be overloaded
- It has a return type of void
- It must call super() explicitly
- It has the same name as the class and no return type (Correct answer)
Correct answer: It has the same name as the class and no return type
A constructor shares the class name and has no return type declared (not even void).
Question 65: What is method overloading in Java?
- Preventing a method from being overridden
- Making a method run faster
- Providing a new implementation for a parent class method
- Defining multiple methods with the same name but different parameter lists (Correct answer)
Correct answer: Defining multiple methods with the same name but different parameter lists
Overloading lets you define multiple methods with the same name differing in number or type of parameters.
Question 66: What is printed by: System.out.println("Hello World".substring(6));
- World
- orld
- World (Correct answer)
- Hello
Correct answer: World
substring(6) returns characters from index 6 to the end; index 6 is 'W', yielding "World".
Question 67: What is the output of the following code? int x = 5; System.out.println(x++);
- 4
- 5 (Correct answer)
- 6
- Compile error
Correct answer: 5
The post-increment operator returns the original value (5) before incrementing x to 6.
Question 68: Given `enum Planet { MERCURY, VENUS, EARTH; }`, what does `Planet.values()` return?
- A Set<Planet> of all constants
- An array Planet[] of all constants (Correct answer)
- An Iterator<Planet> over all constants
- A List<Planet> of all constants
Correct answer: An array Planet[] of all constants
`values()` is a compiler-generated static method that returns a Planet[] array containing all enum constants.
Question 69: When iterating over a `HashMap` with an `Iterator` and you remove an element using `map.remove(key)` (not `iterator.remove()`), what occurs?
- A ConcurrentModificationException is thrown on the next iterator call (Correct answer)
- The iterator skips the next element silently
- A NullPointerException is thrown immediately
- The element is removed and iteration continues normally
Correct answer: A ConcurrentModificationException is thrown on the next iterator call
Structurally modifying a HashMap while iterating it via a fail-fast iterator (without using iterator.remove()) causes ConcurrentModificationException.
Question 70: What is the value of `byte b = (byte) 130;` in Java?
- -126 (Correct answer)
- 130
- Compilation error
- 127
Correct answer: -126
byte holds values from -128 to 127. 130 in binary (8 bits) is 10000010. With a signed byte, the leading 1 indicates a negative number. Using two's complement, this equals -126.
Question 71: What is the output of: String.format("%05d", 42);
- " 42"
- "00042" (Correct answer)
- "42"
- "42000"
Correct answer: "00042"
%05d formats the integer with a field width of 5, padding with leading zeros, producing "00042".
Sun Certified Java Programmer (SCJP) - Java SE 6 (CX-310-065)
The SCJP exam validates proficiency in Java SE 6 programming including OOP principles, collections, generics, concurrency, and exception handling. Formerly offered by Sun Microsystems and now superseded by Oracle Certified Professional Java Programmer (OCPJP).
Exam Rules
- You can skip questions and return to them later
- Flag questions for review before submitting
- No feedback shown until you submit the entire exam
- Unanswered questions count as wrong — answer everything
- 10 pretest questions are mixed in and don't affect your score
- Timer auto-submits when time runs out
- Your progress is auto-saved every 30 seconds