OCP Question 55, Explanation

Given the code format:

class AccessKey{
    String user;
    String pass;
}

and

12. class DBAccess{
13.    AccessKey grantAccess(String user, String pass){
14.    // insert code here
15.    }
16.    public static void main(String[] args){
17.        DBAccess dba = new DBAccess();
18.        AccessKey key = dba.grantAccess("Bill", "1234");
19.    }
20. }

Which code fragment must be inserted at line 14 to enable the code to compile?

A. AccessKey x; return x;
B. return AccessKey;
C. return new AccessKey();
D. return 0;

 

The correct answer is C.

 

The x var is local and, therefore, must be inited before it can be used as a return value in a method; option B is also invalid as AccessKey in it hasn’t even been declared, and option D wants to return a primitive in place of a reference type.

Leave Comment

Your email address will not be published. Required fields are marked *