Declare and instantiate Java objects including nested class objects, and explain the object life-cycle including creation, reassigning references, and garbage collection.
Create classes and records, and define and use instance and static fields and methods, constructors, and instance and static initializers.
Implement overloading, including var-arg methods.
1. The correct answer is B.
Explanation:
sb1 and sb2 are eligible for garbage collection.
sb2 still holds a reference to the StringBuilder object it was initially assigned. Therefore, it is not eligible for garbage collection.StringBuilder object initially referenced by sb1 is eligible for garbage collection.
sb1 is reassigned to reference the same object as sb2, the original StringBuilder object created with new StringBuilder("Java") and initially referenced by sb1 is no longer accessible. Since there are no references pointing to it, it becomes eligible for garbage collection.StringBuilder object initially referenced by sb2 is eligible for garbage collection.
sb1 = sb2;, both sb1 and sb2 reference the same object (new StringBuilder("Python")). This object is still accessible through sb2 (and now sb1 as well), so it is not eligible for garbage collection.StringBuilder objects are eligible for garbage collection.
sb1 becomes eligible for garbage collection after sb1 is reassigned to sb2.2. The correct answers are C and D.
Explanation:
A) implement is incorrect. The correct keyword for implementing an interface in Java is implements.
B) array is incorrect. Java does not have a reserved keyword named array. Arrays are declared with square brackets [ ].
C) volatile is correct. volatile is a reserved keyword that is used to indicate that a variable’s value will be modified by different threads.
D) extends is correct. extends is a reserved keyword used in class declarations to inherit from a superclass.
3. The correct answers are A and E.
Explanation:
// to start a single-line comment, which is a common way to add notes or explain a part of code that does not affect the execution./** and end with */.add method.
/** at the beginning and */ at the end, and are specifically used to describe classes, methods, and fields.TODO comment, different from a single-line comment.
TODO comment, which is a convention many developers follow to mark parts of the code that require further development or attention but is still a single-line comment.4. The correct answers are B and D.
Explanation:
import statement in Application.java is unnecessary because both classes are in the same directory.
import statement is used to bring a class or an entire package into visibility, and its necessity is determined by the package membership of the classes, not their directory location. Even if classes are in the same directory, if they belong to different packages, the import statement is required to use one in the other.import statement in Application.java is necessary for using the Calculator class because they belong to different packages.
Calculator class is in the math package, and the Application class is in the app package. Despite being in the same directory, the different packages require an import statement to use Calculator in Application.Calculator class will not be accessible in Application.java due to being in a different directory.
package and import declarations. As long as the classes are correctly packaged and imported, they can be accessed across different directories.package statement from both files will allow Application.java to use Calculator without an import statement, regardless of directory structure.
package statement from both files will place them in the default package, and they will be able to access each other without an import statement. However, this is not recommended for anything beyond very simple or temporary code due to namespace management and readability concerns.5. The correct answers are A, B, and C.
Explanation:
public class or member can be accessed by any other class in the same package or in any other package.
public modifier grants the highest level of access. A public class or member is accessible from any other class, regardless of the packages they belong to.protected member can be accessed by any class in its own package, but from outside the package, only by classes that extend the class containing the protected member.
protected access level allows a member to be accessed within its own package and by subclasses in any package. It offers a more restrictive level of access than public.default (no modifier) access can be accessed by any class in the same package but not from a class in a different package.
default access level) is specified, the member is accessible only within classes in the same package. This is more restrictive than protected and public.private member can be accessed only by methods that are members of the same class or within the same file.
private members can be accessed only within the same class. It’s not about being within the same file, as Java allows only one public top-level class per file.protected member can be accessed by any class in the Java program, regardless of package.
Protected access does not grant universal access across all classes in a program. Access from outside the package is limited to subclasses only.6. The correct answer is D:
Explanation:
class public Vehicle { }
class keyword, and then the class name.public class vehicle { }
vehicle should be Vehicle.Public class Vehicle { }
Public is incorrectly capitalized. Java is case-sensitive, and the correct keyword is public.public class Vehicle { }
public), followed by the class keyword, and then the class name (Vehicle), which correctly starts with an uppercase letter as per Java naming conventions.classVehicle public { }
class and the class name, and the access modifier’s position is incorrect.7. The correct answers are A, C, and D.
Explanation:
COUNT variable can be accessed directly using the class name without creating an instance of Counter.
Counter.COUNT, without needing to instantiate the class.getCount() method is an example of a static method because it returns the value of a static variable.
getCount() returns a static variable’s value, it is not defined as a static method. Static methods are declared using the static modifier. The method’s instance or non-static nature does not change based on the variables it accesses or returns.Counter is created, the COUNT variable is incremented.
COUNT variable by 1 each time a new instance of Counter is created, demonstrating the shared nature of static variables across all instances.resetCount() method resets the COUNT variable to 0 for all instances of Counter.
resetCount() static method sets the COUNT variable to zero. Since COUNT is static, this change affects all instances of the class, as there is only one COUNT variable shared among them.8. The correct answers are A, C, and D.
Explanation:
A) int _age; is correct. Identifiers in Java can begin with a letter, an underscore (_), or a dollar sign ($). Therefore, _age is a valid identifier.
B) double 2ndValue; is incorrect. Identifiers cannot start with a digit. The correct format would be to start with a letter or a non-digit character such as an underscore or a dollar sign.
C) boolean is_valid; is correct. Similar to _age, is_valid is a valid identifier because it starts with a letter and can contain underscores.
D) String $name; is correct. Identifiers can also start with a dollar sign ($), making $name a valid identifier.
E) char #char; is incorrect. The hash (#) character is not allowed as a starting character in identifiers. Identifiers can only start with letters, $, or _.
9. The correct answer is B.
Explanation:
A) int public static final computeSum(int num1, int num2) is incorrect because the return type in method declarations goes right before the name of the method, not at the beginning.
B) private void updateRecord(int id) throws IOException is correct. This method declaration is syntactically correct in Java. It uses the private access modifier, specifies a return type (void), includes an exception (IOException) that this method might throw, and correctly defines the parameter list.
C) synchronized boolean checkStatus [int status] Correct syntax requires parentheses for the parameter list, even when there are no parameters, making the correct declaration synchronized boolean checkStatus(int status).
D) float calculateArea() {} is incorrect because a method that returns float cannot have an empty method body.
10. The correct answers are A and B.
Explanation:
In Java, a method signature consists of the method name and the parameter list. The return type, access modifier, and exception list are not considered part of the method signature.
public void update(int id, String value))private void update(int identifier, String data))
update(int, String)) because they both have the same method name and parameter list (an int and a String, in that order). The difference in parameter names (id vs. identifier and value vs. data) does not affect the method signature.public boolean update(String value, int id)
void update(String value, int id)
update(String, int)) because the order of the parameters is reversed compared to A and B.protected void update(int id, int value) throws IOException
update(int, int)).11. The correct answers are C and D.
Explanation:
resetAccountPassword method can be accessed from any class within the same package but not from a class in a different package.
resetAccountPassword method has private access, which means it is accessible only within the AccountManager class itself, not from any class, even within the same package. The initial statement was slightly incorrect in suggesting package-level access for a private method.auditTrail method can be accessed from any class within the same package and from subclasses in different packages.
auditTrail method has package-private access (no access modifier), which means it is accessible from any class within the same package but not from subclasses in different packages unless they are also within the same package.notifyAccountChanges method can be accessed from any class within the same package and from subclasses in different packages.
notifyAccountChanges method has protected access, meaning it can be accessed within the same package and by subclasses, even if the subclasses are in different packages.updateAccountInformation method can be accessed from any class, regardless of its package.
updateAccountInformation method is public, so it can be accessed from any class, regardless of the package it belongs to.12. The correct answer is B.
Explanation:
Java is strictly pass-by-value. This means that when passing a variable to a method, Java passes a copy of the variable’s value, not the variable itself. Changes to the parameter inside the method do not affect the original variable.
Before calling changeValue: 10
After calling changeValue: 20
changeValue method changes the value parameter to 20, this change does not affect the original variable originalValue outside the method. The change to value is made on its copy, not on originalValue itself.Before calling changeValue: 10
After calling changeValue: 10
originalValue is passed by value to the changeValue method. Thus, modifications to value inside changeValue do not affect originalValue. The output confirms that originalValue remains unchanged after the method call.Before calling changeValue: 20
After calling changeValue: 20
Before calling changeValue: 20
After calling changeValue: 10
13. The correct answer is B.
Explanation:
Object
String is more specific than Object, so the print(String s) method is called.String
null can be assigned to any reference type, Java prefers the most specific method applicable to the method parameters. Since String is a more specific type than Object, the print(String s) method is chosen over the print(Object o) method.print methods are correctly defined and can potentially match the call print(null). Java’s method overloading mechanism allows this to compile without any issues.print successfully resolves to the print(String s) method at compile time. Since the method is correctly invoked, and there is no other code that could cause a runtime exception, this program runs successfully.14. The correct answers are B and D.
Explanation:
public void print(String... messages, int count)
int count after String... messages violates this rule.public void print(int count, String... messages)
String... messages at the end of the method’s parameter list, which is the required syntax for using varargs.public void print(String messages...)
String messages... is invalid. The correct syntax for varargs is to place the ellipsis (...) after the type and before the variable name, like String... messages.public void print(String[]... messages)
messages can itself be an array of String, and messages will be treated as an array of arrays (String[][]).public void print(String... messages, String lastMessage)
15. The correct answer is A.
Explanation:
Vehicle demonstrates constructor overloading by having multiple constructors with different parameter lists.
Vehicle class has two constructors, one that takes a String (for the vehicle type) and another that takes an int (for the max speed), which is a perfect example of constructor overloading.Vehicle will compile with an error because it does not provide a default constructor.
Vehicle with both type and maxSpeed initialized.
Vehicle instance with both type and maxSpeed initialized through a single constructor call.type and maxSpeed fields of the Vehicle class.
type, and the second initializes the maxSpeed. Without additional code, such as a constructor that accepts both parameters or setter methods, there’s no way for either constructor alone to initialize both fields.16. The correct answer are A and D.
Explanation:
books list and adding two books to it.
books list and adds two books to it.Library class.
books.
books list is an instance variable that is being initialized and populated within the instance initializer block.Library are created, the instance initializer block will execute each time before the constructor, ensuring the books list is initialized and populated for each object.
Library class, the instance initializer block runs before the constructor is invoked. This ensures that the books list is initialized and populated with "Book 1" and "Book 2" for every Library object created.17. The correct answer is A.
Explanation:
static initializer block is executed only once when the class is first loaded into memory, initializing the settings map with default values.
settings map with default configuration values.static initializer block allows instance methods to modify the settings map without creating an instance of the Configuration class.
getSetting can access and modify static fields like settings without needing an instance of the class, this capability is not due to the static initializer block itself but rather the nature of static fields and methods.static initializer blocks are executed each time a new instance of the Configuration class is created.
static initializer block is executed before any instance initializer blocks or constructors, when an instance of the class is created.
18. The correct answer is B.
Explanation:
In Java, the order of initialization when a class is loaded and an instance of that class is created is as follows:
Static fields and static initializers are processed in the order they appear in the class definition. First, the static initializer block prints "1. Static initializer". Then, the static field staticValue is initialized by calling initializeStaticValue(), which prints "2. Static value initializer".
Instance fields and instance initializers are processed in the order they appear when an instance of the class is created. First, the instance field instanceValue is initialized by calling initializeInstanceValue(), which prints "3. Instance value initializer". Then, the instance initializer block prints "3. Instance initializer".
Constructors are executed after all fields and instance initializers have been processed. The constructor in this case prints "4. Constructor".
The numbering of the output for "3. Instance initializer" and "3. Instance value initializer" in the question might seem to suggest they are executed simultaneously or out of order, but it’s important to remember that instance fields and instance initializers execute in the order they appear in the class, before the constructor is executed. The duplicate numbering means that instance field initializers run first, followed by instance initializers, and finally, the constructor runs.
1. Static initializer
2. Static value initializer
3. Instance initializer
3. Instance value initializer
4. Constructor
1. Static initializer
2. Static value initializer
3. Instance value initializer
3. Instance initializer
4. Constructor
1. Static initializer
3. Instance initializer
2. Static value initializer
3. Instance value initializer
4. Constructor
2. Static value initializer
1. Static initializer
3. Instance value initializer
3. Instance initializer
4. Constructor
19. The correct answers are A and C.
Explanation:
toString() on an instance of CustomObject will return a String that includes the class name followed by the @ symbol and the object’s hashcode.
toString() method in java.lang.Object returns a string that includes the class name, the @ symbol, and the object’s hashcode in hexadecimal. If CustomObject does not override toString(), this default format is used.equals(Object obj) on two different instances of CustomObject that have identical content will return true because they are instances of the same class.
equals(Object obj) in java.lang.Object checks for reference equality, meaning it returns true only if both references point to the exact same object. Without overriding equals, two different instances of CustomObject, even with identical content, would not be considered equal.hashCode() on any instance of CustomObject will generate a unique integer that remains consistent across multiple invocations within the same execution of a program.
hashCode() method is designed to return an integer representation of the object’s memory address or a value derived from it. While the exact implementation is not specified and can vary, it is consistent during the execution of a program for any given object.clone() method can be used to create a shallow copy of an instance of CustomObject without the need for CustomObject to implement the Cloneable interface.
clone() method in java.lang.Object is protected, and it throws a CloneNotSupportedException unless the class implements the Cloneable interface. Without CustomObject explicitly implementing Cloneable and overriding clone() to make it public, it cannot be used to clone instances of CustomObject.20. The correct answer is B.
Explanation:
21. The correct answer is A.
Explanation:
InnerClass accesses the non-static message field of OuterClass.InnerClass instance is created through an instance of OuterClass.22. The correct answers are A and D.
Explanation:
for loop, or an if statement.final or effectively final.
final or effectively final (which means their values do not change after they are initialized).23. The correct answer is A.
Explanation:
24. The correct answer is C.
Explanation:
public class. If a class is declared public, it must be the only public class in the file, and the file name must match the class name.private at the top level. Only public, or package-private (no access modifier) classes can be defined at the top level. Inner classes can be private.public class must be declared in a source file that has the same name as the class.
public, the source file in which it is defined must have the same name as the class, followed by the .java extension. This is a strict rule that helps the Java compiler easily locate source files.public.
public class, the source file must be named after that public class, it is not true that none of the classes can be public if a source file contains more than one class. A source file can contain multiple classes, but only one of them can be public, and the source file must be named after that public class. The statement could imply that multiple non-public top-level classes are a common scenario without the context of the public class naming rule.Do you like what you read? Would you consider?
Do you have a problem or something to say?