SCJP Sun Certified Java Programmer MCQ 5 — Questions and Answers
Question 1: Which operator is used to check if an object is an instance of a particular class or interface in Java?
- typeof
- instanceof (Correct answer)
- classof
- isA
Correct answer: instanceof
The 'instanceof' operator returns true if the object is an instance of the specified type.
Question 2: What is the purpose of the 'volatile' keyword in Java?
- Prevents a variable from being garbage collected
- Ensures a variable is read from and written to main memory directly, not cached (Correct answer)
- Marks a variable as unmodifiable
- Makes a variable accessible across packages
Correct answer: Ensures a variable is read from and written to main memory directly, not cached
The volatile keyword ensures all threads see the most up-to-date value by bypassing CPU caching.
Question 3: Which of the following correctly initializes a char variable in Java?
- char c = "A";
- char c = 'A'; (Correct answer)
- char c = A;
- char c = (char)'AB';
Correct answer: char c = 'A';
A char literal is enclosed in single quotes; double quotes are for String literals.
Question 4: What is the output of: int x = 5; System.out.println(x++);
- 6
- 5 (Correct answer)
- 4
- Compile-time error
Correct answer: 5
The post-increment operator returns the current value (5) before incrementing x to 6.
Question 5: Which of the following is true about constructors in Java?
- Constructors can have a return type of void
- Constructors are inherited by subclasses
- Constructors must have the same name as the class (Correct answer)
- A class can have at most one constructor
Correct answer: Constructors must have the same name as the class
A constructor must exactly match the class name and has no return type declaration, not even void.
Question 6: What does the 'break' statement do inside a switch block?
- Exits the entire program
- Skips to the next case label
- Terminates the switch block and transfers control to the statement after it (Correct answer)
- Causes a compile-time error
Correct answer: Terminates the switch block and transfers control to the statement after it
Without break, execution falls through to subsequent cases; break exits the switch block immediately.
Question 7: Which method of the String class returns the character at a specific index?
- getChar()
- charAt() (Correct answer)
- charAtIndex()
- get()
Correct answer: charAt()
String.charAt(int index) returns the char value at the specified index.
Which operator is used to check if an object is an instance of a particular class or interface in Java?