Oracle Certified Professional Java Se 11 Developer · Free Practice Question Medium
Question 41
Question ID: UKOCP21659
Consider codes of 3 java files:
- //Class1.java
- package com.udayankhattry.ocp;
- import java.io.FileNotFoundException;
- public class Class1 {
- public void read() throws FileNotFoundException {}
- }
- //Class2.java
- public class Class2 {
- String Class2;
- public void Class2() {}
- }
- //Class3.java
- public class Class3 {
- private void print() {
- private String msg = "HELLO";
- System.out.println(msg);
- }
- }
Which of the following statements is true?
- A Only Class1.java compiles successfully
- B Only Class2.java compiles successfully
- C Only Class3.java compiles successfully
- D Class1.java and Class2.java compile successfully
- E Class1.java and Class3.java compile successfully
- F Class2.java and Class3.java compile successfully
Reveal correct answer
Correct answer: D
Explanation
UKOCP21659:
java.io.FileNotFoundException exception is a checked exception.
Method declaring checked exception in its throws clause doesn't mean that it should have code to actually throw that type of Exceptions. So even though read() method of Class1 declares to throw FileNotFoundException but its body doesn't actually throw an instance of FileNotFoundException.
Variable and method name can be same as class name, so code of Class2 is also valid. Remember: Though you don't get any compilation error but it is not recommended to use the Class name for variable and method names.
LOCAL variable can be declared with final modifier only. msg variable inside print() method of Class3 is declared private and this causes compilation error.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
