Computer Science Exit Exam Study Guide · 294 questions
Read the question first. Select the eye beside the reading hint, study the cited module section, then reveal the answer. Each eye controls only its own block. All hints and answers start closed whenever this page opens.
Read the linked study-guide sections before revealing the answer. PDF page references count from the first page of the document.
294 of 294 questions
Question 1
When overloading a function, what must be true?
A. The names should be different with different number and/or types of parameters.
B. None of the choices are correct
C. The names should be different with the same number and/or types of parameters.
D. The names should be the same with different number and/or types of parameters.
E. The names should be the same with the same number and/or types of parameters.
Hint / Module Reference (Where to Read)
Compare names and parameter signatures before considering return types or access modifiers.
Correct answer: D — The names should be the same with different number and/or types of parameters.
Overloads retain the method name and change parameter count or parameter types; return type alone cannot distinguish them.
Evidence in the complete study note
Overloaded methods share a name but have different parameter types, counts or type order. Return type alone is insufficient in Java and C++. Overloads can also arise through inherited methods; “same class only” is a teaching simplification. f(int), f(double) and f(int,int) are distinct, but changing a parameter name does not create an overload.OOP12
Choice by choice
A · incorrect — Different names do not overload one function
B · incorrect — D satisfies the overloading rule, so the statement that none of the choices is correct is false.
C · incorrect — Different names define separate methods
D · correct — Same name plus different parameter list meets the definition
E · incorrect — Same name and same parameter signature cannot distinguish overloads
Question 2
Which of the following statement about function overloading is TRUE?
A. Overload function have same name but different parameters/type
B. Overload function is not supported
C. .
Overload function must have different return type
D. Overload function must have the same number of parameters
Hint / Module Reference (Where to Read)
Compare names and parameter signatures before considering return types or access modifiers.
Correct answer: A — Overload function have same name but different parameters/type
The test examples vary both argument counts and types while retaining test as the name.
Evidence in the complete study note
Overloaded methods share a name but have different parameter types, counts or type order. Return type alone is insufficient in Java and C++. Overloads can also arise through inherited methods; “same class only” is a teaching simplification. f(int), f(double) and f(int,int) are distinct, but changing a parameter name does not create an overload.OOP12
The compiler selects the applicable signature from the declared argument types and conversions. int arguments usually choose an exact int overload rather than a wider double overload. A return type is not part of an ordinary Java method signature.OOP12
Choice by choice
A · correct — Matches the definition
B · incorrect — Overloading is explicitly supported
C · incorrect — Return type alone is insufficient
D · incorrect — test() and test(int,int) show that equal counts are not required
Question 3
Which generation of programming languages stated for high-level languages like C++, Java,
Python?
A. 2nd generation
B. 3rd generation
C. 4th generation
D. None of the above
Hint / Module Reference (Where to Read)
Separate language-generation classification, translation strategy and portability assumptions.
OOP39 explicitly places general-purpose high-level languages such as C++, Java and Python in the third generation. This taxonomy concerns historical language classification, not whether a language is object oriented or interpreted. Thus the third-generation option applies to all the examples named in the question.
Evidence in the complete study note
Under the conventional introductory generation taxonomy, general-purpose high-level languages such as C++, Java, Python and Perl are third generation. The taxonomy is separate from object orientation and from compilation versus interpretation. Java source normally compiles to JVM bytecode, and a compatible JVM plus libraries supports portability across systems.OOP39
Choice by choice
A · incorrect — Second generation is not the category assigned to these general-purpose high-level examples in OOP39.
B · correct — Third generation is the explicit conventional category assigned to C++, Java and Python.
C · incorrect — Fourth generation does not match the explicit third-generation classification of the named examples.
D · incorrect — The third-generation option is present, so none of the above cannot be correct.
Question 4
In which generation that classifies and categorizes high-level language like
C++, JAVA, Python, Perl.
A. a | First Generation Language x
B. i? Second Generation Language x
C. |@| Third Generation Language oS
D. | Fourth Generation Language x
Hint / Module Reference (Where to Read)
Separate language-generation classification, translation strategy and portability assumptions.
C++, Java, Python and Perl are third-generation languages in this historical classification. Compilation versus interpretation and object orientation do not alter that historical classification.
Evidence in the complete study note
Under the conventional introductory generation taxonomy, general-purpose high-level languages such as C++, Java, Python and Perl are third generation. The taxonomy is separate from object orientation and from compilation versus interpretation. Java source normally compiles to JVM bytecode, and a compatible JVM plus libraries supports portability across systems.OOP39
Choice by choice
A · incorrect — First generation does not match the third-generation classification of the named high-level languages.
B · incorrect — Second generation does not match the conventional category OOP39 assigns to these high-level examples.
C · correct — The named general-purpose high-level languages are explicitly classified as third generation in OOP39.
D · incorrect — Fourth generation is not the classification given for these examples in the complete note.
Question 5
What is the output of the following Java fragment code? int n = 6, m = 15, p = 3; n -= m; n *= p;
System.out.print(n);
A. 27
B. 3
C. 24
D. -27
Hint / Module Reference (Where to Read)
Respect operator grouping and operand types, then trace each operation in evaluation order.
Start with n=6. The subtraction assignment n-=m computes 6-15, leaving n=-9. The multiplication assignment then uses that updated value: -9*3=-27. OOP23 includes this exact trace. The sign cannot become positive because only subtraction followed by multiplication by positive three occurs.
Evidence in the complete study note
Java evaluates operands left to right while respecting precedence. With n=6,m=15,p=3, n-=m then n*=p leaves -27.OOP23
Choice by choice
A · incorrect — 27 discards the negative sign produced when 15 is subtracted from 6.
B · incorrect — Three is the unchanged multiplier p, not the updated value of n that is printed.
C · incorrect — 24 does not follow either the subtraction result -9 or its subsequent multiplication by 3.
D · correct — The ordered updates yield n=-9 and then n=-27, which System.out.print outputs.
Question 6
What is the output of the following Java fragment code? int[] list = new int[4]; int sum = 0; for(int i
= 0; i < list.length; i++) { list[i] = i * 3; sum += list[i]; } System.out.print(sum);
A. 18
B. 6
C. 3
D. 36
Hint / Module Reference (Where to Read)
Trace every element or API argument and distinguish copying values from aliasing a reference.
The length-four array is visited at indices 0,1,2,3. Assigning i*3 stores 0,3,6,9. Starting sum at zero and adding each element gives 18, exactly the example in OOP27. The loop processes four elements, not merely the first one or an uninitialized default array.
Evidence in the complete study note
For int[] a=new int[4], setting a[i]=i*3 and accumulating yields 0+3+6+9=18.OOP27
Valid indices are 0..a.length-1; an invalid access throws ArrayIndexOutOfBoundsException.OOP26
Choice by choice
A · correct — All four assigned elements contribute: 0+3+6+9 equals the printed sum 18.
B · incorrect — Six is one element’s value, not the sum after all four iterations.
C · incorrect — Three is the element assigned at index 1, rather than the full accumulator result.
D · incorrect — 36 doubles the actual total; each of the four elements is added only once.
Question 7
Consider the following program:
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("enter choice");
int choice = scanner.nextInt();
switch (choice) {
case 1: System.out.println("Hello");
case 2: System.out.println("you");
break;
default: System.out.println("welcome");
}
System.out.println("Goodbye");
}
}
After entering 1, what lines are printed following the initial “enter choice” prompt? Preserve letter case.
A. Hello
You welcome
B. Hello
You
Welcome
Goodbye
C. Hello
Goodbye
D. Hello
you
Goodbye
Hint / Module Reference (Where to Read)
Trace condition tests, control transfers and printing as separate steps.
Input 1 selects case 1, which prints Hello but has no break. Execution falls through to case 2 and prints you. Its break exits the switch before default, so welcome does not print. The final println outside the switch prints Goodbye. The requested output excludes the initial input prompt and preserves exact letter case.
Evidence in the complete study note
break exits the loop; continue skips its remaining body and then runs a for update. Traditional colon-style switch labels fall through without break. Choice 1 printing Hello then case 2 printing you and breaking is followed by Goodbye outside the switch; default is skipped.OOP25
Choice by choice
A · incorrect — This incorrectly includes welcome and omits the final Goodbye.
B · incorrect — Default is skipped after case 2 breaks, so this includes an extra line.
C · incorrect — Fall-through executes case 2, so omitting you is wrong.
D · correct — The exact post-prompt lines are Hello, you and Goodbye.
Question 8
Which one of the following is false regarding Exceptions in Java?
A. We cannot create our own exception classes by extending Exception class
B. Exception class describes errors caused by your program and external circumstances
C. Runtime Exception class describes programming errors such as bad casting and numeric errors
D. All Java exception classes inherit directly or indirectly from Throwable class
Hint / Module Reference (Where to Read)
Separate source errors from runtime exceptions and determine the hierarchy and checked obligation.
Correct answer: A — We cannot create our own exception classes by extending Exception class
The prohibition on user-defined exceptions is false: an exception class can extend Throwable or a subclass. Its examples describe input, file and resource failures and runtime programming bugs.
Evidence in the complete study note
Throwable is the root of throwable values, with Exception and Error branches. RuntimeException and Error subclasses are unchecked; other throwable classes are checked. IOException, FileNotFoundException and SQLException are standard checked examples. ArithmeticException, NullPointerException, ClassCastException and array bounds exceptions are unchecked. A missing semicolon or undeclared variable is a compile-time source error, not a checked exception.OOP29
A custom exception can extend Exception or RuntimeException.OOP29
Choice by choice
A · correct — Contradicts the explicit permission to define exception classes
B · incorrect — Consistent with user, programmer and resource failures
C · incorrect — Consistent with runtime programming bugs, though individual bad-cast examples are not enumerated
D · incorrect — Matches the Throwable ancestry rule
Question 9
Assuming there is a rectangle object, what getArea, getPerimeter can represent?
A. Attribute
B. Property
C. Data field
D. Behavior
Hint / Module Reference (Where to Read)
Distinguish an object’s stored state, operations, identity and class definition.
getArea and getPerimeter describe operations performed by a rectangle, so they are behavior rather than its stored state.
Evidence in the complete study note
An object has identity, state and behavior. State is stored in fields; behavior is provided by methods. A Rectangle object may hold width and height and answer getArea() or getPerimeter(). Two objects can have equal fields and still be distinct objects. A class defines their common structure and behavior; an object is a particular instance.OOP01
Choice by choice
A · incorrect — An attribute stores state rather than performing this operation
B · incorrect — Property here would mean stored/descriptive state, not the two operations
C · incorrect — A data field stores a value; these are methods
D · correct — Methods perform operations and express characteristic behavior
Question 10
Which one of the following is false about abstract classes and abstract methods?
A. We can create instances of abstract classes using the new operator
B. Implementation of abstract methods is provided by the subclasses
C. A class that contains abstract methods must be defined as abstract
D. Abstract methods are defined without implementation in the superclass
Hint / Module Reference (Where to Read)
Check whether a class is concrete and whether every inherited abstract contract has an implementation.
Correct answer: A — We can create instances of abstract classes using the new operator
The abstract-class example permits a concrete method but forbids new A(); subclasses supply the body for callme(). Thus instantiation is the false claim.
Evidence in the complete study note
An abstract class cannot be directly instantiated but can define fields, constructors, abstract methods and concrete methods. It need not contain an abstract method. An abstract method has no body; abstract and final conflict because an operation cannot require overriding while forbidding it.OOP18
A concrete subclass must provide or inherit implementations of all required abstract methods; otherwise it must itself be abstract.OOP18
Choice by choice
A · correct — Direct new instantiation is forbidden
B · incorrect — B supplies the implementation of callme in the example
C · incorrect — An abstract method is an unimplemented requirement of an abstract class in this model
D · incorrect — The example declares abstract void callme() without a body
Question 11
Which operator is used to create an array?
A. new
B. declare
C. static
D. construct
Hint / Module Reference (Where to Read)
Check declared dimensions, initializer shape, fixed length and zero-based index bounds.
OOP26 shows int[] a=new int[5] as valid array creation. Here new is the allocation operator that creates the array object. The note also allows brace initializers without spelling new in declarations, so the answer identifies the operator rather than asserting that every array initializer must explicitly contain it.
Evidence in the complete study note
int[] a=new int[5]; and int a[]={1,2,3}; are valid. int[] a={}; creates a zero-length array; explicit new is unnecessary in a declaration initializer.OOP26
static gives one field per loaded class, shared by its instances.OOP07
Choice by choice
A · correct — new is the operator used in the note’s explicit array-allocation form new int[5].
B · incorrect — declare is not the allocation operator in the Java array-creation syntax shown in OOP26.
C · incorrect — static controls class membership; it does not create an array object by itself.
D · incorrect — construct is not the Java array-allocation operator used in the provided creation syntax.
Question 12
What does this valid Java loop print? Ignore only the trailing space.
for (int i = 2; i <= 11; i = i + 2) {
if (i % 4 == 0)
System.out.print(i * i + " ");
}
A. 16 64
B. 4163664100
C. 16644864
D. 4816644
Hint / Module Reference (Where to Read)
Trace condition tests, control transfers and printing as separate steps.
The loop visits 2, 4, 6, 8 and 10. Only 4 and 8 have remainder zero when divided by 4, so their squares are the only values printed: 16 and 64. The string space separates the values. With valid Java capitalization, operators and parentheses, and ignoring the final space, the loop prints 16 64.
Evidence in the complete study note
while and for pre-test and may execute zero times; do-while post-tests and executes once.OOP25
Java evaluates operands left to right while respecting precedence.OOP23
Once a String operand is encountered, + concatenates in left-to-right groups: 1+2+"x" gives "3x", while "x"+1+2 gives "x12".OOP24
Choice by choice
A · correct — Only the qualifying values 4 and 8 print their squares, giving 16 64.
B · incorrect — This includes squares from iterations where i is not divisible by four.
C · incorrect — This adds values not printed by the two qualifying iterations.
D · incorrect — This does not match the squares of 4 and 8.
Question 13
Which valid Java declaration reproduces a ragged table with first row 12, -9, 8; second row 7, 14; and third row -32, -1, 0? The second row has two elements, not a third element containing zero.
Correct answer: D — Use rows {12,-9,8}, {7,14}, {-32,-1,0}.
Java represents a two-dimensional array as an array of row arrays, so the rows may have different lengths. The source table has lengths 3, 2 and 3. D supplies exactly those rows with comma-separated nested initializers. B is syntactically valid but adds an unwanted middle-row zero. A supplies scalar values where row arrays are needed, and C omits commas between its row initializers.
Evidence in the complete study note
int[] a=new int[5]; and int a[]={1,2,3}; are valid. int[] a={}; creates a zero-length array; explicit new is unnecessary in a declaration initializer.OOP26
Valid indices are 0..a.length-1; an invalid access throws ArrayIndexOutOfBoundsException. Java two-dimensional arrays are arrays of arrays and may be ragged: {{12,-9,8},{7,14},{-32,-1,0}} has row lengths 3,2,3. Java does not expose a portable physical contiguity guarantee, so a language-level answer should not rely on raw addresses.OOP26
Choice by choice
A · incorrect — The declared double[][] requires row-array elements; a flat list of numeric scalars does not supply them.
B · incorrect — Its second row contains an extra zero and therefore does not match the two-element row.
C · incorrect — Missing commas between the row initializers make this declaration syntactically incorrect.
D · correct — Its nested comma-separated rows match the required values and lengths 3, 2 and 3.
Question 14
Which members are good candidates for static? PI is a shared mathematical constant; the salary display reads the receiver’s salary; the hypotenuse calculation uses only side-length parameters; each Student has its own name. Select all that apply.
A. The PI field of a circle class
B. A method that displays the salary of an Employee class
C. A method that calculates the hypotenuse of a right-angle triangle class
D. A name field of a Student class
E. All except B
Hint / Module Reference (Where to Read)
Decide whether a member belongs to a class or an object, then check initialization and final restrictions.
Correct answers (select all): A, C — The PI field of a circle class; A method that calculates the hypotenuse of a right-angle triangle class
PI is one shared mathematical constant, so a static final field suits it. A hypotenuse utility that uses only parameters also needs no current object and can be static. Reading an employee receiver’s salary requires that instance, and each student’s name belongs to its own object. The aggregate option includes the instance name field, so it is not a correct complete selection.
Evidence in the complete study note
static gives one field per loaded class, shared by its instances. If count starts at zero and every constructor increments it, three creations leave count=3. Prefer ClassName.count and ClassName.utility(). A static method has no current instance, but can still use instance members through an explicit object reference.OOP07
A shared mathematical PI is a good static final candidate; a student name normally belongs to an instance. A calculation using only parameters may be static.OOP07
Choice by choice
A · correct — PI is shared across circles and is a suitable static final constant.
B · incorrect — The specified display reads receiver-specific salary state and should be an instance method.
C · correct — The specified calculation uses only parameters and is suitable as a static utility.
D · incorrect — Each student’s separate name should be an instance field.
E · incorrect — All except B still includes the per-student name field, so this set is wrong.
Question 15
Here is the general syntax for method definition:
accessModifier returnType methodName(parameterList ){
Java statements
return returnValue;
}
What is true for the accessModifier?
A. It must always be private or public.
B. It can be omitted, but if not omitted it must be private or public.
C. It can be omitted, but if not omitted there are several choices, including private
and public
D. The access modifier must agree with the type of the return value.
E. All of the above
Hint / Module Reference (Where to Read)
Locate the accessing code, declaring type, package and receiver before applying visibility rules.
Correct answer: C — It can be omitted, but if not omitted there are several choices, including private
and public
The access table includes default/no modifier, private, public and protected. Access controls visibility and has no dependency on return type.
Evidence in the complete study note
For ordinary members: private restricts access to the declaring class/nest; no modifier grants package access; protected grants same-package access plus qualified subclass access; public is widest, provided the declaring type itself is accessible. Top-level classes/interfaces may be public or package-private, not protected/private. Member types have additional visibility possibilities.OOP08
A method has modifiers, return type, name, parameter list and body: public int getAge(){return age;}.OOP11
Choice by choice
A · incorrect — Excludes protected and default
B · incorrect — Allows omission but incorrectly excludes protected
C · correct — Allows omission and the several listed access levels
D · incorrect — Return type and visibility have different roles
E · incorrect — A, B and D are false
Question 16
What is the output of the following Java 17 code?
class FinalExam{
int num1;
public FinalExam() {
num1 = 4;
}
void display() {
System.out.println(num1) ;
}
}
class Final1 extends FinalExam{
int num=3;
public Final1() {
this(5);
num1 = num;
}
public Final1(int num) {
this.num = num * num;
}
}
public class Main{
public static void main(String[] args){
Final1 f = new Final1();
f.display();
}
}
A. 4
B. 25
C. 12
D. 20
Hint / Module Reference (Where to Read)
Trace constructor delegation and initialization in the specified Java version.
Constructing Final1 first runs the parent constructor, setting num1 to 4. Subclass initialization sets num to 3. The delegated Final1(int) body receives 5 and sets num to 25. Control returns to the no-argument body, which assigns num1=num, replacing 4 with 25. display then prints inherited num1. Consistent subclass and constructor names make this an executable Java 17 trace.
Evidence in the complete study note
Under Java 17 rules, an explicit this(args) or super(args) invocation must be the first constructor statement. this invokes another constructor in the same class; super invokes the immediate superclass constructor. A constructor cannot explicitly invoke both. If there is no explicit delegation, an implicit super() is inserted; a matching accessible no-argument parent constructor must exist.OOP10
Trace parent construction first, then subclass field initializers and instance blocks in order, then the relevant subclass constructor body. With consistent class and constructor names and this(5) chaining in the FinalExam example, the parent sets num1=4, the subclass initializes num=3, this(5) sets num=25, and the no-arg body sets num1=num, leaving 25.OOP10
Choice by choice
A · incorrect — 4 is the parent’s initial num1 value, overwritten by the no-argument subclass body.
B · correct — The delegated constructor sets num=25 and the caller copies it to num1.
C · incorrect — 12 is not produced by squaring the delegated argument or by the assignments.
D · incorrect — 20 is not produced by the constructor chain.
Question 17
Which one of the following is important to implement dynamic Polymorphism?
A. Polymorphic variable
B. Method overriding
C. Inheritance
D. All of the above
Hint / Module Reference (Where to Read)
Check what compiles from the declared type, then select behavior from the actual runtime class.
Dynamic dispatch uses an inheritance hierarchy, an overridden method and a superclass reference pointing at a subclass object. The question's polymorphic variable is that reference.
Evidence in the complete study note
For Animal a=new Dog(), Animal is the declared type and Dog the actual type. The declared type determines which member operations compile. If fetch() exists only in Dog, a.fetch() fails compilation. For an eligible overridden sound(), a.sound() invokes Dog.sound() at runtime.OOP15
A subclass overrides an eligible inherited instance method with the same signature and a compatible return type; a covariant reference return may be a subtype.OOP14
class Dog extends Animal declares a subclass/derived/child of a superclass/base/parent.OOP13
Choice by choice
A · incorrect — The superclass reference can hold a child object
B · incorrect — Overriding supplies the subclass behavior
C · incorrect — Inheritance supplies the superclass/subclass relation
D · correct — All three participate in the cited dispatch model
Question 18
An accessible parent declares public abstract int value(); and its direct child is non-abstract with no inherited implementation of that method. What must the child do?
A. A child must override an abstract method inherited from its parent by defining a
method with the same signature and same return type
B. A child must define an additional method similar to the one inherited from its parent by
defining a method with the same signature and different return type.
C. Achild must not define any method with the same signature as the parent's abstract method.
D. A non-abstract child must define an abstract method with the same signature and same
return type as the parent's abstract method.
E. All of the above
Hint / Module Reference (Where to Read)
Check whether a class is concrete and whether every inherited abstract contract has an implementation.
Correct answer: A — A child must override an abstract method inherited from its parent by defining a
method with the same signature and same return type
A concrete child must implement every outstanding abstract method. Here the inherited contract has no parameters and a primitive int return, so the child must supply a public concrete implementation of that same signature and return type. The covariant reference-return exception does not apply to primitive int. A different return type, refusing to implement the method, or declaring it abstract leaves the concrete-class requirement unsatisfied.
Evidence in the complete study note
A concrete subclass must provide or inherit implementations of all required abstract methods; otherwise it must itself be abstract. If parent declares abstract String welcome(), a String welcome() implementation is required; int welcome() is incompatible, and welcome(int) merely adds an overload. A valid class can contain both the required implementation and an unrelated overload.OOP18
A subclass overrides an eligible inherited instance method with the same signature and a compatible return type; a covariant reference return may be a subtype. Visibility cannot become more restrictive, and checked exceptions cannot be broadened incompatibly.OOP14
Choice by choice
A · correct — A concrete matching no-argument int implementation, with the required public access, satisfies the inherited contract.
B · incorrect — A different return type cannot implement this primitive int-returning contract.
C · incorrect — Omitting a matching implementation leaves an abstract obligation in the concrete child.
D · incorrect — An abstract declaration supplies no implementation and cannot satisfy the concrete child’s obligation.
E · incorrect — B, C and D fail the stated implementation requirement, so the aggregate cannot be correct.
Question 19
Which of the following is true?
A. A child class can extend a parent or implement an interface, but not do both.
B. A child class can extend just one parent and can implement just one interface.
C. A child class can extend just one parent and can implement zero or more interfaces.
D. A child class can extend zero or more parents, and can implement zero or more interfaces.
Hint / Module Reference (Where to Read)
Identify the subtype or ownership relationship and distinguish class inheritance from interface contracts.
Correct answer: C — A child class can extend just one parent and can implement zero or more interfaces.
A Java class can extend one class and implement multiple interfaces.
Evidence in the complete study note
class Dog extends Animal declares a subclass/derived/child of a superclass/base/parent. A class extends one direct class and can implement multiple interfaces. Single, multilevel and hierarchical inheritance mean one parent, a chain, and several children of one parent. Java does not permit class Dog extends Animal,Mammal.OOP13
A class can extend a superclass and implement zero or more interfaces.OOP19
Choice by choice
A · incorrect — No exclusive choice between extending and implementing is stated
B · incorrect — Artificially limits interfaces to one
C · correct — One direct superclass and zero or more interfaces matches the rule
D · incorrect — Multiple direct parent classes are forbidden
Question 20
What will be the output of the program?
try {
int x = 0;
int y = 5 / x;
} catch (Exception e) {
System.out.println("Exception");
} catch (ArithmeticException ae) {
System.out.println("Arithmetic Exception");
}
System.out.println("finished");
A. Arithmetic Exception
B. finished
C. Exception
D. Compilation fails.
Hint / Module Reference (Where to Read)
Check the thrown type and catch order before tracing propagation or handler output.
Correct answer: D — Compilation fails because the subtype catch is unreachable.
Exception is caught before its subclass ArithmeticException. OOP30 says that a general catch before a subtype catch makes the latter unreachable and prevents compilation. The program therefore never executes the division or either print statement. Reasoning about which handler would run cannot bypass this compile-time restriction.
Evidence in the complete study note
Catch blocks are considered in source order. Place FileNotFoundException before IOException and IOException before Exception; a general catch before a subtype catch makes that later handler unreachable and prevents compilation.OOP30
Throwable is the root of throwable values, with Exception and Error branches. RuntimeException and Error subclasses are unchecked; other throwable classes are checked. IOException, FileNotFoundException and SQLException are standard checked examples. ArithmeticException, NullPointerException, ClassCastException and array bounds exceptions are unchecked.OOP29
Choice by choice
A · incorrect — The ArithmeticException handler is unreachable at compile time, so it cannot print its message.
B · incorrect — Compilation fails before execution; the statement following the catches never prints finished.
C · incorrect — Although Exception could catch this runtime type, the illegal later catch prevents any execution.
D · correct — The earlier Exception catch subsumes ArithmeticException, making the later handler unreachable and the program uncompilable.
Question 21
Which one of the following constant declaration statements is not possible in the Interface body?
A. static double PI = 3.14;
B. static final double PI = 3.14;
C. double PI = 3.14;
D. final double PI = 3.14;
E. None of the choices is correct
Hint / Module Reference (Where to Read)
Identify the interface contract, effective modifiers and permitted implementation forms.
Correct answer: E — None of the choices is correct
All interface fields are implicitly public, static and final; writing either, both or neither of static and final does not remove the implicit modifiers. Each PI declaration also has an initializer.
Evidence in the complete study note
No interface instance fields or constructors exist; fields are implicitly public static final.OOP19
Choice by choice
A · incorrect — static is explicit and final implicit
B · incorrect — Both static and final are explicit
C · incorrect — Both modifiers are implicit
D · incorrect — final is explicit and static implicit
E · correct — All four declarations satisfy the rule, so no listed declaration is impossible
Question 22
Which one of the following is wrong about Method Overriding?
A. Method overriding is one way of implementing polymorphism at run time.
B. Method overriding deals with methods with similar signatures in the base and derived classes.
C. Method overriding deals with implementing similar operations for different objects.
D. Method overriding is possible between any two classes.
Hint / Module Reference (Where to Read)
Check inheritance, signature compatibility, visibility and eligibility for an override.
Correct answer: D — Method overriding is possible between any two classes.
Overriding is a superclass/subclass relationship with matching method signatures and supports runtime dispatch, not a relationship between arbitrary unrelated classes.
Evidence in the complete study note
A subclass overrides an eligible inherited instance method with the same signature and a compatible return type; a covariant reference return may be a subtype.OOP14
Merely reusing a name in two unrelated classes does not establish overriding.OOP14
For an eligible overridden sound(), a.sound() invokes Dog.sound() at runtime.OOP15
Choice by choice
A · incorrect — Runtime polymorphism is an explicit purpose
B · incorrect — Matches the hierarchy and signature rule
C · incorrect — Different subclass implementations can specialize the inherited operation
D · correct — Unrelated arbitrary classes do not establish overriding
Question 23
Public classes A, B and C are in three different packages, with C extending B and B extending A. From code declared inside C, accessing fields through this, which is the complete access set? Assume ordinary instance fields with distinct names, accessible public declaring types, and no hiding.
A. All fields declared in C, and only accessible inherited protected and public fields from A and B
B. Protected, default and public data only in C and B.
C. Any data in C and only public data in A and B.
D. Protected, default and public data only in C.
Hint / Module Reference (Where to Read)
Locate the accessing code, declaring type, package and receiver before applying visibility rules.
Correct answer: A — All fields declared in C, and only accessible inherited protected and public fields from A and B
Code inside C can access C’s own fields, including private ones. Across package boundaries it can also access inherited public and protected fields through its own inherited context, here represented by this. It cannot access package-private or private ancestor fields directly. Consequently A gives the complete set; the public-only choice is incomplete because qualifying protected inherited access is also permitted.
Evidence in the complete study note
For ordinary members: private restricts access to the declaring class/nest; no modifier grants package access; protected grants same-package access plus qualified subclass access; public is widest, provided the declaring type itself is accessible. Top-level classes/interfaces may be public or package-private, not protected/private. Member types have additional visibility possibilities.OOP08
Across packages, a subclass accessing a protected instance member must do so through its own inherited context or an appropriate subclass-typed receiver, not any arbitrary superclass object.OOP08
Choice by choice
A · correct — This includes C’s own fields and the inherited public/protected access permitted through this.
B · incorrect — Package-private ancestor fields in different packages are not accessible, and A’s inherited access is omitted.
C · incorrect — This omits accessible inherited protected fields and therefore is not the complete set.
D · incorrect — This omits C’s own private access and permitted inherited ancestor access.
Question 24
Inside an instance method, which shown forms invoke an accessible no-argument non-static method? Methodname stands for a valid method name, Objectname for a compatible object reference, and Classname for a type name. Select all that apply.
A. Methodname()
B. Classname.methodname()
C. Objectname.methodname()
D. Variablename.methodname
Hint / Module Reference (Where to Read)
Separate parameters from arguments and operations that read state from operations that change it.
Correct answers (select all): A, C — Methodname(); Objectname.methodname()
An unqualified call inside a suitable instance context uses implicit this, so Methodname() is valid. An object-qualified call explicitly supplies the receiver and is also valid. A type name alone cannot invoke a non-static method without an object. The final form lacks invocation parentheses and therefore does not invoke a method. These are deliberate syntax alternatives under the stated placeholder meanings.
Evidence in the complete study note
A method has modifiers, return type, name, parameter list and body: public int getAge(){return age;}. A void method returns no value. Parameters name the inputs in the declaration; arguments supply values at a call. An instance method can be invoked as object.method(), or with an implicit this inside suitable instance context.OOP11
Java this and super are unavailable as current-instance references in static context.OOP16
Choice by choice
A · correct — The unqualified call uses implicit this in the stated instance context.
B · incorrect — A class name alone does not provide the required instance receiver.
C · correct — The object-qualified call supplies the instance receiver.
D · incorrect — Without parentheses this form does not perform a method invocation.
Question 25
In Java, Base declares an eligible instance method m(), Sub overrides it, and an object’s exact runtime class is Sub. Inside an instance method declared in Sub, what happens on an unqualified call m()? Assume no further subclass or explicit super call.
A. The Compiler will choose randomly the method to be executed
B. It will always refer to the version of that method defined by the subclass
C. Compile time error will occur
D. It will always refer to the version of that method defined by the superclass
Hint / Module Reference (Where to Read)
Check what compiles from the declared type, then select behavior from the actual runtime class.
Correct answer: B — It will always refer to the version of that method defined by the subclass
The unqualified invocation uses the current Sub object as receiver. Since m is an eligible overridden instance method and the exact runtime class is Sub, dynamic dispatch selects Sub’s implementation. The compiler does not choose randomly, and the valid declaration produces no compilation error. An explicit super.m() would request the parent version, but that is excluded by the specified call expression.
Evidence in the complete study note
For Animal a=new Dog(), Animal is the declared type and Dog the actual type. The declared type determines which member operations compile. If fetch() exists only in Dog, a.fetch() fails compilation. For an eligible overridden sound(), a.sound() invokes Dog.sound() at runtime.OOP15
An unqualified instance call may dispatch dynamically; an explicit super call is different.OOP16
Choice by choice
A · incorrect — Dispatch follows the language’s receiver and overriding rules, not random choice.
B · correct — The exact Sub receiver dispatches the ordinary call to Sub.m().
C · incorrect — The stated accessible, eligible declaration and call compile.
D · incorrect — The superclass version would require a different dispatch situation such as explicit super.m().
Question 26
Which of the following statements not true?
A. A private member of a class cannot be accessed by the methods of the same class
B. A public member of a class can be accessed in all the packages
C. A private member of a class cannot be accessed from its derived class
D. A protected member of a class can be accessed from its derived class.
Hint / Module Reference (Where to Read)
Locate the accessing code, declaring type, package and receiver before applying visibility rules.
Correct answer: A — A private member of a class cannot be accessed by the methods of the same class
Private visibility is class-only, so methods of the declaring class can access that member. Public is world-visible; protected includes subclasses.
Evidence in the complete study note
For ordinary members: private restricts access to the declaring class/nest; no modifier grants package access; protected grants same-package access plus qualified subclass access; public is widest, provided the declaring type itself is accessible. Top-level classes/interfaces may be public or package-private, not protected/private. Member types have additional visibility possibilities.OOP08
Across packages, a subclass accessing a protected instance member must do so through its own inherited context or an appropriate subclass-typed receiver, not any arbitrary superclass object. protected therefore does not mean “subclasses only”: unrelated classes in the same package also have access. A class’s own main method can access private fields of an instance of that class.OOP08
Choice by choice
A · correct — False: same-class methods have access
B · incorrect — Public visibility includes other packages
C · incorrect — A child cannot directly access a parent's private member
D · incorrect — Protected includes subclass access
Question 27
_________is one of the basic principles of object oriented programming that use one object
in multiple forms.
A. Inheritance
B. Interface
C. Encapsulation
D. None of the above
Hint / Module Reference (Where to Read)
Identify whether the emphasis is grouping state, hiding implementation, exposing essentials or varying behavior.
Taking many forms is polymorphism. It is not explicitly listed, so the none option is the correct selection.
Evidence in the complete study note
Inheritance forms a subtype relationship and may reuse implementation. Polymorphism lets code using a common type invoke behavior appropriate to different concrete objects.OOP02
Encapsulation groups related state and operations and controls access.OOP02
interface Payable{double getPaymentAmount();} declares an abstract public operation. class Invoice implements Payable must provide public double getPaymentAmount(), perhaps returning getQuantity()*getPricePerItem().OOP19
Choice by choice
A · incorrect — Inheritance acquires parent properties
B · incorrect — Interface defines a contract rather than naming the many-forms principle
C · incorrect — Encapsulation groups and hides data
D · correct — The principle is polymorphism
Question 28
Consider the program:
public class Student {
int id;
int section;
void display() {
System.out.println("ID : " + id);
System.out.println("Section : " + section); }
public static void main(String[] args) {
/*Create an object*/ }}
Which of the following is a correct way to create an object in the main method of the above
program?
A. Student stud = Student (3983,20);
B. Student stud;
C. Student stud=new Student ();
D. Student stud =new Student (3983,2);
Hint / Module Reference (Where to Read)
Separate a reference declaration, object allocation, reference copying and changes to the shared object.
No constructor is declared in Student, so the default no-argument construction pattern applies. A reference declaration alone does not create an object.
Evidence in the complete study note
Student s; declares a reference variable; it creates no Student object. Student s=new Student(); allocates and initializes an instance.OOP03
If a class declares no constructor, Java supplies a default constructor. If Circle(double r) is declared, new Circle() fails unless a no-argument constructor is also declared.OOP09
Choice by choice
A · incorrect — Missing new and invokes an undeclared parameterized constructor
B · incorrect — Declares only a reference
C · correct — Uses new and the implicit no-argument constructor
D · incorrect — No matching two-argument constructor is declared
Question 29
Default, public , protected, private are?
A. Access Modifier
B. Non-access Modifiers
C. Both A and B
D. It's variable
Hint / Module Reference (Where to Read)
Locate the accessing code, declaring type, package and receiver before applying visibility rules.
The access table names no modifier/default, public, protected and private as visibility levels.
Evidence in the complete study note
For ordinary members: private restricts access to the declaring class/nest; no modifier grants package access; protected grants same-package access plus qualified subclass access; public is widest, provided the declaring type itself is accessible. Top-level classes/interfaces may be public or package-private, not protected/private. Member types have additional visibility possibilities.OOP08
Choice by choice
A · correct — They control accessibility
B · incorrect — They are visibility modifiers rather than non-access properties such as static
C · incorrect — No basis for classifying the same list as both
D · incorrect — They are not a variable
Question 30
Java Source Code is compiled into ______________.
A. .Obj
B. Source Code
C. Bytecode
D. .Exe
Hint / Module Reference (Where to Read)
Check declaration order, exact case, package boundaries and the compile-versus-launch stage.
// begins a single-line comment; /* and /** begin block comments.
Evidence in the complete study note
A single-line Java comment begins with // and continues to the end of that line. A block comment begins with /* and ends with */. A documentation comment begins with /** and ends with */ and can be processed by Javadoc. Comment text does not execute as program statements.OOP-S01
Choice by choice
A · incorrect — Starts documentation-style block comments
B · correct — The single-line delimiter
C · incorrect — Starts a block comment
D · incorrect — The required delimiter is listed as B
Question 32
How to compile java code in command prompt?
A. javac filename.java
B. java filename.java
C. javac filename
D. java filename
Hint / Module Reference (Where to Read)
Check declaration order, exact case, package boundaries and the compile-versus-launch stage.
The FileNotFound example shows C:\>javac FilenotFound_Demo.java, establishing the compiler command with a .java source filename.
Evidence in the complete study note
Ordinary compilation uses javac Test.java, producing bytecode, then java Test launches the class. Modern Java can also launch a source file using java Test.java; distinguish source-file launch from running a compiled class.OOP28
Choice by choice
A · correct — Matches the javac compilation command
B · incorrect — Uses java rather than the demonstrated compiler
C · incorrect — Omits the .java source suffix
D · incorrect — Uses the runtime command name rather than javac
Question 33
An ordinary class named filename has already been compiled to filename.class, is in the current directory with no package, and has a valid main method. Which command launches that compiled class? Use class launch, not source-file mode.
A. javac filename.java
B. java filename.java
C. javac filename
D. java filename
Hint / Module Reference (Where to Read)
Check declaration order, exact case, package boundaries and the compile-versus-launch stage.
The Java launcher takes the compiled class’s name for ordinary class launch, so java filename runs the available main method. javac filename.java compiles a source file and is a separate step. Modern Java also supports source-file launch with a .java argument, but the revised question explicitly asks for the already compiled class. The compiler invocation without the source extension is not the requested launch either.
Evidence in the complete study note
Ordinary compilation uses javac Test.java, producing bytecode, then java Test launches the class. Modern Java can also launch a source file using java Test.java; distinguish source-file launch from running a compiled class.OOP28
Choice by choice
A · incorrect — This compiles source rather than launching the existing compiled class.
B · incorrect — This is source-file launch, excluded by the requested class-launch mode.
C · incorrect — This is a compiler invocation rather than the requested class launch.
D · correct — java filename launches the named compiled class.
Question 34
Java is case sensitive?
A. True
B. False
C. Depends On Complier
D. May be true or false
Hint / Module Reference (Where to Read)
Check declaration order, exact case, package boundaries and the compile-versus-launch stage.
OOP28 explicitly states that Java identifiers are case sensitive. Changing the capitalization of a name can therefore change what it denotes or make a reference unresolved. This is a language rule rather than a compiler preference, so the conditional or uncertain answers do not describe standard Java behavior.
Evidence in the complete study note
Java identifiers are case sensitive; $ is allowed but @ is not an identifier character.OOP28
Choice by choice
A · correct — True directly matches the note’s explicit statement that Java identifiers are case sensitive.
B · incorrect — False contradicts the explicit identifier case-sensitivity rule stated in OOP28.
C · incorrect — Case sensitivity is a Java language rule, not an option depending on the compiler implementation.
D · incorrect — The note states a definite language property rather than a true-or-false implementation-dependent possibility.
Question 35
Which is the most complete description of the standard introductory naming conventions and ordinary public-top-level-class file rule in Java? Treat “should” in A and B as style advice, not a syntax requirement, and “class” in C as the public top-level class in a .java source file.
A. For all class names the first letter should be in Upper Case.
B. All method names should start with a Lower Case letter.
C. Name of the program file should exactly match the class name.
D. All of the above
Hint / Module Reference (Where to Read)
Check declaration order, exact case, package boundaries and the compile-versus-launch stage.
Capitalized class initials and lowercase method initials are conventional Java style, not universal syntax requirements. An ordinary public top-level class must match its source filename’s base name. The scope makes A and B recommendations and C the specific file rule. Each is then true, but D is the most complete selection because it includes all three rather than one isolated part.
Evidence in the complete study note
For ordinary public top-level types, filename and type name match. Capitalized class names and lowercase method names are conventions, not universal syntax requirements.OOP28
Choice by choice
A · incorrect — This is valid style advice but only one part of the complete set.
B · incorrect — This is valid style advice but omits the other convention and file rule.
C · incorrect — This is the file rule for the specified public top-level class but is incomplete alone.
D · correct — All three are valid under the stated convention and file-rule scope.
Question 36
All Java components require names. Names used for classes, variables, and methods are called?
A. Variables
B. identifiers
C. Access Modifiers
D. Java Modifiers
Hint / Module Reference (Where to Read)
Check the lexical category and whether the notation names a value, a declaration or non-executed source text.
Identifiers are programmer-given names. Names attached to classes, variables and methods serve that role.
Evidence in the complete study note
An identifier is a programmer-chosen name for an entity such as a class, method or variable. A reserved keyword has a language-defined role and cannot be used as an ordinary identifier. A literal writes a value directly, such as an integer, floating-point number, quoted character, quoted string or Boolean value.OOP-S01
For ordinary members: private restricts access to the declaring class/nest; no modifier grants package access; protected grants same-package access plus qualified subclass access; public is widest, provided the declaring type itself is accessible.OOP08
Choice by choice
A · incorrect — A variable is one named entity, not the name category
B · correct — Matches programmer-given names
C · incorrect — Controls visibility rather than naming
D · incorrect — Modifiers change declarations rather than supply their names
Question 37
Which of the following is smallest integer data type ?
A. int
B. byte
C. short
D. long
Hint / Module Reference (Where to Read)
Identify the primitive category, width and conversion rule before evaluating a declaration or expression.
The actual PDF page-six widening diagram orders byte -> short -> int -> long -> float (and onward to double); the text says widening requires the destination to be wider than the source. Among byte, short, int and long, byte is therefore the smallest in this module diagram. The diagram is a raster/embedded visual omitted from extracted text, so the exact textual citation supplies the associated width condition rather than fabricating a diagram quotation.
Evidence in the complete study note
Java has byte, short, int, long, float, double, char and boolean. Signed integer widths are 8,16,32,64 bits respectively. byte ranges from -128 to 127; short from -32768 to 32767.OOP06
Choice by choice
A · incorrect — int appears after byte and short in the widening diagram
B · correct — byte is the earliest/narrowest listed integer type in the diagram
C · incorrect — short is wider than byte in the diagram
D · incorrect — long appears after int in the diagram
Question 38
Which of the following is not a primitive data type ?
A. byte
B. enum
C. short
D. int
Hint / Module Reference (Where to Read)
Identify the primitive category, width and conversion rule before evaluating a declaration or expression.
Correct answer: D — double is not an integer primitive type.
OOP06 lists byte, short, int and long as the signed integer types with widths 8,16,32,64 bits. Of the supplied options, long, byte and short belong to that group. double represents floating-point values rather than an integer primitive, so it is the exception requested by the question.
Evidence in the complete study note
Java has byte, short, int, long, float, double, char and boolean. Signed integer widths are 8,16,32,64 bits respectively.OOP06
Choice by choice
A · incorrect — long is the 64-bit signed integer primitive in the note’s integer-width sequence.
B · incorrect — byte is the 8-bit signed integer primitive with the stated range -128 to 127.
C · incorrect — short is the 16-bit signed integer primitive with the stated range -32768 to 32767.
D · correct — double belongs to the floating numeric types rather than the signed integer primitive group.
Question 40
Character data type cannot store following value.
A. Digit
B. Letter
C. Special Character
D. String
Hint / Module Reference (Where to Read)
Identify the primitive category, width and conversion rule before evaluating a declaration or expression.
Character literals such as 'M' represent individual characters, while strings such as "Hi" are sequences of characters. A whole String is not one char value.
Evidence in the complete study note
char is an unsigned 16-bit UTF-16 code unit and can hold a digit, letter or symbol, not a whole String.OOP06
Choice by choice
A · incorrect — A digit can be a single character, not a multi-character string
B · incorrect — A letter is a single character, illustrated by M
C · incorrect — A special symbol can be one character
D · correct — A string is a sequence rather than one character
Question 41
Range of Byte Data Type is ____________.
A. -128 to 128
B. -127 to 127
C. -127 to 128
D. -128 to 127
Hint / Module Reference (Where to Read)
Identify the primitive category, width and conversion rule before evaluating a declaration or expression.
OOP06 states that byte ranges from -128 to 127. These inclusive endpoints provide 256 values for an 8-bit signed type. Options that include positive 128 exceed the upper endpoint, and those starting at -127 omit the lowest permitted value. Only D preserves both limits correctly.
Evidence in the complete study note
byte ranges from -128 to 127; short from -32768 to 32767.OOP06
Choice by choice
A · incorrect — The upper endpoint 128 is one greater than the largest byte value 127.
B · incorrect — The lower endpoint -127 omits the valid minimum byte value -128.
C · incorrect — Both endpoints are wrong: -128 is omitted and the invalid positive value 128 is included.
D · correct — The inclusive limits -128 and 127 exactly match the byte range stated in OOP06.
Question 42
What is size of integer in Java Programming.
A. 1 Bytes
B. 2 Bytes
C. 4 Bytes
D. 8 Bytes
Hint / Module Reference (Where to Read)
Identify the primitive category, width and conversion rule before evaluating a declaration or expression.
In OOP06’s ordered list, int is the 32-bit signed integer type. Converting 32 bits at eight bits per byte gives four bytes. The question concerns Java’s fixed int width rather than implementation-dependent C++ sizes. The one-, two- and eight-byte options correspond to different integer widths.
Evidence in the complete study note
Signed integer widths are 8,16,32,64 bits respectively.OOP06
Correct answer: D — long is the 64-bit integer primitive.
OOP06 identifies long as the 64-bit signed integer primitive, following byte, short and int at 8,16 and 32 bits. That directly matches the question’s storage-width interpretation. boolean represents logical values, int has only 32 bits, and float is not the stated 64-bit integer storage type.
Evidence in the complete study note
Java has byte, short, int, long, float, double, char and boolean. Signed integer widths are 8,16,32,64 bits respectively.OOP06
OOP06 gives the Java short range as -32768 through 32767. The question asks for its minimum, so the negative lower endpoint is required. -32767 is one above the minimum; positive 32767 is the maximum, and positive 32768 is outside the stated range entirely.
Evidence in the complete study note
byte ranges from -128 to 127; short from -32768 to 32767.OOP06
Choice by choice
A · correct — -32768 is exactly the lower endpoint of the short range given in OOP06.
B · incorrect — -32767 is representable but is one above the minimum short value.
C · incorrect — 32768 is above the maximum short value and cannot be its minimum.
D · incorrect — 32767 is the maximum short value, whereas the question asks for the minimum.
Question 45
What default value does a Java boolean instance field receive before any explicit initializer or constructor assignment?
A. TRUE
B. false
C. null
D. garbage
Hint / Module Reference (Where to Read)
Locate the declaration scope and check default initialization versus definite assignment.
Java fields receive defined initial values before ordinary explicit initialization. For primitive boolean fields that value is false. true is the other Boolean value, null is a reference value rather than a Boolean value, and Java does not expose an uninitialized field as garbage. The question specifically selects an instance field, so local-variable definite-assignment rules do not change the answer.
Evidence in the complete study note
Java fields and array elements receive defaults: numeric zero, char '\u0000', boolean false and references null. A local int t; followed by printing t is a compilation error.OOP05
Choice by choice
A · incorrect — true is not the default Boolean field value.
B · correct — false is the default value of a boolean field.
C · incorrect — null is a reference default and cannot be a primitive boolean value.
D · incorrect — Java supplies a defined field default rather than a garbage value.
Question 46
What will be the output of the program?
class Main {
public static void main(String args[]) {
int t;
System.out.println(t);
}
}
A. 0
B. garbage value
C. compiler error
D. runtime error
Hint / Module Reference (Where to Read)
Locate the declaration scope and check default initialization versus definite assignment.
t is a local variable read before assignment. Local variables must be initialized before use and have no default value.
Evidence in the complete study note
Locals occur in methods, constructors or blocks; they must be definitely assigned before use and cannot have public/private/protected modifiers.OOP05
A local int t; followed by printing t is a compilation error.OOP05
Choice by choice
A · incorrect — Incorrectly applies a field-style default
B · incorrect — Locals cannot be read as an arbitrary garbage value
C · correct — Violates the initialization-before-use requirement
D · incorrect — The violation arises before execution rather than as a runtime failure
Question 47
What will be the output of the program?
class Test {
public static void main(String[] args) {
for(int i = 0; 0; i++)
{
System.out.println(""Hello"");
break;
}
}
}
A. Hello
B. Empty Output
C. Compiler error
D. Runtime error
Hint / Module Reference (Where to Read)
Identify the primitive category, width and conversion rule before evaluating a declaration or expression.
The for condition is integer literal 0, whereas OOP06 explicitly says for(...;0;...) is invalid in Java. The doubled quotes around Hello are another source syntax defect. Compilation therefore fails before any loop or print can execute. Treating zero as a false Java condition would incorrectly import C++ numeric truth conversion.
Evidence in the complete study note
boolean does not convert to or from numeric truth values; if(0) and for(...;0;...) are invalid.OOP06
An identifier is a programmer-chosen name for an entity such as a class, method or variable. A reserved keyword has a language-defined role and cannot be used as an ordinary identifier. A literal writes a value directly, such as an integer, floating-point number, quoted character, quoted string or Boolean value.OOP-S01
A while header is while(condition). A basic for header is for(initialization; condition; update). A do-while statement places its condition after the body. An if selects its true branch or, when present, its else branch; only the selected branch executes.OOP-S03
Choice by choice
A · incorrect — No Hello output occurs because the invalid loop condition prevents compilation.
B · incorrect — Zero is not a legal false condition in Java; this is a compile-time error rather than a valid zero-iteration loop.
C · correct — The numeric condition and malformed quoted text are compile-time source defects.
D · incorrect — The program fails translation before execution, so the relevant failure is not a runtime exception.
Question 48
What will be the output of the program?
class mainclass {
public static void main(String args[])
{
boolean var1 = true;
boolean var2 = false;
if (var1)
System.out.println(var1);
else
System.out.println(var2);
}
}
A. 0
B. 1
C. true
D. FALSE
Hint / Module Reference (Where to Read)
Respect operator grouping and operand types, then trace each operation in evaluation order.
var1 is initialized to true, so the if body executes and prints var1. The else body is skipped, so var2 does not appear. Java’s Boolean output is the lowercase word true, followed by the newline from println. It does not use numeric 1 or uppercase TRUE. Correcting C’s case makes it the exact visible output rather than an approximate description.
Evidence in the complete study note
Printing Boolean true gives lowercase true, not 1 or uppercase TRUE.OOP23
A while header is while(condition). A basic for header is for(initialization; condition; update). A do-while statement places its condition after the body. An if selects its true branch or, when present, its else branch; only the selected branch executes.OOP-S03
Choice by choice
A · incorrect — The chosen true Boolean value does not print as numeric 0.
B · incorrect — Java Boolean output is not encoded as numeric 1.
C · correct — The true branch prints the lowercase word true.
D · incorrect — The false value is not printed because the else branch is skipped.
Question 49
What is the numerical value computed by the final expression, rounded to eight digits after the decimal point? This asks for the rounded value, not the exact unformatted console string.
class average {
public static void main(String args[])
{
double num[] = {5.5, 10.1, 11, 12.8, 56.9, 2.5};
double result;
result = 0;
for (int i = 0; i<6; ++i)
result = result + num[i];
System.out.print(result/6);
}
}
A. 16.34
B. 16.56666664
C. 16.46666667
D. 16.76666667
Hint / Module Reference (Where to Read)
Trace every element or API argument and distinguish copying values from aliasing a reference.
The six listed numbers sum to 98.8 mathematically. Dividing by six gives approximately 16.4666666667, which rounds to 16.46666667 at eight decimal places. Small binary-double representation differences do not affect that rounding here. The original unformatted print call does not impose eight-place formatting, so the revised question explicitly requests a rounded numerical value rather than claiming this is its exact console string.
Evidence in the complete study note
For int[] a=new int[4], setting a[i]=i*3 and accumulating yields 0+3+6+9=18. To average an array, sum every element and divide by its length using floating arithmetic; handle zero length separately. Floating representations and printing can differ from a rounded mathematical result. For the six-value example, the mathematical average is 98.8/6, approximately 16.46666667; the exact printed string also depends on floating representation and formatting.OOP27
Valid indices are 0..a.length-1; an invalid access throws ArrayIndexOutOfBoundsException.OOP26
Choice by choice
A · incorrect — 16.34 is not the sum divided by six at the requested precision.
B · incorrect — 16.56666664 differs from the computed mean before rounding.
C · correct — 16.46666667 is the mean rounded to eight decimal places.
D · incorrect — 16.76666667 does not match the computed mean.
Question 50
What will be the output of the program?
class increment {
public static void main(String args[])
{
int g = 4;
System.out.print(++g * 8);
}
}
A. 32
B. 36
C. 40
D. 48
Hint / Module Reference (Where to Read)
Track the old and updated values separately and distinguish a character operand from a string.
The prefix increment changes g from 4 to 5 before its value is used in multiplication. The expression therefore computes 5*8=40 and prints that integer. This differs from postfix increment, which would supply the old value to the multiplication. Only one increment occurs in this expression.
Evidence in the complete study note
Starting x=5, printing x++ then ++x gives 5 then 7.OOP24
Java evaluates operands left to right while respecting precedence.OOP23
Choice by choice
A · incorrect — 32 would multiply the old value 4 by 8, which does not respect prefix increment.
B · incorrect — 36 is not the product of either the old value 4 or updated value 5 with 8.
C · correct — Prefix increment supplies 5, so the printed product is 5 times 8, or 40.
D · incorrect — 48 requires g to become 6, but the single increment changes it only from 4 to 5.
Question 51
What will this program print when run on Java 17?
class area {
public static void main(String args[])
{
double r, pi, a;
r = 9.8;
pi = 3.14;
a = pi * r * r;
System.out.println(a);
}
}
A. 301.5656
B. 301
C. 301.56
D. 301.57
Hint / Module Reference (Where to Read)
Read the cited conceptual rules, state the model, and apply them before comparing the alternatives.
Java groups pi * r * r as (pi * r) * r and rounds each double multiplication using binary64 arithmetic. The resulting value has hexadecimal representation 0x1.2d90cb295e9e2p+8. Java 17’s standard conversion prints that value as 301.5656, followed by println’s line terminator. The supplementary Oracle rules establish the precise arithmetic and text conversion; no separate decimal-place formatting is applied.
Evidence in the complete study note
Java 17 float uses IEEE 754 binary32, and double uses binary64. Successive multiplications group from left to right. Each floating-point operation rounds to its representable result, using nearest-value rounding with ties to even; regrouping a product can change its result.OOP-S02
PrintStream.print(double) converts the stored value through String.valueOf and Double.toString. For finite nonzero magnitudes from 0.001 inclusive to 10000000 exclusive, the standard decimal form uses at least one fractional digit and only the further digits needed to distinguish the value from adjacent doubles. println(double) also adds a line terminator. This is not fixed-decimal-place formatting.OOP-S02
Additional authoritative reference
Successive multiplications group from left to right. Java 17 double operations use binary64 with each product rounded to the nearest representable value; applying these rules gives 0x1.2d90cb295e9e2p+8 for this expression.
For a finite double of this magnitude the decimal representation uses only the fractional digits needed to distinguish the value from adjacent doubles. The computed value is the same binary64 value as literal 301.5656, and this decimal is its distinguishing representation.
The prefix decrement reduces g from 6 to 5 before multiplication uses it. The resulting integer expression is 5*8, which equals 40. The updated value is used immediately; it is not the old 6 and no later increment occurs. Thus the integer printed is 40.
Evidence in the complete study note
Prefix ++ and -- update a variable before supplying its value; postfix forms supply the old value before the update. Multiplication, division and remainder bind before addition and subtraction; same-level binary arithmetic groups left to right. Integer division truncates toward zero.OOP-S03
Java evaluates operands left to right while respecting precedence.OOP23
Choice by choice
A · incorrect — 48 uses the old value 6, which would not reflect the prefix decrement before multiplication.
B · correct — Prefix decrement supplies 5 to the multiplication, producing 5*8=40.
C · incorrect — 56 uses 7, but decrement reduces the initial 6 instead of increasing it.
D · incorrect — 44 is not 5 multiplied by 8 and does not follow the stated prefix update.
Question 53
To declare more than one variable of the specified type, we can use a __________ list.
A. colon-separated
B. bracket-separated
C. comma-separated
D. None of the above
Hint / Module Reference (Where to Read)
Locate the declaration scope and check default initialization versus definite assignment.
Correct answer: C — A comma-separated declarator list.
OOP05 illustrates a declaration with int a=10,b=10, separating the declarators with a comma. The shared type applies to each name in that declaration. Colons and brackets serve other syntactic purposes and do not separate ordinary variable declarators in the example. The comma-separated option states the required list form.
Evidence in the complete study note
Initializers such as int a=10,b=10; assign initial values.OOP05
Choice by choice
A · incorrect — A colon does not separate the ordinary variable declarators shown in the note’s shared-type declaration.
B · incorrect — Brackets describe array types or indexing rather than separating names in a declarator list.
C · correct — The example int a=10,b=10 uses a comma between variable declarators sharing the type int.
D · incorrect — Comma-separated is an offered and supported list form, so none of the above is false.
Question 54
In the introductory grouping by declaration scope and class-versus-instance ownership, how many categories of Java variables are distinguished? Include parameter and block-local contexts within the local category.
A. 2
B. 3
C. 4
D. 5
Hint / Module Reference (Where to Read)
Locate the declaration scope and check default initialization versus definite assignment.
The introductory grouping distinguishes local variables, instance fields and class/static fields. Locals belong to method, constructor or block execution; instance fields belong to individual objects; static fields belong to the class. This gives three categories. The question uses that teaching grouping rather than counting every variable category distinguished by the full language specification.
Evidence in the complete study note
The introductory three-way grouping is local, instance and class/static variables.OOP05
Choice by choice
A · incorrect — Two categories cannot account for all three of local, instance and class/static variables.
B · correct — The specified introductory grouping contains local, instance and class/static categories: three.
C · incorrect — Four exceeds the three categories in the specified grouping.
D · incorrect — Five exceeds the three categories in the specified grouping.
Question 55
Local variables are declared in?
A. methods
B. constructors
C. blocks
D. All of the above
Hint / Module Reference (Where to Read)
Locate the declaration scope and check default initialization versus definite assignment.
A static field belongs to the loaded class and is shared by its instances. ClassName.field makes that ownership explicit and is the recommended qualification. An object reference can sometimes qualify a static member, but it obscures the class-level nature and is not the preferred form asked for. Function names do not supply the owning type, and the style rule gives a definite answer.
Evidence in the complete study note
static gives one field per loaded class, shared by its instances. If count starts at zero and every constructor increments it, three creations leave count=3. Prefer ClassName.count and ClassName.utility().OOP07
With Animal a=new Dog(), a.staticMethod() resolves using Animal’s compile-time type. Prefer Animal.staticMethod() for clarity.OOP16
Choice by choice
A · incorrect — Object qualification can be legal, but it is not the preferred class-ownership notation.
B · correct — Class qualification is the preferred notation for a static field.
C · incorrect — A function name does not identify the field’s owning type as a qualifier.
D · incorrect — The note provides a definite preferred class-qualified form.
Question 57
Which of the following is an Example of variable initialization?
A. int a, b, c;
B. int a = 10, b = 10;
C. int 10 = a;
D. None of the above
Hint / Module Reference (Where to Read)
Locate the declaration scope and check default initialization versus definite assignment.
The declaration double c = 8.4 illustrates assignment of an initial value at declaration; B follows the same type-name-equals-value pattern for a and b.
Evidence in the complete study note
Initializers such as int a=10,b=10; assign initial values.OOP05
An identifier is a programmer-chosen name for an entity such as a class, method or variable. A reserved keyword has a language-defined role and cannot be used as an ordinary identifier. A literal writes a value directly, such as an integer, floating-point number, quoted character, quoted string or Boolean value.OOP-S01
Choice by choice
A · incorrect — Declares variables without initial values
B · correct — Assigns initial values 10 to named variables
C · incorrect — Places a literal where the declared name belongs
D · incorrect — B demonstrates initialization
Question 58
Access modifiers cannot be used for local variables.
A. Yes
B. No
C. Can be yes or no
D. Cannot say
Hint / Module Reference (Where to Read)
Locate the declaration scope and check default initialization versus definite assignment.
Correct answer: D — Both numeric values and characters can participate in arithmetic.
OOP06 states that arithmetic promotes char, byte and short to int in many expressions. Characters are therefore allowed alongside numeric operands. boolean does not convert to numeric truth values and is not an arithmetic operand. D gives the complete supported pair; A and C each mention only part of that operand domain.
Evidence in the complete study note
Arithmetic promotes char, byte and short to int in many expressions. boolean does not convert to or from numeric truth values; if(0) and for(...;0;...) are invalid.OOP06
Choice by choice
A · incorrect — Characters are permitted through promotion, but this option alone omits the also-permitted numeric operand category.
B · incorrect — Java boolean does not convert to numeric values for arithmetic, as OOP06 explicitly states.
C · incorrect — Numeric operands are permitted, but this option alone omits the also-permitted character category.
D · correct — Both numeric and char operands are permitted; chars undergo numeric promotion for arithmetic.
Question 60
Modulus operator, %, can be applied to which of these?
A. Both Integers and floating - point numbers
B. Integers
C. Floating - point numbers
D. None of the mentioned
Hint / Module Reference (Where to Read)
Respect operator grouping and operand types, then trace each operation in evaluation order.
Correct answer: A — Both integers and floating-point numbers in Java.
OOP23 explicitly contrasts Java with C++: Java % accepts floating-point operands as well as integers. This course’s Java context therefore makes A the complete domain among the offered choices. B and C each name only one supported category. Importing C++’s integral-only restriction would give the wrong answer for Java.
Evidence in the complete study note
Unlike C++, Java % also accepts floating-point operands.OOP23
Choice by choice
A · correct — Both integer and floating-point operands are accepted by Java’s remainder operator according to OOP23.
B · incorrect — Integers are allowed, but this option alone omits Java’s also-supported floating-point operands.
C · incorrect — Floating-point values are allowed, but this option alone omits the also-supported integer operands.
D · incorrect — The note explicitly supports both supplied operand categories, so none of the mentioned is false.
Question 61
Evaluate the value of the expression?
6 - 2 + 10 % 4 + 7
A. 14
B. 12
C. 13
D. 10
Hint / Module Reference (Where to Read)
Respect operator grouping and operand types, then trace each operation in evaluation order.
The remainder operation is evaluated first: 10%4 is 2. The remaining additions and subtraction group left to right, yielding 6-2+2+7 = 4+2+7 = 13. OOP23 includes the same expression and result. No floating conversion or increment operation appears in this calculation.
Evidence in the complete study note
Java evaluates operands left to right while respecting precedence.OOP23
6-2+10%4+7 is 13.OOP23
Prefix ++ and -- update a variable before supplying its value; postfix forms supply the old value before the update. Multiplication, division and remainder bind before addition and subtraction; same-level binary arithmetic groups left to right. Integer division truncates toward zero.OOP-S03
Choice by choice
A · incorrect — 14 does not follow the remainder 10%4=2 and the resulting sum 6-2+2+7.
B · incorrect — 12 is one below the computed total and does not respect the stated remainder result.
C · correct — Evaluating 10%4 first gives 2; then 6-2+2+7 equals 13.
D · incorrect — 10 omits or miscalculates part of the expression; the full integer evaluation gives 13.
Question 62
What is the output of this program?
class Main {
public static void main(String args[])
{
double var1 = 2 + 4;
double var2 = var1 / 4;
int var3 = 2 + 4;
int var4 = var3 / 4;
System.out.print(var2 + " " + var4);
}
}
A. 0 1
B. 1 1
C. 1.5 1
D. 1.5 1.0
Hint / Module Reference (Where to Read)
Respect operator grouping and operand types, then trace each operation in evaluation order.
Both additions initially produce 6. Assigning one to double makes var1=6.0, so var1/4 gives 1.5. var3 remains int, so var3/4 truncates to integer 1. The string containing a space then concatenates their representations, producing 1.5 1 rather than giving the integer result a decimal suffix.
Evidence in the complete study note
Integer 6/4 is 1; double 6.0/4 is 1.5.OOP23
Once a String operand is encountered, + concatenates in left-to-right groups: 1+2+"x" gives "3x", while "x"+1+2 gives "x12".OOP24
A while header is while(condition). A basic for header is for(initialization; condition; update). A do-while statement places its condition after the body. An if selects its true branch or, when present, its else branch; only the selected branch executes.OOP-S03
Choice by choice
A · incorrect — The double division of 6.0 by 4 yields 1.5, not zero.
B · incorrect — The first quotient is floating point and retains .5 rather than becoming integer 1.
C · correct — The double quotient prints 1.5, followed by the space and integer quotient 1.
D · incorrect — var4 is int, so its string representation is 1 rather than 1.0.
Question 63
What will be the output of the program?
class Bitwise
{
public static void main(String [] args)
{
int x = 11 & 9;
int y = x ^ 3;
System.out.println( y | 12 );
}
}
A. 7
B. 0
C. 14
D. 8
Hint / Module Reference (Where to Read)
Respect operator grouping and operand types, then trace each operation in evaluation order.
The AND produces 11&9 = 1011&1001 = 1001, or 9. XOR with 3 gives 1001^0011 = 1010, or 10. OR with 12 then gives 1010|1100 = 1110, or 14. OOP23 explicitly provides this chain; these are integer bitwise operations, not Boolean short-circuit operations.
Evidence in the complete study note
For bitwise values, write binary columns: 11&9=9; 9^3=10; 10|12=14.OOP23
Choice by choice
A · incorrect — Seven has binary 0111, whereas the final OR produces 1110.
B · incorrect — The final OR includes the set bits of 12, so it cannot produce zero.
C · correct — The chain produces x=9, y=10 and final y|12=14.
D · incorrect — Eight omits bits set by the final OR of binary 1010 and 1100.
Question 64
What is the output of relational operators?
A. Integer
B. Boolean
C. Characters
D. Double
Hint / Module Reference (Where to Read)
Read the cited conceptual rules, state the model, and apply them before comparing the alternatives.
Relational expressions test a relation rather than return one of their numeric operands. In Java that truth result is Boolean, consistent with OOP06’s prohibition on treating boolean as numeric truth values and OOP23’s Boolean output discussion. Integer, character and double values can be compared in suitable expressions, but are not the comparison result type.
Evidence in the complete study note
Java relational comparisons (<, <=, >, >=) and equality tests (==, !=) produce primitive boolean truth values. Their result is not an integer truth code or a value of the numeric operand type.OOP-S03
Choice by choice
A · incorrect — Java comparison results are logical values rather than integer truth codes such as zero and one.
B · correct — A relational test yields the Boolean truth value true or false.
C · incorrect — Characters can be compared, but a comparison does not return a character result.
D · incorrect — Double operands may participate in comparisons, but their relation yields a Boolean rather than a double.
Question 65
Which of these is returned by "greater than", "less than" and "equal to" operators?
A. Integers
B. Floating - point numbers
C. Boolean
D. None of the mentioned
Hint / Module Reference (Where to Read)
Read the cited conceptual rules, state the model, and apply them before comparing the alternatives.
Greater-than, less-than and equality operators express truth tests. Java represents their results as Boolean values, not integers or floating-point numbers. OOP06 distinguishes boolean from numeric values, and OOP23 describes printing Boolean true as lowercase true. The operand type therefore does not become the result type of the test.
Evidence in the complete study note
Java relational comparisons (<, <=, >, >=) and equality tests (==, !=) produce primitive boolean truth values. Their result is not an integer truth code or a value of the numeric operand type.OOP-S03
Choice by choice
A · incorrect — Java uses Boolean truth values for comparisons rather than returning integer zero or one.
B · incorrect — Comparing floating operands still yields a truth value, not a floating-point numerical result.
C · correct — Greater-than, less-than and equality comparisons return Boolean true or false.
D · incorrect — Boolean is explicitly offered and is the appropriate logical result type, so none is false.
Question 66
In Java, what type must expression1 have in the conditional expression expression1 ? expression2 : expression3?
A. Integer
B. Floating - point numbers
C. Boolean
D. None of the mentioned
Hint / Module Reference (Where to Read)
Read the cited conceptual rules, state the model, and apply them before comparing the alternatives.
Correct answer: C — Java requires boolean or Boolean for the first operand of ?: .
Java’s conditional operator requires its first operand to have primitive boolean or boxed Boolean type. That condition chooses which of the other two expressions is evaluated; the unselected alternative is not evaluated. Integer and floating-point values are not accepted as numeric truth codes. The Boolean option therefore names the required logical category, and None is false because that category is offered.
Evidence in the complete study note
The conditional expression condition ? whenTrue : whenFalse requires a boolean or Boolean condition. It evaluates only the selected alternative. An integer or floating-point first operand is a compile-time error.OOP-S03
boolean does not convert to or from numeric truth values; if(0) and for(...;0;...) are invalid.OOP06
Additional authoritative reference
Java conditional expressions require a first operand of type boolean or Boolean.
The last statement assigns 8 to z, then that same assigned value to y and then x. The earlier x=0 and y=1 values are overwritten, and no addition takes place. This follows assignment’s value propagation rather than the left-to-right operand arithmetic discussed in OOP23. The final stored value of x is 8.
Evidence in the complete study note
Assignments group right to left: a=b=c assigns c to b, then the resulting value to a. A later assignment overwrites an earlier value. Compound assignments update the left variable using the indicated operation.OOP-S03
Choice by choice
A · incorrect — Zero is x’s earlier value; the final chained assignment overwrites it with 8.
B · incorrect — One is y’s earlier value, which is also overwritten before x receives the chain’s result.
C · incorrect — The statement performs assignments, not addition of the earlier y value to 8.
D · correct — The chain assigns 8 to z, then y and x, leaving x equal to 8.
Question 68
What is the output of this program?
class Main
{
public static void main(String args[])
{
int x = 8;
System.out.println(++x * 3 + " " + x);
}
}
A. 24 8
B. 24 9
C. 27 8
D. 27 9
Hint / Module Reference (Where to Read)
Track the old and updated values separately and distinguish a character operand from a string.
Prefix ++x changes x from 8 to 9 before multiplication, producing 27. Concatenating the string containing a space switches the remaining + operations to text concatenation. The later x still holds 9 because no further update occurs. Therefore the single println emits 27 9, followed by its newline.
Evidence in the complete study note
Starting x=5, printing x++ then ++x gives 5 then 7.OOP24
Once a String operand is encountered, + concatenates in left-to-right groups: 1+2+"x" gives "3x", while "x"+1+2 gives "x12".OOP24
Choice by choice
A · incorrect — Both values wrongly use the original x=8 despite the prefix increment before multiplication.
B · incorrect — The final x is 9, but the product must also use updated 9 and become 27.
C · incorrect — The product is 27, but x remains 9 rather than reverting to its original 8.
D · correct — The prefix update gives 9, its product is 27, and concatenation then appends space and 9.
Question 69
_________ are a sequence of characters.
A. Character
B. Strings
C. Integer
D. Classes
Hint / Module Reference (Where to Read)
Read the cited conceptual rules, state the model, and apply them before comparing the alternatives.
The String Class description explicitly equates strings with a sequence of chars.
Evidence in the complete study note
A String represents a sequence of UTF-16 code units. A single char represents one code unit rather than an entire String. String objects are immutable; changing a reference to another String does not modify the original text value.OOP-S04
Choice by choice
A · incorrect — A character is one element, not the named sequence type
B · correct — The sequence-of-characters type
C · incorrect — Integer represents a different primitive category
D · incorrect — Class is the general blueprint concept rather than this sequence type
Question 70
The String class is?
A. mutable
B. immutable
C. Both A and B
D. None of the above
Hint / Module Reference (Where to Read)
Separate identity, content equality, immutable values and references that may be reassigned.
String is immutable, unlike mutable classes whose state can change.
Evidence in the complete study note
Java String objects are immutable. text += " World" assigns a reference to a new concatenated result and can print Hello World without mutating the original String object. final class String prevents subclassing; final alone does not make arbitrary objects immutable.OOP22
Choice by choice
A · incorrect — Contradicts the stated immutable classification
B · correct — Matches the stated classification
C · incorrect — The two opposite classifications do not both describe String here
D · incorrect — B is directly supported
Question 71
Methods used to obtain information about an object are known as?
A. string methods
B. class methods
C. object method
D. accessor methods
Hint / Module Reference (Where to Read)
Separate parameters from arguments and operations that read state from operations that change it.
OOP11 says an accessor or getter returns information, whereas a mutator or setter changes state. Methods used to obtain information about an object therefore have the specific name accessor methods. String, class and object describe other categories or associations and do not identify this information-reading responsibility.
Evidence in the complete study note
An accessor/getter returns information; a mutator/setter changes state.OOP11
Prefer ClassName.count and ClassName.utility().OOP07
Choice by choice
A · incorrect — String methods concern a particular class; the requested information-reading role applies to objects generally.
B · incorrect — Class methods identify a class/static association, rather than the specific purpose of returning object information.
C · incorrect — Object method is too general; object methods can either read or change state.
D · correct — Accessor methods specifically return information about object state, matching the definition in OOP11.
Question 72
Which method returns the character at the specified index?
A. int compareTo(Object o)
B. int compareTo(String anotherString)
C. char charAt(int index)
D. int compareToIgnoreCase(String str)
Hint / Module Reference (Where to Read)
Separate identity, content equality, immutable values and references that may be reassigned.
OOP22 explicitly says charAt(index) returns a char. C gives that operation’s parameter and result type: an integer position selects a single character. The compareTo alternatives return int comparison results rather than the character at a position, so they do not satisfy the requested retrieval behavior.
Correct answer: D — charAt (with an index argument).
The operation named in OOP22 is charAt(index), with a lowercase c and uppercase A. D alone preserves that exact Java method name. The options abbreviate away the index argument; an actual call needs it. Java’s case sensitivity prevents Charat or charat from naming the same standard operation.
Java identifiers are case sensitive; $ is allowed but @ is not an identifier character.OOP28
Choice by choice
A · incorrect — char is a primitive type keyword, not the indexed String character-access method name.
B · incorrect — Charat has the wrong capitalization and does not name the charAt operation in OOP22.
C · incorrect — charat lacks the uppercase A required by the case-sensitive standard method name.
D · correct — charAt is the exact method name; a real invocation supplies an index inside the parentheses.
Question 74
Which Java loop form pre-tests its body condition and writes that condition alone in parentheses immediately after its loop keyword, rather than using a three-clause header or a post-test?
A. for
B. do-while
C. while
D. None of the above
Hint / Module Reference (Where to Read)
Read the cited conceptual rules, state the model, and apply them before comparing the alternatives.
A while loop tests its condition before every possible execution and has a condition-only header. A for loop is also a pre-test loop, but its ordinary header has initialization, condition and update clauses. A do-while loop tests after its body and therefore runs at least once. The added header and timing distinctions make while the unique match rather than relying on repetition alone.
Evidence in the complete study note
A while header is while(condition). A basic for header is for(initialization; condition; update). A do-while statement places its condition after the body. An if selects its true branch or, when present, its else branch; only the selected branch executes.OOP-S03
while and for pre-test and may execute zero times; do-while post-tests and executes once.OOP25
Choice by choice
A · incorrect — A basic for uses the three-clause header excluded by the stem.
B · incorrect — A do-while post-tests rather than pre-testing its first iteration.
C · correct — while has the condition-only pre-test form described.
D · incorrect — The while form satisfies the description, so none is incorrect.
Question 75
Which loop guaranteed to execute at least one time?
A. for
B. do-while
C. while
D. All of the above
Hint / Module Reference (Where to Read)
Trace condition tests, control transfers and printing as separate steps.
OOP25 states that do-while post-tests and executes once, whereas for and while pre-test and may execute zero times. The mandatory first body execution is therefore specific to do-while among these forms. This guarantee concerns entering its body when the statement is reached, before deciding whether to repeat.
Evidence in the complete study note
while and for pre-test and may execute zero times; do-while post-tests and executes once.OOP25
Choice by choice
A · incorrect — A for loop tests its condition before its first body execution and may execute zero times.
B · correct — A do-while executes its body before testing the condition, guaranteeing the first body execution.
C · incorrect — A while loop pre-tests; an initially false condition prevents all body executions.
D · incorrect — For and while can execute zero times, so the first-execution guarantee does not apply to all forms.
Question 76
Which statement causes the loop to immediately jump to the next iteration of the loop?
A. Exit
B. Break
C. Jump
D. Continue
Hint / Module Reference (Where to Read)
Trace condition tests, control transfers and printing as separate steps.
continue skips the rest of the current iteration and proceeds to the loop’s continuation step; break exits the loop. Thus continue matches moving to the next iteration.
Evidence in the complete study note
break exits the loop; continue skips its remaining body and then runs a for update.OOP25
Choice by choice
A · incorrect — Exit is not the named loop-jump statement here
B · incorrect — break leaves the loop
C · incorrect — Jump is a category, rather than the required keyword
D · correct — continue advances control to loop continuation
Question 77
A BREAK statement inside a Loop like WHILE, FOR, DO WHILE and Enhanced-FOR causes the program execution ___ Loop
A. Exit
B. Continuation with next iteration
C. Never exit
D. Can not say
Hint / Module Reference (Where to Read)
Trace condition tests, control transfers and printing as separate steps.
Correct answer: A — Elements with a common declared component type.
OOP26 says array elements share a declared common component type, possibly a superclass or interface. That is the precise interpretation of similar type in A. Reference elements may point to different compatible runtime subclasses, but this does not give the array unrelated declared element types or make arbitrary heterogeneous data its defining property.
Evidence in the complete study note
Elements have a declared common component type, which may be a superclass/interface.OOP26
Choice by choice
A · correct — Similar type is accurate when understood as the array’s single declared common component type.
B · incorrect — The array does not assign an unrelated declared type to each element; compatible runtime subclasses are a separate issue.
C · incorrect — Heterogeneous runtime objects may share one component type, but unrestricted heterogeneity is not the array’s defining type rule.
D · incorrect — Combining A with unrestricted heterogeneity obscures the single declared component type required by OOP26.
Question 79
Array data access using _____.
A. Operator
B. Variable
C. index
D. Pointer
Hint / Module Reference (Where to Read)
Check declared dimensions, initializer shape, fixed length and zero-based index bounds.
OOP26 defines valid array indices as zero through length-1. Selecting an array element therefore uses its index, as in a[i]. An operator participates in the syntax and a variable can hold the index, but neither term identifies the selection value as precisely. Java does not require a raw pointer to access an element.
Evidence in the complete study note
Valid indices are 0..a.length-1; an invalid access throws ArrayIndexOutOfBoundsException.OOP26
Choice by choice
A · incorrect — Array-access syntax uses brackets, but operator is less specific than the index that selects the element.
B · incorrect — A variable can store an index, but array selection also accepts other integer index expressions.
C · correct — An index specifies the position of the requested element within the array’s valid bounds.
D · incorrect — Java element access uses checked indices rather than requiring a programmer-visible raw pointer.
Question 80
Java Array can allocate __________.
A. Dynamic Memory
B. Static Memory
C. Both A and B
D. None of the above
Hint / Module Reference (Where to Read)
Check declared dimensions, initializer shape, fixed length and zero-based index bounds.
Correct answer: A — Dynamic allocation of an array object.
OOP26 shows array creation through new int[5] and describes the result as an array object with fixed length after creation. Allocation occurs when that creation expression executes, which is the dynamic-memory meaning of A. Fixed array length does not mean statically allocated storage, and a static reference does not change the array object into static memory.
Evidence in the complete study note
int[] a=new int[5]; and int a[]={1,2,3}; are valid. int[] a={}; creates a zero-length array; explicit new is unnecessary in a declaration initializer. int a[],b; makes only a an array; int[] c,d; makes both arrays. Array objects have fixed length after creation, although the reference may be reassigned.OOP26
Choice by choice
A · correct — The creation expression allocates an array object when executed, even though the created object’s length is fixed.
B · incorrect — A fixed length does not imply static allocation; new creates an array object during execution.
C · incorrect — Declaring a static reference does not supply a second static-allocation mechanism for the array object itself.
D · incorrect — The valid new-array expression in OOP26 demonstrates dynamic allocation, so none is false.
Question 81
Which complete Java array declaration has an incorrect initializer syntax? Treat each option independently.
A. int[] arr = new int[5];
B. int arr[] = new int[5];
C. int arr[] = new int[5];
D. int arr[] = int[5] new;
Hint / Module Reference (Where to Read)
Check declared dimensions, initializer shape, fixed length and zero-based index bounds.
Java permits array brackets on the declared type or after the variable name, and new int[5] allocates a five-element array. Thus A is valid, and B and its duplicate C are also valid declarations. D reverses the required allocation token order, putting new after int[5]. Replacing editorial periods with semicolons isolates the intended initializer-syntax error without treating punctuation noise as the tested concept.
Evidence in the complete study note
int[] a=new int[5]; and int a[]={1,2,3}; are valid. int[] a={}; creates a zero-length array; explicit new is unnecessary in a declaration initializer. int a[],b; makes only a an array; int[] c,d; makes both arrays.OOP26
Choice by choice
A · incorrect — Brackets on the type and new int[5] are valid.
B · incorrect — Brackets after the variable name are legal with this allocation expression.
C · incorrect — This duplicates B’s valid declaration and is not an incorrect initializer.
D · correct — The initializer must place new before int[5], so this token order is incorrect.
Question 82
Index in array start with ______.
A. -1
B. 0
C. 1
D. infinite
Hint / Module Reference (Where to Read)
Check declared dimensions, initializer shape, fixed length and zero-based index bounds.
OOP26 states that valid array indices run from zero to length minus one. Thus the first element of any nonempty Java array has index 0. An empty array has no valid element index, but that does not change the language’s zero-based indexing convention requested by this question.
Evidence in the complete study note
Valid indices are 0..a.length-1; an invalid access throws ArrayIndexOutOfBoundsException.OOP26
Choice by choice
A · incorrect — Negative one is below the valid lower bound and causes an invalid access when used.
B · correct — Zero is the first valid index of a nonempty Java array.
C · incorrect — One selects the second element when present; Java arrays do not use one-based indexing.
D · incorrect — Infinity is not an array index; valid positions are finite integers below the fixed array length.
Question 83
Which shown Java declarations create and initialize a one-dimensional int array? Zero-length arrays count. Treat the options independently. Select all that apply.
A. int arr [] [] = {1, 2, 3, 4};
B. int [] arr = (1, 2, 3);
C. int [] arr = {};
D. int arr [] = {1, 2, 3};
Hint / Module Reference (Where to Read)
Check declared dimensions, initializer shape, fixed length and zero-based index bounds.
Correct answers (select all): C, D — int [] arr = {};; int arr [] = {1, 2, 3};
C creates an int array of length zero, and D creates one of length three initialized to 1, 2 and 3. Both declare, create and initialize a one-dimensional array. A declares two dimensions but supplies scalar elements instead of row arrays. B uses parentheses, which do not form an array initializer. Explicitly allowing zero length prevents incorrectly rejecting the valid empty array.
Evidence in the complete study note
int[] a=new int[5]; and int a[]={1,2,3}; are valid. int[] a={}; creates a zero-length array; explicit new is unnecessary in a declaration initializer. int a[],b; makes only a an array; int[] c,d; makes both arrays.OOP26
Java two-dimensional arrays are arrays of arrays and may be ragged: {{12,-9,8},{7,14},{-32,-1,0}} has row lengths 3,2,3.OOP26
Choice by choice
A · incorrect — The flat int values do not initialize the declared int[][] component rows.
B · incorrect — Parentheses do not provide a Java array initializer.
C · correct — Empty braces validly create and initialize a zero-length int array.
D · correct — The brace list validly creates and initializes a three-element int array.
Question 84
We can calculate the length of an array using ________.
A. sizeof(array)
B. array.len
C. array.length
D. array.sizeof()
Hint / Module Reference (Where to Read)
Check declared dimensions, initializer shape, fixed length and zero-based index bounds.
OOP26 uses a.length as the fixed element count when defining valid indices. Therefore array.length is the correct Java expression for the length field of an array reference named array. This is a field access rather than a method invocation, and the other supplied spellings are not the array-length mechanism described in the note.
Evidence in the complete study note
Array objects have fixed length after creation, although the reference may be reassigned.OOP26
Valid indices are 0..a.length-1; an invalid access throws ArrayIndexOutOfBoundsException.OOP26
Choice by choice
A · incorrect — sizeof is not the Java array-length expression used in OOP26’s index-bound rule.
B · incorrect — The field name is length, not len, so this spelling does not retrieve array length.
C · correct — Java arrays expose their fixed element count through the length field, without parentheses.
D · incorrect — The note uses a length field; arrays do not expose the proposed sizeof method.
Question 85
Which is an inherent property of Java arrays? Here “Code Optimization” means a guarantee that merely introducing an array makes every algorithm run faster.
A. Code Optimization
B. Random access
C. Size No-Limit
D. Both A and B
Hint / Module Reference (Where to Read)
Check declared dimensions, initializer shape, fixed length and zero-based index bounds.
Correct answer: B — Random access is the concrete array advantage.
Arrays provide indexed random access, so B states the inherent capability. They have a fixed length after creation and are bounded by implementation limits and available resources, so unlimited size is false. An array is a storage structure, not a guarantee that every algorithm becomes faster: allocating an unused array cannot improve a computation that does not need it. A therefore fails the stated guarantee, and combining it with B does not make D correct.
Evidence in the complete study note
Random access is the reliable array advantage; size is bounded by implementation/resources, not unlimited.OOP27
Array objects have fixed length after creation, although the reference may be reassigned.OOP26
Student s=new Student(); allocates and initializes an instance.OOP03
Choice by choice
A · incorrect — The stated universal speedup does not follow from array storage; adding an unused allocation does not improve the algorithm’s required computation.
B · correct — Indexed random access is a direct array capability.
C · incorrect — Array length is fixed after creation and constrained by implementation limits and resources.
D · incorrect — This conjunction includes the false universal optimization guarantee, even though random access itself is true.
Question 86
Which term describes the logical index order of a Java array, from 0 through length−1, rather than making any claim about physical RAM placement?
A. Random
B. Sequential
C. Sequential & Random
D. Binary search
Hint / Module Reference (Where to Read)
Check declared dimensions, initializer shape, fixed length and zero-based index bounds.
Java arrays expose a logical sequence of indices starting at zero and ending at length minus one. Sequential describes that order. Random access describes the ability to choose an index directly, not a random logical ordering of elements or a portable physical-memory arrangement. Binary search is an algorithm rather than an ordering description. The revised question therefore tests index semantics without assuming exposed physical contiguity.
Evidence in the complete study note
Valid indices are 0..a.length-1; an invalid access throws ArrayIndexOutOfBoundsException.OOP26
Random access is the reliable array advantage; size is bounded by implementation/resources, not unlimited.OOP27
Choice by choice
A · incorrect — Random access does not mean that the logical index sequence is randomly ordered.
B · correct — Sequential describes the logical index progression from 0 to length−1.
C · incorrect — Combining access capability with ordering does not give the precise ordering term requested.
D · incorrect — Binary search is an algorithm, not the array’s logical index order.
Question 87
What will be the output of the program?
class Main
{
public static void main(String args[]) {
int arr[] = {10, 20, 30, 40, 50};
for(int i=0; i < arr.length; i++)
{
System.out.print(" " + arr[i]);
}
}
}
A. 10 20 30 40 50
B. Compiler Error
C. 10 20 30 40
D. None of the above
Hint / Module Reference (Where to Read)
Check declared dimensions, initializer shape, fixed length and zero-based index bounds.
Correct answer: D — Exact output: " 10 20 30 40 50", with an initial space.
The loop visits all five indices, 0 through 4. Each print prepends the literal string containing one space, including before the first element. The exact output is therefore " 10 20 30 40 50" without a newline. A lists the correct numbers but omits that initial space. Under literal output matching, D is the offered exact answer.
Evidence in the complete study note
int[] a=new int[5]; and int a[]={1,2,3}; are valid.OOP26
Valid indices are 0..a.length-1; an invalid access throws ArrayIndexOutOfBoundsException.OOP26
while and for pre-test and may execute zero times; do-while post-tests and executes once.OOP25
Once a String operand is encountered, + concatenates in left-to-right groups: 1+2+"x" gives "3x", while "x"+1+2 gives "x12".OOP24
PrintStream.print(double) converts the stored value through String.valueOf and Double.toString. For finite nonzero magnitudes from 0.001 inclusive to 10000000 exclusive, the standard decimal form uses at least one fractional digit and only the further digits needed to distinguish the value from adjacent doubles. println(double) also adds a line terminator. This is not fixed-decimal-place formatting.OOP-S02
Choice by choice
A · incorrect — The listed values are right, but the printed option omits the leading space emitted before 10.
B · incorrect — The array declaration and traversal stay within indices 0 through 4, so no compilation error follows.
C · incorrect — The last index 4 is visited and prints 50; this also omits the initial space.
D · correct — None of the other options reproduces the exact leading-space output required by the literal code.
Question 88
Which of these is an incorrect Statement?
A. It is necessary to use new operator to initialize an array
B. Array can be initialized using comma separated expressions surrounded by curly braces
C. Array can be initialized when they are declared
D. None of the mentioned
Hint / Module Reference (Where to Read)
Check declared dimensions, initializer shape, fixed length and zero-based index bounds.
Correct answer: A — Explicit new is not necessary in a declaration initializer.
OOP26 explicitly states that new need not be written in a declaration initializer and shows both empty and nonempty brace forms. Thus A is the incorrect statement. B and C describe the valid brace-initializer form used at declaration. This does not imply that an existing array variable can later be assigned a bare brace list.
Evidence in the complete study note
int[] a=new int[5]; and int a[]={1,2,3}; are valid. int[] a={}; creates a zero-length array; explicit new is unnecessary in a declaration initializer.OOP26
Choice by choice
A · correct — The claim is false: brace initialization at declaration creates an array without explicitly writing new.
B · incorrect — This is a true description of the comma-separated brace initializer shown in OOP26.
C · incorrect — This is true: the note’s examples initialize arrays as part of their declarations.
D · incorrect — A is an offered false statement, so it is incorrect to say none is incorrect.
Question 89
What is the type of variable "b" and "d" in the below snippet?
int a[], b;
int []c, d;
A. "b" and "d" are int
B. "b" and "d" are arrays of type int
C. "d" is int variable; and "b" is int array
D. "b" is int variable; and "d" is int array
Hint / Module Reference (Where to Read)
Check declared dimensions, initializer shape, fixed length and zero-based index bounds.
In int a[],b, the brackets belong only to a, leaving b as a scalar int. In int[] c,d, the brackets are part of the common type, so both c and d are int arrays. OOP26 gives these exact forms. The distinction depends on bracket placement rather than on the variable names.
Evidence in the complete study note
int a[],b; makes only a an array; int[] c,d; makes both arrays.OOP26
Choice by choice
A · incorrect — b is scalar int, but d belongs to the common int[] type of the second declaration.
B · incorrect — Only d is an array; the first declaration attaches brackets to a rather than to b.
C · incorrect — This reverses the actual types: b is scalar int and d is int[].
D · correct — Brackets after a leave b scalar, while brackets after int make both c and d arrays.
Question 90
How to sort an array?
A. Array.sort()
B. Arrays.sort()
C. Collection.sort()
D. System.sort()
Hint / Module Reference (Where to Read)
Trace every element or API argument and distinguish copying values from aliasing a reference.
OOP27 specifies java.util.Arrays.sort(a) for in-place sorting of an array. B names that method, with the argument omitted as shorthand in the options; a real invocation supplies the array. The other class/method combinations do not match the array-sorting API provided here.
Evidence in the complete study note
java.util.Arrays.sort(a) sorts in place.OOP27
Choice by choice
A · incorrect — The supplied class name Array does not match the java.util.Arrays class specified here.
B · correct — Arrays.sort is the correct method name; actual use supplies the array argument as Arrays.sort(a).
C · incorrect — Collection.sort is not the array-sorting API identified in OOP27.
D · incorrect — System.sort is not the array-sorting API provided in the complete note.
Question 91
Which correctly spelled Java API copies a selected range from one existing array into another existing array? The parentheses in distractors stand for a method name, not a complete no-argument invocation.
A. System.arraycopy(src, srcPos, dst, dstPos, length)
B. Array.copy()
C. Arrays.copy()
D. Collection.copy()
Hint / Module Reference (Where to Read)
Trace every element or API argument and distinguish copying values from aliasing a reference.
Correct answer: A — System.arraycopy(src, srcPos, dst, dstPos, length)
System.arraycopy copies length elements from the supplied source position into a supplied destination array position. Its name uses lowercase c in copy. Arrays.copyOf is a different supported API that creates a copy, but Arrays.copy is not that method’s name. The other printed names do not identify the requested array-copy API. Correcting A’s spelling and supplying its arguments restores a usable exact choice.
Evidence in the complete study note
System.arraycopy(src,srcPos,dst,dstPos,length) copies into an existing array; its exact spelling uses lowercase c. Arrays.copyOf(a,n) creates a copy. a=b merely aliases the same array.OOP27
Choice by choice
A · correct — This is the correctly spelled range-copy API for existing source and destination arrays.
B · incorrect — Array.copy is not the supported API named here.
C · incorrect — The supported creation API is Arrays.copyOf, not Arrays.copy.
D · incorrect — Collection.copy is not the specified array-range-copy API.
Question 92
Which named type categories can be directly declared as top-level members of a Java package? Subpackages are separately named packages, not automatically enclosed members. Select all that apply.
A. Classes
B. Sub Packages
C. Interfaces
D. All of the above
Hint / Module Reference (Where to Read)
Check declaration order, exact case, package boundaries and the compile-versus-launch stage.
Correct answers (select all): A, C — Classes; Interfaces
A package organizes named types, including classes and interfaces, and provides a naming and access boundary. A subpackage is a separate package identity even when its name starts with the parent’s name. It does not automatically gain membership or access through that spelling. Consequently classes and interfaces are the direct type categories, while the all option wrongly includes subpackages in the same membership sense.
Evidence in the complete study note
package p; precedes imports; imports precede top-level type declarations. import p.*; imports accessible types from p as needed, not types in p.sub automatically. Packages organize names and control access; hierarchical spelling does not grant special access between a package and its subpackages.OOP28
Choice by choice
A · correct — Classes can be top-level named types belonging to the package.
B · incorrect — A subpackage is a separate named package rather than a directly declared type member.
C · correct — Interfaces can be top-level named types belonging to the package.
D · incorrect — All includes the separate-package category and is therefore too broad.
Question 93
Which of these keywords is used to define packages in Java?
A. pkg
B. Pkg
C. package
D. Package
Hint / Module Reference (Where to Read)
Check declaration order, exact case, package boundaries and the compile-versus-launch stage.
Import statements follow any package declaration and precede top-level type declarations; they come first when there is no package declaration. They bring external class/interface names into the source context.
Evidence in the complete study note
package p; precedes imports; imports precede top-level type declarations. import p.*; imports accessible types from p as needed, not types in p.sub automatically. Packages organize names and control access; hierarchical spelling does not grant special access between a package and its subpackages.OOP28
class Dog extends Animal declares a subclass/derived/child of a superclass/base/parent.OOP13
Use if(a instanceof Ferrari) before narrowing when the dynamic type is uncertain.OOP21
Choice by choice
A · incorrect — instanceof is an object-type test, not an import
B · correct — Matches the source-file import statement
C · incorrect — extends defines inheritance
D · incorrect — implement is not the import statement
Question 95
Which of the following packages is used to includes classes to create user interface like Button and Checkbox?
A. java.lang
B. java.net
C. java.awt
D. java.io
Hint / Module Reference (Where to Read)
Check declaration order, exact case, package boundaries and the compile-versus-launch stage.
OOP28 explicitly identifies java.awt as including Button and Checkbox. The question names those UI classes, so the answer follows directly from their package membership. java.lang, networking and I/O packages serve other purposes and are not the package the note identifies for these two AWT controls.
Evidence in the complete study note
java.lang is implicitly imported; java.util supplies utilities; java.io supplies I/O; java.awt includes Button and Checkbox.OOP28
Calendar and Date are classes in java.util; Collection is an interface in that package. java.util also contains Arrays and Scanner. java.net supplies networking facilities; java.awt supplies the Button and Checkbox UI controls described in the package overview.OOP-S04
Choice by choice
A · incorrect — java.lang is implicitly imported, but OOP28 locates Button and Checkbox in java.awt instead.
B · incorrect — The named controls are AWT UI types, not networking types in the proposed java.net package.
C · correct — OOP28 explicitly lists Button and Checkbox as classes included in java.awt.
D · incorrect — java.io supplies input/output facilities rather than the two AWT controls named by the question.
Question 96
Which of the following packages is used to includes utility classes like Calendar, Collection, Date?
A. java.lang
B. java.net
C. java.awt
D. java.util
Hint / Module Reference (Where to Read)
Read the cited conceptual rules, state the model, and apply them before comparing the alternatives.
The question identifies Calendar, Collection and Date as utility types. OOP28 assigns utility facilities to java.util, in contrast to implicitly imported language facilities, AWT user-interface classes and I/O. Therefore java.util is the package category supported for the named utility examples, rather than the language, networking or UI alternatives.
Evidence in the complete study note
Calendar and Date are classes in java.util; Collection is an interface in that package. java.util also contains Arrays and Scanner. java.net supplies networking facilities; java.awt supplies the Button and Checkbox UI controls described in the package overview.OOP-S04
java.lang is implicitly imported; java.util supplies utilities; java.io supplies I/O; java.awt includes Button and Checkbox.OOP28
Choice by choice
A · incorrect — java.lang supplies core language facilities; the utility package identified here is java.util.
B · incorrect — java.net is the networking alternative, not the utility package identified in OOP28.
C · incorrect — java.awt contains AWT UI controls, rather than the utility facilities requested by the question.
D · correct — java.util is the note’s explicit utility-package mapping for the class/interface examples in the stem.
Question 97
An accessible class declares an ordinary field. Which offered modifier choices permit another unrelated class in the same package to access that field directly? Choose the most complete answer; this asks about member modifiers, not top-level class modifiers.
A. Public
B. Protected
C. No Modifier
D. All of the mentioned
Hint / Module Reference (Where to Read)
Locate the accessing code, declaring type, package and receiver before applying visibility rules.
For ordinary members, public allows access, protected includes same-package access, and no modifier grants package access. All three listed choices therefore permit the unrelated same-package client to access the field. This does not claim that protected is legal on a top-level class, and class accessibility alone would not expose a private field. Under the explicitly member-level scope, D is the complete selection.
Evidence in the complete study note
For ordinary members: private restricts access to the declaring class/nest; no modifier grants package access; protected grants same-package access plus qualified subclass access; public is widest, provided the declaring type itself is accessible.OOP08
protected therefore does not mean “subclasses only”: unrelated classes in the same package also have access.OOP08
Choice by choice
A · incorrect — Public permits the access, but this is only one of the three valid modifier choices.
B · incorrect — Protected includes same-package access, but this option alone is incomplete.
C · incorrect — No modifier grants package access, but this option alone is incomplete.
D · correct — All three listed member-modifier choices permit the specified same-package access.
Question 98
Which option is a syntactically complete Java on-demand import of accessible top-level types from package pkg, without importing subpackages automatically?
A. import pkg.
B. Import pkg.
C. import pkg.*;
D. Import pkg.*
Hint / Module Reference (Where to Read)
Check declaration order, exact case, package boundaries and the compile-versus-launch stage.
A type-import-on-demand statement uses lowercase import, the package name, a dot and wildcard, and a semicolon. import pkg.*; therefore supplies the complete syntax. It makes accessible types from pkg available as needed without automatically importing types from pkg.sub. A lacks the wildcard or type name, and capitalized Import is not the Java keyword in B or D.
Evidence in the complete study note
import p.*; imports accessible types from p as needed, not types in p.sub automatically.OOP28
Java identifiers are case sensitive; $ is allowed but @ is not an identifier character.OOP28
Choice by choice
A · incorrect — The trailing dot lacks a wildcard or type name and a complete terminator.
B · incorrect — Capitalized Import is not the keyword, and the target is incomplete.
C · correct — This is the complete lowercase wildcard import statement.
D · incorrect — Capitalized Import is not a Java keyword and the statement lacks its semicolon.
Question 99
Which of the following is false statement about package in java?
A. Packages are used for preventing naming conflicts
B. Providing controlled access: protected and default have package level access control.
C. Packages cannot be considered as data encapsulation
D. Both B and C
Hint / Module Reference (Where to Read)
Check declaration order, exact case, package boundaries and the compile-versus-launch stage.
Correct answer: C — The claim that packages cannot support encapsulation is false.
OOP28 says packages organize names and control access, while OOP08 defines package access and same-package protected access. These mechanisms can hide implementation types or members behind permitted boundaries, so C’s categorical denial is false. A and B describe real package roles. D incorrectly includes the true package-access statement B among the false claims.
Evidence in the complete study note
Packages organize names and control access; hierarchical spelling does not grant special access between a package and its subpackages.OOP28
For ordinary members: private restricts access to the declaring class/nest; no modifier grants package access; protected grants same-package access plus qualified subclass access; public is widest, provided the declaring type itself is accessible.OOP08
protected therefore does not mean “subclasses only”: unrelated classes in the same package also have access.OOP08
Information hiding keeps implementation decisions behind a stable interface.OOP02
Choice by choice
A · incorrect — Organizing names into packages supports avoiding naming conflicts, so this is a true purpose rather than the false claim.
B · incorrect — Default access is package access, and protected also grants same-package access; the statement is true.
C · correct — Packages control access and can hide implementation types or members, contradicting this categorical denial of encapsulation.
D · incorrect — B is supported by the access rules, so both B and C cannot be classified as false.
Question 100
For a Java naming hierarchy such as p and p.q, what is the specific conventional term for packages such as p.q relative to p?
A. packages
B. nested packages sharing their parent’s member-access scope
C. util subpackages
D. subpackages
Hint / Module Reference (Where to Read)
Check declaration order, exact case, package boundaries and the compile-versus-launch stage.
The conventional term for p.q relative to p is subpackage. This is a naming hierarchy, not a lexical enclosing scope: the parent’s import does not automatically import types from the subpackage, and their related names grant no special member access. Packages is only the broad category. The util qualifier would restrict the answer to a particular package family instead of naming the general relationship.
Evidence in the complete study note
import p.*; imports accessible types from p as needed, not types in p.sub automatically. Packages organize names and control access; hierarchical spelling does not grant special access between a package and its subpackages.OOP28
Choice by choice
A · incorrect — Packages names the broad category but does not identify the requested relationship to a parent name.
B · incorrect — The naming hierarchy does not give a subpackage its parent’s member-access scope.
C · incorrect — The relationship applies to arbitrary package names, not just util subpackages.
D · correct — Subpackages is the conventional term for the requested naming relationship.
Question 101
____________ can be defined as the process where one class acquires the properties (methods and fields) of another.
A. Overriding
B. Inheritance
C. Polymorphism
D. Abstraction
Hint / Module Reference (Where to Read)
Identify the subtype or ownership relationship and distinguish class inheritance from interface contracts.
Inheritance means acquiring another class's methods and fields.
Evidence in the complete study note
class Dog extends Animal declares a subclass/derived/child of a superclass/base/parent.OOP13
Use inheritance when a subtype can satisfy the parent’s contract: Dog is an Animal.OOP13
Inheritance forms a subtype relationship and may reuse implementation. Polymorphism lets code using a common type invoke behavior appropriate to different concrete objects.OOP02
A subclass overrides an eligible inherited instance method with the same signature and a compatible return type; a covariant reference return may be a subtype.OOP14
Abstraction presents the essential operations while omitting details irrelevant to the caller.OOP02
Choice by choice
A · incorrect — Overrides a method rather than acquiring the class properties generally
B · correct — Matches the definition word for word
C · incorrect — Many forms is a different principle
D · incorrect — Exposes essential information rather than acquiring class properties
Question 102
The class which inherits the properties of other is known as ________
A. superclass
B. parent class
C. subclass
D. None of the above
Hint / Module Reference (Where to Read)
Identify the subtype or ownership relationship and distinguish class inheritance from interface contracts.
super accesses superclass members, while this refers to the current object; the comparison concerns member access, rather than distinct receiver objects.
Evidence in the complete study note
Java this denotes the current object; this.name=name distinguishes a field from a parameter. super.name selects a hidden superclass field; super.sound() directly requests the parent implementation. It does not create a second parent object. An unqualified instance call may dispatch dynamically; an explicit super call is different.OOP16
Choice by choice
A · incorrect — construct is not the compared keyword
B · correct — Explicitly named comparison
C · incorrect — class defines a type rather than this-like access
D · incorrect — extends establishes inheritance rather than member reference
Question 106
Which of these is correct way of inheriting class A by class B?
A. class B + class A {}
B. class B inherits class A {}
C. class B extends A {}
D. class B extends class A {}
Hint / Module Reference (Where to Read)
Identify the subtype or ownership relationship and distinguish class inheritance from interface contracts.
The abstract-class definition explicitly uses the abstract keyword.
Evidence in the complete study note
An abstract class cannot be directly instantiated but can define fields, constructors, abstract methods and concrete methods. It need not contain an abstract method. An abstract method has no body; abstract and final conflict because an operation cannot require overriding while forbidding it.OOP18
class Dog extends Animal declares a subclass/derived/child of a superclass/base/parent.OOP13
Choice by choice
A · correct — Matches the definition
B · incorrect — util is not the modifier
C · incorrect — extends names an inheritance relation
D · incorrect — A directly supplies the keyword
Question 108
A method which is declared as abstract and does not have implementation is known as an _____________?
A. Abstract Interface
B. Abstract Thread
C. Abstract List
D. abstract Method
Hint / Module Reference (Where to Read)
Check whether a class is concrete and whether every inherited abstract contract has an implementation.
The summary says abstract methods have no body/implementation. That is the method kind described by the stem.
Evidence in the complete study note
An abstract method has no body; abstract and final conflict because an operation cannot require overriding while forbidding it.OOP18
interface Payable{double getPaymentAmount();} declares an abstract public operation. class Invoice implements Payable must provide public double getPaymentAmount(), perhaps returning getQuantity()*getPricePerItem().OOP19
Choice by choice
A · incorrect — Confuses a method with an interface
B · incorrect — Thread is not the unimplemented method category
C · incorrect — List is not the unimplemented method category
D · correct — Matches a method without implementation
Question 109
Which offered access modifier may be explicitly applied to an ordinary top-level Java interface? This is not a member interface nested in another type.
A. Public
B. private
C. Protected
D. All of the mentioned
Hint / Module Reference (Where to Read)
Locate the accessing code, declaring type, package and receiver before applying visibility rules.
An ordinary top-level interface may be public or package-private. Of the explicit access modifiers listed, only public is permitted at top level. Private and protected can apply in some nested member contexts but are excluded by the stated declaration location. No modifier is the package-private alternative, though it is not one of the offered choices. Therefore the aggregate of all modifiers is false.
Evidence in the complete study note
Top-level classes/interfaces may be public or package-private, not protected/private. Member types have additional visibility possibilities.OOP08
Choice by choice
A · correct — Public is permitted on an ordinary top-level interface.
B · incorrect — Private is not a legal top-level interface modifier.
C · incorrect — Protected is not a legal top-level interface modifier.
D · incorrect — All includes the forbidden private and protected top-level modifiers.
Question 110
Which of these keywords is used by a class to use an interface defined previously?
A. Import
B. import
C. implements
D. Implements
Hint / Module Reference (Where to Read)
Identify the interface contract, effective modifiers and permitted implementation forms.
A class implements an interface, while an interface extends another interface.
Evidence in the complete study note
interface Payable{double getPaymentAmount();} declares an abstract public operation. class Invoice implements Payable must provide public double getPaymentAmount(), perhaps returning getQuantity()*getPricePerItem(). A class can extend a superclass and implement zero or more interfaces. An interface can extend several interfaces.OOP19
package p; precedes imports; imports precede top-level type declarations. import p.*; imports accessible types from p as needed, not types in p.sub automatically. Packages organize names and control access; hierarchical spelling does not grant special access between a package and its subpackages.OOP28
Choice by choice
A · incorrect — Import is neither the demonstrated spelling nor implementation keyword
B · incorrect — import is a source naming facility, not implementation
C · correct — Matches class implementation syntax
D · incorrect — Capitalized form is not the stated keyword
Question 111
Which modifier lists can legally prefix int X = 1; when it is declared as a field in a Java interface? Missing public/static/final modifiers are supplied implicitly. Treat each choice independently. Select all that apply.
A. public static
B. private final
C. public final
D. static final
Hint / Module Reference (Where to Read)
Identify the interface contract, effective modifiers and permitted implementation forms.
Correct answers (select all): A, C, D — public static; public final; static final
Every interface field is implicitly public static final. A can omit final, C can omit static, and D can omit public because the language supplies each missing modifier. The initializer int X=1 satisfies the constant field’s initialization requirement. Private conflicts with the field’s public visibility and is therefore forbidden. The three legal partial modifier lists all produce the same effective field modifiers.
Evidence in the complete study note
No interface instance fields or constructors exist; fields are implicitly public static final.OOP19
Choice by choice
A · correct — public static is legal because final is implicit.
B · incorrect — private conflicts with an interface field’s implicit public visibility.
C · correct — public final is legal because static is implicit.
D · correct — static final is legal because public is implicit.
Question 112
In Java 17, which option most completely describes the permitted method contents of an interface? Here “declaration” means an abstract method declaration without a body and “definition” means a permitted method with a body; it does not ask what every interface must contain.
A. Method definition
B. Method declaration
C. Method declaration and definition
D. Method name
Hint / Module Reference (Where to Read)
Identify the interface contract, effective modifiers and permitted implementation forms.
Correct answer: C — Method declaration and definition
Modern Java interfaces can contain abstract method declarations and method bodies of permitted kinds, including default and static methods and private helpers. They need not contain every kind, but both declarations and definitions are allowed. A and B each describe only part of that capability. C is the most complete category, while a bare method name does not constitute the required declaration or definition.
Evidence in the complete study note
A method declaration without private, default or static is implicitly public abstract. Modern interfaces may also have default/static method bodies, and Java 9+ private helper methods.OOP19
Choice by choice
A · incorrect — Permitted method bodies are part of the answer, but this omits abstract declarations.
B · incorrect — Abstract declarations are allowed, but this omits permitted method bodies.
C · correct — Both abstract declarations and permitted method definitions can appear in Java 17 interfaces.
D · incorrect — A name alone is not a complete method declaration or definition.
Question 113
What type of methods an interface contain by default?
A. abstract
B. static
C. final
D. private
Hint / Module Reference (Where to Read)
Identify the interface contract, effective modifiers and permitted implementation forms.
Correct answer: A — Exceptions are thrown at runtime; checked obligations are checked at compile time.
OOP29 explains that checked does not mean an exception occurs during compilation. The compiler verifies catch-or-declare obligations; an actual exception throw occurs during program execution. Therefore Run Time is the correct occurrence answer. Compile-time syntax or name errors are a different category and do not make Java exceptions occur at any arbitrary stage.
Evidence in the complete study note
A missing semicolon or undeclared variable is a compile-time source error, not a checked exception.OOP29
Checked does not mean the exception occurs at compile time: the compiler checks an obligation to catch or declare it, while an actual throw occurs at runtime.OOP29
Choice by choice
A · correct — An actual exception throw occurs during execution, as OOP29 explicitly states.
B · incorrect — Any time conflates runtime throwing with compile-time checking and source errors.
C · incorrect — Compilation checks obligations or reports source errors; it is not when the described program throws an exception.
D · incorrect — Run Time is offered and is the supported occurrence stage, so none is false.
Question 115
Which of these keywords is not a part of exception handling?
A. finally
B. thrown
C. catch
D. try
Hint / Module Reference (Where to Read)
Check the thrown type and catch order before tracing propagation or handler output.
try, catch and finally are Java exception-handling keywords; thrown is an English word in compiler diagnostics, rather than a Java keyword.
Evidence in the complete study note
throw new IOException("message") actively throws a value; throws IOException in a signature declares a possible checked exception. A caller must handle or propagate checked obligations. try encloses guarded operations; a matching catch handles the thrown type or a subtype. Execution skips the remainder of the try when a throw occurs.OOP30
finally normally executes after try and any selected catch, including when leaving by return or propagating an exception.OOP31
Choice by choice
A · incorrect — Present in the example's cleanup block
B · correct — Not a keyword used to declare or handle exceptions; distinguish the word thrown in diagnostics
C · incorrect — Present as the handler clause
D · incorrect — Present as the monitored block
Question 116
Which of these keywords must be used to handle the exception thrown by try block in some rational manner?
A. finally
B. throw
C. catch
D. try
Hint / Module Reference (Where to Read)
Check the thrown type and catch order before tracing propagation or handler output.
The catch clause contains the handler for its exception type. finally is separate cleanup, and try surrounds the monitored operation.
Evidence in the complete study note
throw new IOException("message") actively throws a value; throws IOException in a signature declares a possible checked exception. A caller must handle or propagate checked obligations. try encloses guarded operations; a matching catch handles the thrown type or a subtype. Execution skips the remainder of the try when a throw occurs.OOP30
finally normally executes after try and any selected catch, including when leaving by return or propagating an exception.OOP31
Choice by choice
A · incorrect — Runs final code rather than the type-specific handler
B · incorrect — Would signal an exception rather than handle one
C · correct — The explicit exception handler clause
D · incorrect — Marks monitored code, not the handler
Question 117
Which of these is a super class of all errors and exceptions in the Java language?
A. Catchable
B. Throwable
C. RunTimeExceptions
D. None of the above
Hint / Module Reference (Where to Read)
Separate source errors from runtime exceptions and determine the hierarchy and checked obligation.
OOP29 places Exception and Error under the common root Throwable. Therefore Throwable is the superclass covering all errors and exceptions in the question. RuntimeException is only a sub-branch and cannot be the root of Error or checked exceptions. Catchable is not the root type named in the provided hierarchy.
Evidence in the complete study note
Throwable is the root of throwable values, with Exception and Error branches. RuntimeException and Error subclasses are unchecked; other throwable classes are checked.OOP29
Choice by choice
A · incorrect — Catchable is not the root class specified here’s throwable hierarchy.
B · correct — Throwable is explicitly the shared root above both Exception and Error.
C · incorrect — RuntimeException is an unchecked exception branch, not the common superclass of all errors and exceptions.
D · incorrect — Throwable is offered and is the hierarchy root, so none of the above is false.
Question 118
In which of the following package Exception class exist?
A. java.file
B. java.lang
C. java.io
D. java.util
Hint / Module Reference (Where to Read)
Read the cited conceptual rules, state the model, and apply them before comparing the alternatives.
Correct answer: B — java.lang.Exception belongs to java.lang.
The base Exception class belongs to java.lang, which is implicitly imported. Its place in the Throwable hierarchy does not determine the package of every subclass: I/O-specific subclasses may belong to java.io while the base remains java.lang.Exception. java.util contains utility types, and java.file is not the package of this class. Thus B supplies the correct package.
Evidence in the complete study note
The base Exception class is java.lang.Exception. It does not belong to java.io merely because some subclasses represent I/O failures. Package membership and position in an inheritance hierarchy are separate facts.OOP-S04
Throwable is the root of throwable values, with Exception and Error branches.OOP29
java.lang is implicitly imported; java.util supplies utilities; java.io supplies I/O; java.awt includes Button and Checkbox.OOP28
Additional authoritative reference
The Exception class is declared in the java.lang package.
Correct answer: C — An HTML document, in the historical applet model.
OOP34 explicitly says historical applet code was embedded in an HTML document and executed by a compatible JVM host/plugin or applet viewer. HTML is therefore the requested embedding format. The answer concerns legacy applets; it does not imply modern browsers execute applets or that JavaScript, CSS or SQL provides the described host document.
Evidence in the complete study note
In the historical applet model, Java code was embedded in an HTML document and executed by a compatible JVM host/plugin or applet viewer.OOP34
Choice by choice
A · incorrect — JavaScript is not the embedding document format identified for historical applets in OOP34.
B · incorrect — CSS specifies styling rather than the HTML document into which the historical applet is embedded.
C · correct — HTML is the document format explicitly named as the historical applet embedding context.
D · incorrect — SQL is not the document format that hosts the historical applet in OOP34.
Question 120
Which of the following is required to view an applet?
A. JCM
B. JDM
C. JVM
D. Java class
Hint / Module Reference (Where to Read)
Use the historical host lifecycle and distinguish activation, suspension, drawing and unloading.
Correct answer: C — A JVM, together with a compatible historical host or applet viewer.
OOP34 says applets execute through a compatible JVM host/plugin or applet viewer. JVM is therefore the necessary component among the named options, although a JVM alone is not the entire browser embedding environment. This is a historical requirement rather than a statement that current browsers provide applet support.
Evidence in the complete study note
In the historical applet model, Java code was embedded in an HTML document and executed by a compatible JVM host/plugin or applet viewer.OOP34
A JVM alone is also not the complete browser embedding environment.OOP34
Choice by choice
A · incorrect — JCM is not the JVM execution component specified by OOP34 for historical applet viewing.
B · incorrect — JDM is not the JVM host or applet-viewer component identified here.
C · correct — A compatible JVM is necessary to execute the applet, together with an appropriate historical host/viewer.
D · incorrect — A Java class supplies code but does not itself provide the required JVM execution environment.
Question 121
Which method is automatically called after the browser calls the init method?
A. start
B. stop
C. destroy
D. paint
Hint / Module Reference (Where to Read)
Use the historical host lifecycle and distinguish activation, suspension, drawing and unloading.
OOP34 says init initializes once and start follows initialization and resumes activity. Thus start is the lifecycle method called after init under the historical host model. stop suspends activity, destroy cleans up before unloading, and paint draws content; none states the next lifecycle stage after initialization.
Evidence in the complete study note
init initializes once; start follows initialization and resumes activity; stop suspends activity when the host deactivates it; destroy performs final cleanup before unloading. paint draws content and is not a constructor.OOP34
Choice by choice
A · correct — start follows initialization and resumes applet activity, exactly matching the requested lifecycle point.
B · incorrect — stop suspends activity when deactivated; it is not the post-init startup callback.
C · incorrect — destroy performs cleanup before unloading, rather than starting activity immediately after initialization.
D · incorrect — paint draws content and is not the lifecycle startup callback that follows init.
Question 122
In the historical Java applet lifecycle, which callback performs final cleanup when a compatible host normally unloads the applet?
A. start
B. stop
C. destroy
D. paint
Hint / Module Reference (Where to Read)
Use the historical host lifecycle and distinguish activation, suspension, drawing and unloading.
The applet lifecycle assigns final cleanup before unloading to destroy. start begins or resumes activity, stop handles host deactivation, and paint draws content. A normal browser shutdown may cause an unload, but unloading can also occur without shutting the browser down. The revised stem therefore asks for the cleanup callback directly and does not make an incorrect exclusive shutdown claim or promise cleanup after an abrupt crash.
Evidence in the complete study note
init initializes once; start follows initialization and resumes activity; stop suspends activity when the host deactivates it; destroy performs final cleanup before unloading. paint draws content and is not a constructor.OOP34
destroy is not defined exclusively as “browser shuts down”: the host may destroy an applet on unloading, and abrupt process termination does not guarantee cleanup.OOP34
Choice by choice
A · incorrect — start begins or resumes activity rather than performing final cleanup.
B · incorrect — stop suspends activity on host deactivation, not final unloading.
C · correct — destroy performs final cleanup before normal applet unloading.
D · incorrect — paint draws content rather than handling final cleanup.
Question 123
What are non-static Java fields declared directly in a class, outside methods, constructors and initializer-block local scopes, called?
A. Instance variables
B. Local variables
C. Class variables
D. Static variables
Hint / Module Reference (Where to Read)
Locate the declaration scope and check default initialization versus definite assignment.
Fields belong to a class declaration, but non-static fields hold separate state for each object and are called instance variables. Static fields are class variables shared by instances, so merely being outside a method would not distinguish them. The stem now explicitly excludes static and block-local declarations. Local variables belong to method, constructor or block scopes rather than to each object’s field state.
Evidence in the complete study note
The introductory three-way grouping is local, instance and class/static variables. Locals occur in methods, constructors or blocks; they must be definitely assigned before use and cannot have public/private/protected modifiers. Fields occur in a class outside method bodies; non-static fields belong to each instance, while static fields belong to the class. Declaration location alone does not distinguish instance and static fields.OOP05
Choice by choice
A · correct — Non-static object fields are instance variables.
B · incorrect — Locals belong to executable scopes rather than the class’s object state.
C · incorrect — Class variables are static fields, excluded by the question.
D · incorrect — Static variables are shared class fields, excluded by the question.
Question 124
Which one of the following sending a message to an object is correct?
A. obj.add
B. obj.add.obj
C. obj.add()
D. obj.add().obj
Hint / Module Reference (Where to Read)
Separate parameters from arguments and operations that read state from operations that change it.
Binding attributes and methods into one class is encapsulation.
Evidence in the complete study note
Encapsulation groups related state and operations and controls access. Information hiding keeps implementation decisions behind a stable interface.OOP02
Inheritance forms a subtype relationship and may reuse implementation. Polymorphism lets code using a common type invoke behavior appropriate to different concrete objects. Prefer a precise mechanism over a vague slogan: wrapping fields and methods points to encapsulation; showing what an operation does while hiding how points to abstraction.OOP02
A subclass overrides an eligible inherited instance method with the same signature and a compatible return type; a covariant reference return may be a subtype.OOP14
Choice by choice
A · incorrect — Transfers properties across classes
B · correct — Groups data and the operations on that data
C · incorrect — Allows an operation to take different forms
D · incorrect — Replaces an inherited method implementation
Question 126
A keyword used to have only a single piece of storage for a particular field is?
A. this
B. object
C. Final
D. Static
Hint / Module Reference (Where to Read)
Decide whether a member belongs to a class or an object, then check initialization and final restrictions.
Only one copy of each class variable exists per class regardless of object count, and static is the declaration modifier for that property.
Evidence in the complete study note
static gives one field per loaded class, shared by its instances. If count starts at zero and every constructor increments it, three creations leave count=3. Prefer ClassName.count and ClassName.utility().OOP07
final prevents reassignment of a variable, overriding of a method or extension of a class. A final reference may still refer to a mutable object.OOP07
Choice by choice
A · incorrect — this does not provide shared storage
B · incorrect — object does not declare the shared field category
C · incorrect — final prevents modification rather than determining one copy
D · correct — Static denotes the intended static modifier, though the literal Java spelling is lowercase static
Question 127
What represents the concept that data can only be manipulated in known, well-defined ways
A. Inheritance
B. Information hiding
C. Polymorphism
D. overloading
Hint / Module Reference (Where to Read)
Identify whether the emphasis is grouping state, hiding implementation, exposing essentials or varying behavior.
Encapsulation hides class data and controls access through the class's methods. This is the information-hiding control over how data is manipulated.
Evidence in the complete study note
Encapsulation groups related state and operations and controls access. Information hiding keeps implementation decisions behind a stable interface. Abstraction presents the essential operations while omitting details irrelevant to the caller.OOP02
Inheritance forms a subtype relationship and may reuse implementation. Polymorphism lets code using a common type invoke behavior appropriate to different concrete objects.OOP02
Overloaded methods share a name but have different parameter types, counts or type order.OOP12
Choice by choice
A · incorrect — Does not restrict manipulation paths
B · correct — Describes control through the hidden-data/method boundary
C · incorrect — Concerns multiple forms rather than restricting access
D · incorrect — Concerns same-name methods with differing parameters
Question 128
Which one of the following is incorrect about inheritance
A. Subclass inherits members of superclass
B. Constructors are not members
C. Constructors of superclass can be invoked from subclass
D. Constructors of superclass inherited by subclass
Hint / Module Reference (Where to Read)
Read the cited conceptual rules, state the model, and apply them before comparing the alternatives.
Correct answer: D — Constructors of superclass inherited by subclass
Java constructors are not members and are not inherited, but a subclass can invoke its superclass constructor using super.
Evidence in the complete study note
In Java’s class-declaration terminology, constructors are not members and are not inherited. A subclass can invoke superclass construction; this does not turn the superclass constructor into an inherited subclass method.OOP-S05
Under Java 17 rules, an explicit this(args) or super(args) invocation must be the first constructor statement. this invokes another constructor in the same class; super invokes the immediate superclass constructor. A constructor cannot explicitly invoke both. If there is no explicit delegation, an implicit super() is inserted; a matching accessible no-argument parent constructor must exist.OOP10
class Dog extends Animal declares a subclass/derived/child of a superclass/base/parent.OOP13
Choice by choice
A · incorrect — Subclass membership inheritance is the general mechanism
B · incorrect — Constructors are not members.
C · incorrect — Explicitly demonstrated with super(arg-list)
D · correct — Contradicts the noninheritance rule
Question 129
Consider an abstract Java class that explicitly declares an abstract method. Which statement is incorrect about that class? In C, constructing objects means directly instantiating this abstract class.
A. It is a class containing abstract method
B. Abstract method is incomplete
C. Used to construct objects
D. None of the above
Hint / Module Reference (Where to Read)
Check whether a class is concrete and whether every inherited abstract contract has an implementation.
The given class contains an abstract method by assumption, and that method has no implementation body. An abstract class may include constructors and concrete methods, but it cannot itself be directly instantiated. C is therefore the false statement in the stated sense. A describes the given class rather than imposing a requirement on every abstract class, and None is false because C is incorrect.
Evidence in the complete study note
An abstract class cannot be directly instantiated but can define fields, constructors, abstract methods and concrete methods. It need not contain an abstract method. An abstract method has no body; abstract and final conflict because an operation cannot require overriding while forbidding it.OOP18
A concrete subclass must provide or inherit implementations of all required abstract methods; otherwise it must itself be abstract.OOP18
Choice by choice
A · incorrect — This is true of the particular class because the stem explicitly says it declares an abstract method.
B · incorrect — An abstract method has no implementation body, which is the intended meaning of incomplete.
C · correct — Direct instantiation of the abstract class is prohibited, so this is the incorrect statement.
D · incorrect — C is an incorrect statement, so None of the above cannot be selected.
Question 130
Which statement correctly describes imports in an ordinary Java source compilation unit?
A. A Java source file may contain zero or more import statements before its top-level type declarations
B. Import statement appears after the class declaration
C. Import statement appears before package statement
D. All of the above
Hint / Module Reference (Where to Read)
Check declaration order, exact case, package boundaries and the compile-versus-launch stage.
Correct answer: A — A Java source file may contain zero or more import statements before its top-level type declarations
An optional package declaration comes first, followed by any import declarations, then the top-level type declarations. A source file can have no imports or multiple imports in that position. B places imports after a class, and C places them before the package declaration, reversing the ordering rules. D includes those false statements. These ordering rules apply to Java source files, rather than compiled .class contents.
Evidence in the complete study note
package p; precedes imports; imports precede top-level type declarations.OOP28
Choice by choice
A · correct — This places zero or more source imports before the top-level types.
B · incorrect — Imports precede top-level class declarations rather than following them.
C · incorrect — The package declaration, when present, precedes imports.
D · incorrect — B and C reverse the required ordering, so all is incorrect.
Question 131
Which one of the following is correct about narrowing casting?
A. Done by the programmer
B. It is automatic
C. Done by the compiler
D. All
Hint / Module Reference (Where to Read)
Identify the primitive category, width and conversion rule before evaluating a declaration or expression.
Narrowing is explicit and must be done programmatically using a cast; the automatic conversion section instead describes widening.
Evidence in the complete study note
A compatible widening conversion often needs no cast; narrowing usually needs an explicit cast and may lose information. Widening an int to float can lose precision, so “widening never loses information” is false.OOP06
Choice by choice
A · correct — Matches explicit programmatic narrowing
B · incorrect — Confuses narrowing with widening
C · incorrect — The compiler does not insert the narrowing cast described here
D · incorrect — B and C do not match explicit narrowing
Question 132
Which one of the following is incorrect about method overriding?
A. A method declared final cannot be overridden
B. Similar argument list is required
C. Constructors cannot be overridden
D. None
Hint / Module Reference (Where to Read)
Check inheritance, signature compatibility, visibility and eligibility for an override.
final methods cannot be overridden, argument types and order must match, and constructors are not inherited methods. Hence none of A-C is incorrect under the intended exact-match reading.
Evidence in the complete study note
A subclass overrides an eligible inherited instance method with the same signature and a compatible return type; a covariant reference return may be a subtype. Visibility cannot become more restrictive, and checked exceptions cannot be broadened incompatibly. @Override requests compiler checking; Java has no override keyword. Constructors, final methods, static methods and private parent methods are not overridden.OOP14
Constructors are not inherited or overridden.OOP09
Choice by choice
A · incorrect — Explicitly prohibited by overriding rules
B · incorrect — Here, “similar argument list” must mean the same argument types in the same order.
C · incorrect — Constructors are not inherited methods and have the class's own name
D · correct — None of A-C contradicts these rules
Question 133
Which listed cases are not checked exceptions in Java? Interpret “array index out of bounds” as ArrayIndexOutOfBoundsException and “file required not found” as FileNotFoundException. Select all that apply.
A. Missing semicolons
B. Array index out of bounds
C. Usage of undeclared variables
D. File required not found
Hint / Module Reference (Where to Read)
Separate source errors from runtime exceptions and determine the hierarchy and checked obligation.
Correct answers (select all): A, B, C — Missing semicolons; Array index out of bounds; Usage of undeclared variables
A missing semicolon and an undeclared variable are source errors rejected during compilation; neither is a checked exception. ArrayIndexOutOfBoundsException is a runtime exception and is unchecked. FileNotFoundException is a checked exception, so its catch-or-declare obligation is checked by the compiler even though an actual throw occurs at runtime. The revised multiple-selection question accepts all three cases outside the checked-exception category.
Evidence in the complete study note
IOException, FileNotFoundException and SQLException are standard checked examples. ArithmeticException, NullPointerException, ClassCastException and array bounds exceptions are unchecked. A missing semicolon or undeclared variable is a compile-time source error, not a checked exception.OOP29
Checked does not mean the exception occurs at compile time: the compiler checks an obligation to catch or declare it, while an actual throw occurs at runtime.OOP29
Choice by choice
A · correct — A missing semicolon is a compile-time source error, not a checked exception.
B · correct — ArrayIndexOutOfBoundsException is unchecked.
C · correct — An undeclared variable is a compile-time source error, not a checked exception.
D · incorrect — FileNotFoundException is checked and therefore is not selected.
Question 134
If a class is named Student, the class constructor name is___________..
A. Any legal java identifier
B. Any legal java identifier starting with s
C. Student
D. Student constructor
Hint / Module Reference (Where to Read)
Check the class name, return-type absence and the constructors actually declared.
The access table defines private as visible to the class only.
Evidence in the complete study note
For ordinary members: private restricts access to the declaring class/nest; no modifier grants package access; protected grants same-package access plus qualified subclass access; public is widest, provided the declaring type itself is accessible.OOP08
Choice by choice
A · incorrect — Default includes the package
B · incorrect — Protected includes package and subclasses
C · incorrect — Public is visible to the world
D · correct — Matches class-only visibility
Question 136
The keyword used to create subclass/derived class in inheritance is___________
A. Implement
B. Implements
C. extend
D. extends
Hint / Module Reference (Where to Read)
Identify the subtype or ownership relationship and distinguish class inheritance from interface contracts.
OOP28 explicitly allows $ in Java identifiers but rejects @ as an identifier character. D contains @, so it cannot be the requested variable name. A’s dollar sign and underscore do not create that defect. By2 and Java also contain ordinary letters and a permitted trailing digit where present.
Evidence in the complete study note
For ordinary ASCII Java identifiers, the first character is a letter, underscore or dollar sign; later characters may also be digits. A reserved keyword is not an ordinary identifier, and a lone underscore is not a valid identifier in Java 17.OOP-S01
Java identifiers are case sensitive; $ is allowed but @ is not an identifier character.OOP28
Choice by choice
A · incorrect — A$_2 uses a letter first and permitted dollar sign, underscore and digit thereafter.
B · incorrect — By2 starts with a letter and has an allowed digit after the letters.
C · incorrect — Java is a case-sensitive ordinary identifier, not the prohibited @ pattern identified in the note.
D · correct — A@2$ contains @, which OOP28 explicitly prohibits within a Java identifier.
Question 138
A blue print of an object is called _________.
A. operation
B. method
C. class
D. Attribute
Hint / Module Reference (Where to Read)
Distinguish an object’s stored state, operations, identity and class definition.
A class is the blueprint or template for an object.
Evidence in the complete study note
An object has identity, state and behavior. State is stored in fields; behavior is provided by methods. A Rectangle object may hold width and height and answer getArea() or getPerimeter(). Two objects can have equal fields and still be distinct objects. A class defines their common structure and behavior; an object is a particular instance.OOP01
Choice by choice
A · incorrect — Operation describes behavior
B · incorrect — Method implements an operation
C · correct — The stated blueprint concept
D · incorrect — Attribute describes state
Question 139
How is generalization implemented in Object-Oriented software engineering?
A. Inheritance
B. Polymorphism
C. Encapsulation
D. Abstract Classes
Hint / Module Reference (Where to Read)
Identify the subtype or ownership relationship and distinguish class inheritance from interface contracts.
Generalization groups specialized classes under a general superclass; a subclass specializes its superclass, and inheritance implements that hierarchy.
Evidence in the complete study note
Use inheritance when a subtype can satisfy the parent’s contract: Dog is an Animal.OOP13
Aggregation models one instance grouping other instances as a whole with parts. It is an object-relationship concept, not a method-dispatch rule. Inheritance instead relates a specialized class to a general class; overridden operations can then provide polymorphic behavior.OOP-S05
Encapsulation groups related state and operations and controls access. Information hiding keeps implementation decisions behind a stable interface. Abstraction presents the essential operations while omitting details irrelevant to the caller.OOP02
Choice by choice
A · correct — Creates the generalized/specialized class hierarchy
B · incorrect — Uses multiple forms within a hierarchy rather than creating its relationship
C · incorrect — Groups data and methods
D · incorrect — Can serve as a base but is not the general implementation mechanism required
Question 140
Choose the incorrect statement in terms of Objects.
A. Objects are abstractions of real-world
B. Objects can't manage themselves
C. Objects encapsulate state and representation information
D. All of the mentioned
Hint / Module Reference (Where to Read)
Distinguish an object’s stored state, operations, identity and class definition.
Correct answer: B — “Objects cannot manage themselves” is the incorrect generalization.
OOP01 says objects hold state and behavior, control responsibilities, communicate through method calls and can delegate. It expressly calls the claim that objects cannot manage their own state misleading. Therefore B is the false generalization. A is a conventional modeling description, and C describes encapsulated state, so all statements cannot be incorrect.
Evidence in the complete study note
An object has identity, state and behavior. State is stored in fields; behavior is provided by methods. A Rectangle object may hold width and height and answer getArea() or getPerimeter(). Two objects can have equal fields and still be distinct objects. A class defines their common structure and behavior; an object is a particular instance.OOP01
Choose classes around responsibilities: an account controls its own balance, a transaction records a payment, and a service coordinates them. Objects send messages through method calls such as obj.add(). They can delegate work to other objects; saying that objects cannot manage their own state is misleading. Procedural and object oriented designs both support reuse; global shared data is not compulsory in procedural programming.OOP01
Encapsulation groups related state and operations and controls access. Information hiding keeps implementation decisions behind a stable interface. Abstraction presents the essential operations while omitting details irrelevant to the caller.OOP02
Choice by choice
A · incorrect — Objects can model abstractions of real-world entities; this conventional modeling description is not the identified false generalization.
B · correct — Objects can control their state through behavior and delegate responsibilities, contradicting this categorical claim.
C · incorrect — Encapsulation of state and related representation is consistent with the note’s object model.
D · incorrect — The supported abstraction and encapsulation descriptions prevent treating every supplied statement as incorrect.
Question 141
Which OOP concept describes one operation in a class hierarchy producing different behavior for different runtime object types?
A. Aggregation
B. Polymorphism
C. Inheritance
Hint / Module Reference (Where to Read)
Check what compiles from the declared type, then select behavior from the actual runtime class.
Polymorphism lets code using a common type invoke behavior appropriate to each concrete object. Eligible overriding supplies this effect at runtime: the same inherited operation may dispatch to a different subclass implementation. Inheritance establishes the relationship that permits those related types, but does not alone name the varying behavior. Aggregation instead models a whole grouping parts, rather than method dispatch.
Evidence in the complete study note
For an eligible overridden sound(), a.sound() invokes Dog.sound() at runtime.OOP15
Aggregation models one instance grouping other instances as a whole with parts. It is an object-relationship concept, not a method-dispatch rule. Inheritance instead relates a specialized class to a general class; overridden operations can then provide polymorphic behavior.OOP-S05
Inheritance forms a subtype relationship and may reuse implementation. Polymorphism lets code using a common type invoke behavior appropriate to different concrete objects.OOP02
Choice by choice
A · incorrect — Aggregation describes whole-part object relationships, not varying operation behavior.
B · correct — Polymorphism names behavior selected appropriately for different concrete object types through a common operation.
C · incorrect — Inheritance establishes the subtype hierarchy; polymorphism names the differing behavior through that hierarchy.
Question 142
Which statement correctly describes the implicit object argument in an ordinary C++17 member-function call?
A. The this pointer is supplied as the implicit object argument to ordinary non-static member functions
B. The this pointer is supplied as a hidden argument to static member variables
C. The this pointer is supplied as a hidden argument to static member functions
D. The this pointer is supplied as a hidden argument to every member function, including static functions
Hint / Module Reference (Where to Read)
Use the stated language rules and identify whether a member call has an implicit current object.
Correct answer: A — The this pointer is supplied as the implicit object argument to ordinary non-static member functions
In ordinary C++17 non-static member functions, this points to the object on which the function is invoked and can be understood as the implicit object argument. Member variables do not receive call arguments. Static member functions have no current instance and no this pointer, so a claim about every member function is also too broad. Correcting variables to functions in A restores the intended distinction.
Evidence in the complete study note
In ordinary C++17 non-static member functions, this is a pointer to the object on which the function is called; this->field selects a member. It is often explained as an implicit object argument to a member function call. It is not an argument passed to member variables, and a static member function has no this pointer.OOP17
Choice by choice
A · correct — Ordinary non-static member functions have the implicit object represented by this.
B · incorrect — Variables are not calls and do not receive hidden object arguments.
C · incorrect — Static member functions have no this pointer.
D · incorrect — Including static functions makes the universal claim false.
Question 143
What does this Java program print?
public class Calculation {
public static void main(String[] args) {
int sum = 0;
for (int j = 1; j <= 10; j++) {
sum = sum + j;
}
System.out.println(+sum);
}
}
A. 55
B. 44
C. 33
D. 66
Hint / Module Reference (Where to Read)
Trace condition tests, control transfers and printing as separate steps.
The loop adds each integer from 1 through 10 exactly once. Their sum is 10×11/2=55, and unary plus does not change that integer before printing. The malformed trailing token is replaced by the required closing braces, leaving the loop itself unchanged. Forty-four and thirty-three are not the inclusive sum, while sixty-six would correspond to additionally summing 11, beyond the bound.
Evidence in the complete study note
A loop summing j=1..10 yields 55.OOP25
Prefix ++ and -- update a variable before supplying its value; postfix forms supply the old value before the update. Multiplication, division and remainder bind before addition and subtraction; same-level binary arithmetic groups left to right. Integer division truncates toward zero. Unary plus preserves its numeric operand’s value.OOP-S03
Choice by choice
A · correct — The inclusive sum 1+2+…+10 is 55.
B · incorrect — 44 is not the sum of the ten loop values.
C · incorrect — 33 is not the sum produced by the inclusive loop.
D · incorrect — 66 would include an extra 11 beyond the stated upper bound.
Question 144
Which exact case-sensitive Java keyword declares a subclass relationship to a superclass?
A. Inherits
B. Superclass
C. extends
D. Implements
Hint / Module Reference (Where to Read)
Identify the subtype or ownership relationship and distinguish class inheritance from interface contracts.
A Java class declares its superclass with extends, as in class Dog extends Animal. The lowercase spelling is required because Java identifiers and keywords are case sensitive. implements is used for interface contracts rather than the superclass relationship, while Inherits and Superclass are not the required keyword. Correcting the option’s initial letter makes the subclass-declaration question exact without changing its concept.
Evidence in the complete study note
class Dog extends Animal declares a subclass/derived/child of a superclass/base/parent.OOP13
interface Payable{double getPaymentAmount();} declares an abstract public operation. class Invoice implements Payable must provide public double getPaymentAmount(), perhaps returning getQuantity()*getPricePerItem(). A class can extend a superclass and implement zero or more interfaces. An interface can extend several interfaces.OOP19
Java identifiers are case sensitive; $ is allowed but @ is not an identifier character.OOP28
Choice by choice
A · incorrect — Inherits is not the Java subclass-declaration keyword.
B · incorrect — Superclass names the relationship but is not its declaration keyword.
C · correct — extends is the exact keyword used between subclass and superclass names.
D · incorrect — implements concerns interfaces, and the printed capitalized word is not the required keyword.
Question 145
A BankAccount keeps its balance and deposit operation together. Clients cannot assign balance directly and must use validated operations. Which principle specifically names this bundling of state with operations and control of access to that state?
A. Abstraction
B. Inheritance
C. Polymorphism
D. Encapsulation
Hint / Module Reference (Where to Read)
Identify whether the emphasis is grouping state, hiding implementation, exposing essentials or varying behavior.
Correct answer: D — Encapsulation controls which information of an object is exposed.
The question specifically asks for the mechanism that groups an object’s state with its operations and controls access to that state. That is encapsulation. Abstraction also matters in the account’s public view, but it names the essential operations presented to callers rather than the requested state-and-operation boundary. Inheritance and polymorphism concern subtype relationships and behavior through common types, respectively.
Evidence in the complete study note
Encapsulation groups related state and operations and controls access. Information hiding keeps implementation decisions behind a stable interface. Abstraction presents the essential operations while omitting details irrelevant to the caller. These ideas overlap: a private balance plus deposit(amount) can demonstrate all three, depending on what the question emphasizes.OOP02
Inheritance forms a subtype relationship and may reuse implementation. Polymorphism lets code using a common type invoke behavior appropriate to different concrete objects.OOP02
Choice by choice
A · incorrect — Abstraction emphasizes the essential caller-facing view; it does not specifically name the requested grouping and state-access boundary.
B · incorrect — Inheritance forms a subtype relationship rather than the requested state-and-operation boundary.
C · incorrect — Polymorphism selects behavior through a common type rather than grouping and controlling this state.
D · correct — Encapsulation specifically groups the balance with its operations and controls direct access.
Question 146
Consider the following code snippet
class Animal { void sound() { System.out.printIn("Animal sound"); } }
class Dog extends Animal { void sound() { System.out.printIn("Bark!"); } }
Which OOP concept is illustrated when Dog provides its own version of sound?
A. Method overriding
B. Method overloading
C. Abstraction
D. Encapsulation
Hint / Module Reference (Where to Read)
Check inheritance, signature compatibility, visibility and eligibility for an override.
Dog repeats sound() from Animal with its own body: that is a subclass method with the same name/signature as its superclass method. Literal printIn is a typo, but does not change the declaration relationship.
Evidence in the complete study note
A subclass overrides an eligible inherited instance method with the same signature and a compatible return type; a covariant reference return may be a subtype.OOP14
Overloaded methods share a name but have different parameter types, counts or type order.OOP12
Check exact Java spelling and syntax: extends differs from Extends, println differs from printIn/printin, constructor names must match class names, and braces and operators such as <= and == affect validity and behavior. Java is case sensitive: an invalid program may not compile even when a possible trace seems clear.OOP37
Choice by choice
A · correct — Matches the same-signature subclass relationship
B · incorrect — No changed parameter list is shown
C · incorrect — No abstract declaration or essential-interface example is needed
D · incorrect — The example emphasizes replacement behavior, not grouping hidden data
Question 147
Which most restrictive Java member-access category admits unrelated classes in the same package and qualified subclass access in other packages, while excluding unrelated classes in other packages?
A. Public
B. Default
C. Private
D. Protected
Hint / Module Reference (Where to Read)
Locate the accessing code, declaring type, package and receiver before applying visibility rules.
Correct answer: D — Protected, subject to cross-package receiver restrictions.
Protected combines same-package access with qualified subclass access across packages. It therefore reaches both required contexts while excluding unrelated other-package clients. Public is broader and violates that exclusion. Package/default access does not reach the other-package subclass, while private is narrower than the required same-package access. Cross-package instance access must still use the inherited context or an appropriate subclass-typed receiver.
Evidence in the complete study note
For ordinary members: private restricts access to the declaring class/nest; no modifier grants package access; protected grants same-package access plus qualified subclass access; public is widest, provided the declaring type itself is accessible. Top-level classes/interfaces may be public or package-private, not protected/private. Member types have additional visibility possibilities.OOP08
Across packages, a subclass accessing a protected instance member must do so through its own inherited context or an appropriate subclass-typed receiver, not any arbitrary superclass object.OOP08
Choice by choice
A · incorrect — Public also admits unrelated classes in other packages, violating the explicit exclusion.
B · incorrect — Package/default access does not admit the required subclass access across packages.
C · incorrect — Private does not grant access to unrelated same-package classes.
D · correct — Protected grants the required same-package and qualified cross-package subclass access without granting universal access.
Question 148
In abstract class Employee, calculateTax must remain a public concrete instance method while explicitly forbidding subclasses from overriding it. Which declaration achieves that requirement?
A. public abstract double calculateTax();
B. public final double calculateTax(){ return 0.0; }
C. private double calculateTax(){ return 0.0; }
D. public static double calculateTax(){ return 0.0; }
Hint / Module Reference (Where to Read)
Decide whether a member belongs to a class or an object, then check initialization and final restrictions.
Correct answer: B — public final double calculateTax(){ return 0.0; }
final explicitly prohibits overriding an instance method while allowing it to remain public and concrete. abstract instead requires an implementation and supplies no body. private would remove public access and create independent child declarations rather than preserve the required public contract. static changes the method into a class operation whose same-signature child method hides it. Only the public final instance declaration satisfies all stated requirements.
Evidence in the complete study note
final prevents reassignment of a variable, overriding of a method or extension of a class.OOP07
A subclass overrides an eligible inherited instance method with the same signature and a compatible return type; a covariant reference return may be a subtype. Visibility cannot become more restrictive, and checked exceptions cannot be broadened incompatibly. @Override requests compiler checking; Java has no override keyword. Constructors, final methods, static methods and private parent methods are not overridden.OOP14
An abstract method has no body; abstract and final conflict because an operation cannot require overriding while forbidding it.OOP18
For ordinary members: private restricts access to the declaring class/nest; no modifier grants package access; protected grants same-package access plus qualified subclass access; public is widest, provided the declaring type itself is accessible.OOP08
Fields are hidden rather than dynamically overridden, and same-signature static methods hide rather than override.OOP16
Choice by choice
A · incorrect — abstract removes the concrete implementation and permits or requires overriding.
B · correct — public final retains public concrete instance behavior and prohibits overriding.
C · incorrect — private violates the required public accessibility.
D · incorrect — static violates the requirement to remain an instance method.
Question 149
What will be the output for the Java expression: 8 - 2 * 5 * (3 + 9 / 3) + 6 / 3
A. -150
B. -30
C. -50
D. 50
Hint / Module Reference (Where to Read)
Respect operator grouping and operand types, then trace each operation in evaluation order.
Inside the parentheses, 9/3=3, so the group is 3+3=6. The multiplication gives 2*5*6=60, and the remaining integer division gives 6/3=2. The result is 8-60+2=-50, matching OOP23’s explicit example. The negative sign follows from subtracting the larger product.
Evidence in the complete study note
In 8-2*5*(3+9/3)+6/3, the result is -50.OOP23
Prefix ++ and -- update a variable before supplying its value; postfix forms supply the old value before the update. Multiplication, division and remainder bind before addition and subtraction; same-level binary arithmetic groups left to right. Integer division truncates toward zero. Unary plus preserves its numeric operand’s value.OOP-S03
Choice by choice
A · incorrect — -150 does not follow the parenthesized value 6 and product 60 obtained from the stated operands.
B · incorrect — -30 miscalculates the product or remaining terms; 8-60+2 is -50.
C · correct — The grouped arithmetic gives 8-60+2, which equals -50.
D · incorrect — The product is subtracted, so changing -50 to positive 50 loses the required sign.
Question 150
Which one of the following is used for constants in Java?
A. const
B. final
C. define
D. All of the above
Hint / Module Reference (Where to Read)
Decide whether a member belongs to a class or an object, then check initialization and final restrictions.
final creates the equivalent of a named constant by preventing value modification.
Evidence in the complete study note
final prevents reassignment of a variable, overriding of a method or extension of a class. A final reference may still refer to a mutable object. A shared mathematical PI is a good static final candidate; a student name normally belongs to an instance.OOP07
Choice by choice
A · incorrect — Not the keyword given for constants
B · correct — Explicitly stated named-constant mechanism
C · incorrect — Not Java’s named-constant keyword
D · incorrect — Only final is established
Question 151
In which character method returns the uppercase form of the specified
char value.
A. a | toUpperCase()
B. i? | toLowerCase()
C. @) toString()
D. | isDigit()
Hint / Module Reference (Where to Read)
Read the cited conceptual rules, state the model, and apply them before comparing the alternatives.
OOP22 names Character.toUpperCase(ch) as the operation that converts a character to uppercase. A supplies the correct method name, with its argument abbreviated away. Lowercase conversion, string representation and a digit test have different purposes.
Evidence in the complete study note
Character.toUpperCase(ch) supplies the uppercase equivalent where one exists; Character.toLowerCase(ch) supplies the lowercase equivalent. Character.isDigit(ch) tests whether a character is a digit and returns boolean. Character.toString(ch) supplies a one-character String rather than converting letter case.OOP-S04
Choice by choice
A · correct — toUpperCase is the named conversion; an actual Character call supplies the char argument.
B · incorrect — toLowerCase names the opposite letter-case conversion rather than producing uppercase.
C · incorrect — toString names textual representation rather than uppercase conversion of the supplied character.
D · incorrect — isDigit names a predicate about a character, not an uppercase conversion operation.
Question 152
In which parameter is the regular expression to which this string is to be
matched?
A. a | regul x
B. Q « x
C. |@| regex v
D. | None of the above x
Hint / Module Reference (Where to Read)
Separate identity, content equality, immutable values and references that may be reassigned.
Correct answer: C — regex, in the documented Java String.matches(String regex) signature.
In the Java String-matching API, matches(String regex) names its regular-expression parameter regex. This answers the API-signature question; it does not make regex a mandatory parameter name in arbitrary programmer-defined methods.
Evidence in the complete study note
charAt(index) returns a char; length() counts UTF-16 units; substring(begin,end) excludes end. Character.toUpperCase(ch) converts a character, and matches(String regex) takes a regular-expression parameter named regex.OOP22
Choice by choice
A · incorrect — The image recovers regul, which is not the parameter name in OOP22’s documented matches signature.
B · incorrect — The image recovers reg; the documented String.matches parameter is named regex, not reg.
C · correct — The image places regex at C, matching the regular-expression parameter named in OOP22.
D · incorrect — The documented parameter name is present at C, so none of the above is false.
Question 153
Which one of the following is not the purpose of the super keyword?
A. Refer to the current object
B. Call superclass constructor
C. Access hidden variables
D. Invoke superclass method with the same name as the subclass method
Hint / Module Reference (Where to Read)
Distinguish the current instance, parent context, hidden fields and static dispatch.
super refers to the immediate superclass and can access its members or constructor. It is distinguished from this, which refers to the current instance.
Evidence in the complete study note
Java this denotes the current object; this.name=name distinguishes a field from a parameter. super.name selects a hidden superclass field; super.sound() directly requests the parent implementation. It does not create a second parent object. An unqualified instance call may dispatch dynamically; an explicit super call is different.OOP16
Under Java 17 rules, an explicit this(args) or super(args) invocation must be the first constructor statement. this invokes another constructor in the same class; super invokes the immediate superclass constructor. A constructor cannot explicitly invoke both.OOP10
Choice by choice
A · correct — Current-object role belongs to this, not the superclass qualifier
B · incorrect — Explicit superclass-constructor use
C · incorrect — super.member can resolve hidden variables
D · incorrect — Explicit superclass-method access use
Question 154
Which one of the following has the same name as the class name?
A. Method
B. Variable
C. Constructor
D. Package name
Hint / Module Reference (Where to Read)
Check the class name, return-type absence and the constructors actually declared.
A class defines the common data/method shape of its objects and is itself a reference type. That supports attributes/methods, a distinct type, and a collection of similar objects.
Evidence in the complete study note
An object has identity, state and behavior. State is stored in fields; behavior is provided by methods. A Rectangle object may hold width and height and answer getArea() or getPerimeter(). Two objects can have equal fields and still be distinct objects. A class defines their common structure and behavior; an object is a particular instance.OOP01
Choice by choice
A · incorrect — Class consists of data and methods
B · incorrect — Class defines a reference type and its objects' shape
C · incorrect — Matches the definition of a set of similar objects
D · correct — Combines the three supported descriptions
Question 156
Which one is used to achieve the encapsulation concept in Java?
A. Declare the variables of a class as private.
B. Provide public setter and getter methods to modify and view the variable's
values.
C. By using an Interface.
D. A & B
Hint / Module Reference (Where to Read)
Identify whether the emphasis is grouping state, hiding implementation, exposing essentials or varying behavior.
Hidden private fields plus accessible methods provide controlled access to class data. A alone hides data; B supplies the permitted interaction boundary.
Evidence in the complete study note
Encapsulation groups related state and operations and controls access. Information hiding keeps implementation decisions behind a stable interface.OOP02
For ordinary members: private restricts access to the declaring class/nest; no modifier grants package access; protected grants same-package access plus qualified subclass access; public is widest, provided the declaring type itself is accessible.OOP08
An accessor/getter returns information; a mutator/setter changes state. Encapsulation does not require blindly generating setters for every field: validate changes and expose only useful operations.OOP11
Choice by choice
A · incorrect — Provides class-only data visibility
B · incorrect — Provides the methods through which hidden data can be accessed
C · incorrect — An interface alone does not hide a class's data fields
D · correct — Combines hiding and controlled method access
Question 157
Which one of the following is the collection of statements that performs a
specific operation?
A. Class
B. Package
C. Variable
D. Method
Hint / Module Reference (Where to Read)
Separate parameters from arguments and operations that read state from operations that change it.
Methods are class members that perform operations and contain executable bodies.
Evidence in the complete study note
A method has modifiers, return type, name, parameter list and body: public int getAge(){return age;}. A void method returns no value. Parameters name the inputs in the declaration; arguments supply values at a call.OOP11
An object has identity, state and behavior. State is stored in fields; behavior is provided by methods. A Rectangle object may hold width and height and answer getArea() or getPerimeter().OOP01
Choice by choice
A · incorrect — A class groups fields and methods, not just one operation's statements
B · incorrect — Package groups classes/interfaces
C · incorrect — Variable stores data rather than an operation body
D · correct — Matches an operation implemented by a statement body
Question 158
For this valid Java instance method inside a class, which input/output statement is correct?
public void test(boolean a, boolean b) {
if (a) {
System.out.println("A");
} else if (a && b) {
System.out.println("A && B");
} else {
if (!b) {
System.out.println("!B");
} else {
System.out.println("None");
}
}
}
A. If a and b are both true, the output is "A && B".
B. If a is true and b is false, the output is "!B".
C. If a is false and b is true, the output is "None".
D. If a and b are both false, the output is "None".
Hint / Module Reference (Where to Read)
Trace condition tests, control transfers and printing as separate steps.
Correct answer: C — a=false and b=true prints None.
If a is true, the first branch prints A regardless of b. If a is false, the else-if condition a && b is necessarily false, so execution enters the final else. There !b selects !B when b is false and None when b is true. Only C pairs its input values with the resulting output.
Evidence in the complete study note
In if(a)... else if(a&&b)..., the second condition can never be true on a path reaching it because a is already false.OOP25
For Boolean values, ! reverses true and false, && is true only when both operands are true, and || is true when at least one is true.OOP-S03
An if selects its true branch or, when present, its else branch; only the selected branch executes.OOP-S03
Choice by choice
A · incorrect — When a is true the first branch prints A, not the unreachable A && B branch.
B · incorrect — a=true selects A immediately regardless of b, so !B does not print.
C · correct — a=false bypasses both earlier tests and b=true makes !b false, selecting None.
D · incorrect — With both false, the final !b test is true and prints !B rather than None.
Question 159
Which one of the following methods can be overriding?
A. Abstract method
B. Final Method
C. Private method
D. Static method
Hint / Module Reference (Where to Read)
Check inheritance, signature compatibility, visibility and eligibility for an override.
Subclasses provide implementations of inherited abstract methods; the overriding rules explicitly exclude private, static and final methods.
Evidence in the complete study note
A subclass overrides an eligible inherited instance method with the same signature and a compatible return type; a covariant reference return may be a subtype.OOP14
Constructors, final methods, static methods and private parent methods are not overridden.OOP14
An abstract inherited method is implemented by an overriding method in a concrete subclass.OOP14
Choice by choice
A · correct — A child supplies the abstract method's implementation
B · incorrect — Explicitly prohibited
C · incorrect — Explicitly prohibited
D · incorrect — Explicitly prohibited; static behavior is not overridden
Question 160
Considering the following program, Which one of the following statements gives syntax error?
class Shape {
double x;
void area() { ... }
}
class Circle extends Shape {
double PI = 3.14;
void display() { ... }
}
A. Shape s = new Circle(); s.area();
B. Shape s = new Shape(); s.area();
C. Shape s = new Circle(); s.display();
D. Circle c = new Circle(); c.area();
Hint / Module Reference (Where to Read)
Check what compiles from the declared type, then select behavior from the actual runtime class.
Correct answer: C — Shape s = new Circle(); s.display();
A superclass reference can refer to a child object, but only exposes members available through its declared type. An Animal reference cannot directly access the Dog-specific field breed. Shape has no display(), so s.display() is the analogous compile-time member error.
Evidence in the complete study note
For Animal a=new Dog(), Animal is the declared type and Dog the actual type. The declared type determines which member operations compile. If fetch() exists only in Dog, a.fetch() fails compilation. For an eligible overridden sound(), a.sound() invokes Dog.sound() at runtime.OOP15
Choice by choice
A · incorrect — Shape reference can call its declared area; runtime dispatch applies
B · incorrect — Shape object and its declared area are consistent
C · correct — display is only declared in Circle, not the reference type Shape
D · incorrect — Circle inherits area from Shape
Question 161
One of the following does not describe an object
A. Delegates responsibilities to other objects
B. It receives and sends message from/to other objects
C. It is an instance of a class
D. It is an abstract description of the state and behavior of a collection of similar objects
Hint / Module Reference (Where to Read)
Distinguish an object’s stored state, operations, identity and class definition.
Correct answer: D — It is an abstract description of the state and behavior of a collection of similar objects
An object is a concrete runtime instance with state and behavior, whereas the abstract description of similar objects is the class blueprint.
Evidence in the complete study note
An object has identity, state and behavior. State is stored in fields; behavior is provided by methods. A Rectangle object may hold width and height and answer getArea() or getPerimeter(). Two objects can have equal fields and still be distinct objects. A class defines their common structure and behavior; an object is a particular instance.OOP01
Objects send messages through method calls such as obj.add(). They can delegate work to other objects; saying that objects cannot manage their own state is misleading.OOP01
Choice by choice
A · incorrect — Can describe collaborating operations, though delegation is not separately defined
B · incorrect — Method communication is consistent with the class operations description
C · incorrect — Explicit object definition
D · correct — Describes the class template rather than one instance
Question 162
Which statements about Java 17 constructors are false? Select all that apply.
A. A constructor can be overloaded
B. It has the same name as the class
C. can be invoked within any method without object instantiation.
D. the first line of the constructor must be a call on another constructor in the same class
E. Has no return statement
Hint / Module Reference (Where to Read)
Check the class name, return-type absence and the constructors actually declared.
Correct answers (select all): C, D, E — can be invoked within any method without object instantiation.; the first line of the constructor must be a call on another constructor in the same class; Has no return statement
Constructors can be overloaded and must use the class’s exact name, so A and B are true. They are not ordinary methods that can be called anywhere without construction. A same-class this(...) call is not mandatory; delegation may use super(...) or implicit super(). Constructors also allow bare return; even though they have no return type and cannot return an expression. Therefore C, D and E are false.
Evidence in the complete study note
A constructor has the class’s exact name and no return type, not even void. It initializes the new object and can be overloaded or private. A private constructor can support a factory or controlled singleton creation; it does not mean the class can never create an object internally.OOP09
Constructors are not inherited or overridden. They may contain return; but cannot return an expression. Fields get their default values before ordinary constructor initialization, rather than receiving defaults only because a default constructor was generated.OOP09
Under Java 17 rules, an explicit this(args) or super(args) invocation must be the first constructor statement. this invokes another constructor in the same class; super invokes the immediate superclass constructor. A constructor cannot explicitly invoke both. If there is no explicit delegation, an implicit super() is inserted; a matching accessible no-argument parent constructor must exist.OOP10
Choice by choice
A · incorrect — Overloading constructors is permitted, so this statement is true.
B · incorrect — A constructor has the exact class name, so this statement is true.
C · correct — Constructors are not ordinary methods callable from any method without construction.
D · correct — An explicit same-class constructor call is not mandatory.
E · correct — A bare return; is allowed, so the claim of no return statement is false.
Question 163
What is the output of the following program? Assume every necessary part of the program is included.
class Car {
void drive() {
System.out.print("generic noise:");
}
}
public class Casting {
public static void main(String []args){
Car a = new Car();
Ferrari d = (Ferrari)a;
a.drive();
d.brake();
}
}
class Ferrari extends Car {
void drive() {
System.out.print("drive:");
}
void brake() {
System.out.println("brake hard:");
}
}
A. Generic noise: brake hard
B. drive: brake hard
C. generic nose: drive: brake hard
D. Compiler Error
E. Run time Error
Hint / Module Reference (Where to Read)
Separate compile-time cast compatibility from the object’s actual runtime type.
Correct answer: E — Runtime ClassCastException before any drive or brake output.
a refers to an actual Car created with new Car(), not to a Ferrari. The cast is type-checkable because Ferrari is a subclass, but it fails at runtime as OOP21 states. Execution stops at the cast with ClassCastException, before a.drive() or d.brake() can print any of their messages.
Evidence in the complete study note
Upcasting a subclass reference to a superclass is implicit and does not change the object. A downcast may pass compile-time type checks yet fail at runtime. Car a=new Car(); Ferrari f=(Ferrari)a; throws ClassCastException before subsequent drive() or brake() calls. It does not turn a plain Car into a Ferrari.OOP21
Choice by choice
A · incorrect — The failing cast occurs before either drive or brake, so neither listed message prints.
B · incorrect — No Ferrari object exists here; the cast throws before any dynamic drive or brake call.
C · incorrect — The program never reaches any of the three proposed messages because the cast fails first.
D · incorrect — The related-class cast can pass compile-time checking; the actual object type causes a runtime failure.
E · correct — Casting a plain Car object to Ferrari throws ClassCastException at runtime before any method output.
Question 164
Which Java local declarations are valid when considered independently? Assume no type named x exists and the references are not read before assignment. Select all that apply.
A. None of the choices is correct
B. int [ ] x, y = new int[5];
C. int x[ ] = new x[5];
D. int [ ] x = new int[4];
E. int x = {5, 4, 9};
Hint / Module Reference (Where to Read)
Check declared dimensions, initializer shape, fixed length and zero-based index bounds.
Correct answers (select all): B, D — int [ ] x, y = new int[5];; int [ ] x = new int[4];
In B, int[] is the shared type of both x and y. Only y receives a new five-element array, which is a legal declaration as long as unassigned x is not read. D separately creates a four-element int array. C cannot use the variable-like name x as an allocation type under the stated scope, and E declares a scalar int with an array initializer. Thus B and D are valid.
Evidence in the complete study note
int[] a=new int[5]; and int a[]={1,2,3}; are valid. int[] a={}; creates a zero-length array; explicit new is unnecessary in a declaration initializer. int a[],b; makes only a an array; int[] c,d; makes both arrays. Array objects have fixed length after creation, although the reference may be reassigned.OOP26
Locals occur in methods, constructors or blocks; they must be definitely assigned before use and cannot have public/private/protected modifiers.OOP05
Choice by choice
A · incorrect — B and D are valid declarations, so none is incorrect.
B · correct — Both references have type int[]; initializing only y is legal.
C · incorrect — No type x exists, so new x[5] is not a valid allocation here.
D · correct — This is a valid int[] declaration and allocation.
E · incorrect — A scalar int cannot be initialized with a multi-element brace array initializer.
Question 165
What is a Java static initializer block?
A. A block that initializes class-level state during class initialization, before that class’s first relevant active use, including its main invocation
B. None of the choices is correct.
C. There is no such block.
D. It is used to create synchronized code.
Hint / Module Reference (Where to Read)
Decide whether a member belongs to a class or an object, then check initialization and final restrictions.
Correct answer: A — A block that initializes class-level state during class initialization, before that class’s first relevant active use, including its main invocation
A static initializer executes during class initialization and can initialize static state. It runs before the class’s first relevant active use, including invoking its main method, rather than simply whenever a class file is loaded. It is a real Java construct, so none and the denial option are false. Synchronization is a different concern and does not define a static initializer’s purpose.
Evidence in the complete study note
A static initializer runs during class initialization, before the class’s first relevant active use, not simply whenever a file is loaded.OOP07
Choice by choice
A · correct — This states the class-state initialization purpose and correct initialization timing.
B · incorrect — A correctly describes a real construct, so none is incorrect.
C · incorrect — Static initializer blocks exist in Java.
D · incorrect — Creating synchronized code is not the defining role of a static initializer.
Question 166
What is the output of the below given Java code? Assume every necessary components of the program are included.
int i;
for (i = 0; i < 5; i++) {
if (i % 2 == 0)
System.out.print ( i + " ");
System.out.print ( i + 1);
}
A. 0 12 34 5
B. None of the choices is correct
C. 0 2 4 6
D. 0 122 344 5
Hint / Module Reference (Where to Read)
Trace condition tests, control transfers and printing as separate steps.
Only the first print is controlled by if. At i=0,2,4 it prints the even value followed by a space; every iteration then prints i+1 without a separator. The contributions are "0 1", "2", "2 3", "4", "4 5". Joining them produces "0 122 344 5", exactly as OOP25 records.
Evidence in the complete study note
Count executions independently from printing. For i=0..4, if(i%2==0) print(i+" "); followed unconditionally by print(i+1); produces "0 122 344 5".OOP25
A print call emits its value without inserting a separator or ending the line. A println call emits its value followed by a line terminator. Spaces must come from the supplied text or explicit output operations; adjacent calls do not automatically separate their values.OOP-S02
Choice by choice
A · incorrect — This omits digits from the unconditional i+1 prints on odd and even iterations.
B · incorrect — D supplies the exact concatenated output, so none of the choices is false.
C · incorrect — The unconditional print runs five times; the output is not just an even-number sequence.
D · correct — Joining every conditional and unconditional print yields the exact string 0 122 344 5.
Question 167
______ is a way of saying: This object is a type of that object.
A. IS-A
B. HAS-A
C. ARE-A
D. HAD-A
Hint / Module Reference (Where to Read)
Identify the subtype or ownership relationship and distinguish class inheritance from interface contracts.
IS-A describes type membership: an object belongs to a type or one of its subtypes.
Evidence in the complete study note
Use inheritance when a subtype can satisfy the parent’s contract: Dog is an Animal. For shared Pet.name and speak(), put common state/contract in Pet, specialized fetch() in Dog, and appropriate speak() implementations in Dog and Cat. Composition represents has-a, such as Car containing Engine. Reuse alone does not justify an invalid is-a relationship.OOP13
Choice by choice
A · correct — Matches the named IS-A relationship
B · incorrect — HAS-A would describe composition/containment rather than type membership
C · incorrect — Not the named relationship
D · incorrect — Not the named relationship
Question 168
Which Java member access modifier permits subclasses in other packages to access inherited members through their own inherited context, while excluding unrelated clients in those other packages? Same-package access is allowed.
A. protected
B. private
C. default
D. public
Hint / Module Reference (Where to Read)
Locate the accessing code, declaring type, package and receiver before applying visibility rules.
protected includes same-package access and also permits qualified subclass access across packages. That matches the revised boundary, which excludes unrelated clients in other packages while allowing same-package clients. private does not generally expose inherited members to separately declared subclasses, package access does not reach other packages, and public allows unrelated external clients. The question no longer demands an impossible universal subclasses-only rule.
Evidence in the complete study note
For ordinary members: private restricts access to the declaring class/nest; no modifier grants package access; protected grants same-package access plus qualified subclass access; public is widest, provided the declaring type itself is accessible.OOP08
Across packages, a subclass accessing a protected instance member must do so through its own inherited context or an appropriate subclass-typed receiver, not any arbitrary superclass object. protected therefore does not mean “subclasses only”: unrelated classes in the same package also have access.OOP08
Choice by choice
A · correct — protected provides same-package access plus the specified qualified cross-package subclass access.
B · incorrect — private does not grant the requested general cross-package subclass access.
C · incorrect — Package/default access does not extend to subclasses in another package.
D · incorrect — public also permits unrelated accessible external clients, violating the boundary.
Question 169
Which one of the following is the correct way of creating a String object?
A. String m = 'Computer Science';
B. String m = new String('Technology');
C. String m = 'H', 'e', 'l', 'l', 'o';
D. String m = new String("Exit Exam");
Hint / Module Reference (Where to Read)
Read the cited conceptual rules, state the model, and apply them before comparing the alternatives.
Correct answer: D — String m = new String("Exit Exam");
A String literal uses double quotes, while a character literal supplies one char in single quotes. D passes a valid String literal to the String constructor and assigns the resulting object reference. A and B instead use invalid multi-character character literals. C is not one valid String initializer: separate comma-delimited character literals do not form a String expression or a character-array constructor argument.
Evidence in the complete study note
A double-quoted string literal denotes a String object. new String(existingString) creates a String with the same text; new String(charArray) copies the array’s characters into an immutable String. A single-quoted literal denotes one char, so several characters enclosed together in single quotes cannot supply a String.OOP-S04
Student s; declares a reference variable; it creates no Student object. Student s=new Student(); allocates and initializes an instance.OOP03
Choice by choice
A · incorrect — The multi-character text in single quotes is not a valid Java character literal or String expression.
B · incorrect — new String does not make its invalid single-quoted multi-character argument legal.
C · incorrect — The comma-separated character literals do not form one String initializer or a supplied char-array value.
D · correct — A double-quoted String argument matches the String constructor and initializes the String reference.
Question 170
Which one of the following is false about String in Java?
A. In Java a string is treated as object
B. We can create a String object using String literal
C. We can create a String object using array of characters
D. Content of a string can be changed once the string is created
Hint / Module Reference (Where to Read)
Read the cited conceptual rules, state the model, and apply them before comparing the alternatives.
Correct answer: D — A created String’s content cannot be changed.
OOP22 explicitly states that Java String objects are immutable. A variable can later reference a new String result, but the existing object’s content does not change. D therefore contradicts the rule. The other choices describe String objects or ways of supplying initial content, which do not assert mutation of an already-created String.
Evidence in the complete study note
A double-quoted string literal denotes a String object. new String(existingString) creates a String with the same text; new String(charArray) copies the array’s characters into an immutable String. A single-quoted literal denotes one char, so several characters enclosed together in single quotes cannot supply a String.OOP-S04
Java String objects are immutable. text += " World" assigns a reference to a new concatenated result and can print Hello World without mutating the original String object. final class String prevents subclassing; final alone does not make arbitrary objects immutable.OOP22
Choice by choice
A · incorrect — String is an object type in the note; this is not the false mutability claim.
B · incorrect — A String literal supplies String content; it does not imply the resulting object can later mutate.
C · incorrect — Supplying initial character content creates a String; it does not change an existing String’s immutable content.
D · correct — This is false: Java String objects are immutable after creation, even if a variable is rebound.
Question 171
Which concept refers to extending specialized classes from generalized classes in object-
oriented programming?
A. Inheritance
B. Overriding
C. Overloading
D. Data field Encapsulation
Hint / Module Reference (Where to Read)
Identify the subtype or ownership relationship and distinguish class inheritance from interface contracts.
A subclass is a specialized version of a superclass, and inheritance creates that relation.
Evidence in the complete study note
class Dog extends Animal declares a subclass/derived/child of a superclass/base/parent.OOP13
Use inheritance when a subtype can satisfy the parent’s contract: Dog is an Animal.OOP13
Encapsulation groups related state and operations and controls access. Information hiding keeps implementation decisions behind a stable interface. Abstraction presents the essential operations while omitting details irrelevant to the caller.OOP02
Choice by choice
A · correct — Matches specialized-from-general hierarchy
B · incorrect — Replaces an inherited method, not the class relationship
C · incorrect — Adds same-name methods with changed parameters
D · incorrect — Groups/controls data, not class specialization
Question 172
One of the following is NOT TRUE about inheritance:
A. The subclass can add variables, but cannot redefine them
B. The derived class (subclass) is allowed to add methods or redefine them
C. A feature that allows us to derive a class from another class
D. Allows programmers to customize without actually modifying the original class (superclass)
Hint / Module Reference (Where to Read)
Identify the subtype or ownership relationship and distinguish class inheritance from interface contracts.
Correct answer: A — The subclass can add variables, but cannot redefine them
B declares its own i, hiding A.i, and adds its own methods. Thus subclass fields can be declared with an ancestor's name; A's cannot claim is false in the intended hiding sense.
Evidence in the complete study note
class Dog extends Animal declares a subclass/derived/child of a superclass/base/parent. A class extends one direct class and can implement multiple interfaces. Single, multilevel and hierarchical inheritance mean one parent, a chain, and several children of one parent.OOP13
Fields are hidden rather than dynamically overridden, and same-signature static methods hide rather than override.OOP16
Choice by choice
A · correct — Contradicted by B's int i hiding A.i
B · incorrect — Subclass can add methods and override inherited ones
C · incorrect — Matches the inheritance definition
D · incorrect — Subclass extension permits customization without changing the parent
Question 173
Which OOP concept allows objects of different classes to be treated as objects of a common superclass?
A. Polymorphism
B. Inheritance
C. Abstraction
D. Encapsulation
Hint / Module Reference (Where to Read)
Check what compiles from the declared type, then select behavior from the actual runtime class.
A parent-class reference referring to child objects is a common use of polymorphism. Inheritance establishes the relation, while polymorphism is the treatment through the common type.
Evidence in the complete study note
To solve dispatch questions: check the declaration and visibility, determine the compile-time signature, then identify the object’s runtime class and its most specific override. An array Animal[]{new Dog(),new Cat()} can call speak() on each using one loop. New subclasses can supply behavior without rewriting this generic loop, which is the practical meaning of extensibility.OOP15
Inheritance forms a subtype relationship and may reuse implementation. Polymorphism lets code using a common type invoke behavior appropriate to different concrete objects.OOP02
Choice by choice
A · correct — Names the common-superclass many-forms treatment
B · incorrect — Prerequisite relationship but not the treatment asked for
C · incorrect — Hides background details
D · incorrect — Groups data and methods
Question 174
Which purposes apply to a Java interface viewed as a capability contract? “Blueprint” means an operation contract for implementing classes, and “multiple inheritance” means multiple type inheritance rather than multiple superclass state inheritance. Select all that apply.
A. To define a blueprint for a class
B. To allow multiple inheritance
C. To create objects directly
D. To hide internal implementation details
Alternative version 1
Which purposes apply to Java interfaces as capability contracts, rather than complete per-instance state definitions? “Blueprint” means an operation contract, and “multiple inheritance” means multiple type inheritance. Select all that apply.
A. To create multiple constructors for a class
B. To define the state and behavior of an object
C. To define a blueprint of a class
D. To achieve multiple inheritance
Hint / Module Reference (Where to Read)
Identify the interface contract, effective modifiers and permitted implementation forms.
Correct answers (select all): A, B, D — To define a blueprint for a class; To allow multiple inheritance; To hide internal implementation details
An interface specifies an operation contract that implementing classes satisfy, so the qualified blueprint description is valid. A class can implement multiple interfaces, gaining multiple type inheritance. Clients can use the contract without depending on a particular implementation’s internals, supporting abstraction. Interfaces are not directly instantiated, so creating objects directly is not their purpose. The multi-select form therefore accepts A, B and D.
Evidence in the complete study note
interface Payable{double getPaymentAmount();} declares an abstract public operation. class Invoice implements Payable must provide public double getPaymentAmount(), perhaps returning getQuantity()*getPricePerItem().OOP19
Information hiding keeps implementation decisions behind a stable interface. Abstraction presents the essential operations while omitting details irrelevant to the caller.OOP02
Use an abstract class for shared state, construction and common implementation; use an interface for a capability across unrelated classes and multiple type inheritance.OOP20
Choice by choice
A · correct — An operation blueprint is the contract that implementations must satisfy.
B · correct — Implementing multiple interfaces supports multiple type inheritance.
C · incorrect — An interface cannot be instantiated directly.
D · correct — The public contract lets callers use capabilities without depending on internal implementation details.
Alternative version 1
Correct answers (select all): C, D — Interfaces define capability contracts and support multiple type inheritance.
This variant places the contract/blueprint purpose at C and multiple type inheritance at D. Both are valid: implementing objects satisfy the public operation contract, and a class may implement several interfaces. Interfaces have no constructors or per-instance fields, so they do not create class constructors or define an object’s complete state and implementation. Its selected labels therefore differ from the primary option set.
interface Payable{double getPaymentAmount();} declares an abstract public operation. class Invoice implements Payable must provide public double getPaymentAmount(), perhaps returning getQuantity()*getPricePerItem(). A class can extend a superclass and implement zero or more interfaces. An interface can extend several interfaces. No interface instance fields or constructors exist; fields are implicitly public static final.OOP19
Use an abstract class for shared state, construction and common implementation; use an interface for a capability across unrelated classes and multiple type inheritance.OOP20
A · incorrect — Interfaces have no constructors, so creating multiple constructors is not their purpose.
B · incorrect — An interface specifies capabilities rather than complete per-instance state and implementation.
C · correct — The defined blueprint is an operation contract for implementing classes.
D · correct — Several interface types provide multiple type inheritance.
Question 175
Which OOP relationship is formed when a Java class implements several interface contracts? Choose the relationship concept, rather than the language construct declaring each contract.
A. Polymorphism
B. Encapsulation
C. Inheritance
D. Interface
Hint / Module Reference (Where to Read)
Identify the interface contract, effective modifiers and permitted implementation forms.
Correct answer: C — Inheritance, specifically multiple interface/type inheritance.
Implementing several interfaces gives the class several interface types and forms multiple type inheritance. Inheritance is therefore the relationship concept requested. Interface names a construct used to declare a contract, rather than the relationship itself. Polymorphism can use the resulting common types to select behavior, while encapsulation groups state and controls access. Neither names the requested multiple-type relationship.
Evidence in the complete study note
A class can extend a superclass and implement zero or more interfaces. An interface can extend several interfaces.OOP19
Use an abstract class for shared state, construction and common implementation; use an interface for a capability across unrelated classes and multiple type inheritance.OOP20
Encapsulation groups related state and operations and controls access. Information hiding keeps implementation decisions behind a stable interface. Abstraction presents the essential operations while omitting details irrelevant to the caller.OOP02
Choice by choice
A · incorrect — Polymorphism uses common types for appropriate behavior; the question asks for the type relationship itself.
B · incorrect — Encapsulation groups state and controls access rather than forming the specified type relationship.
C · correct — The class acquires multiple interface types, which is multiple type inheritance.
D · incorrect — Interface is the construct defining a contract, not the requested relationship concept.
Question 176
Which of the following concepts in OOP allows a class to inherit attributes and methods from
another class?
A. Inheritance
B. Abstraction
C. Encapsulation
D. Polymorphism
Hint / Module Reference (Where to Read)
Identify the subtype or ownership relationship and distinguish class inheritance from interface contracts.
Acquiring another class's methods and fields defines inheritance.
Evidence in the complete study note
class Dog extends Animal declares a subclass/derived/child of a superclass/base/parent.OOP13
Encapsulation groups related state and operations and controls access. Information hiding keeps implementation decisions behind a stable interface. Abstraction presents the essential operations while omitting details irrelevant to the caller.OOP02
Inheritance forms a subtype relationship and may reuse implementation. Polymorphism lets code using a common type invoke behavior appropriate to different concrete objects.OOP02
Choice by choice
A · correct — Matches acquisition from another class
B · incorrect — Essential information exposure
C · incorrect — Wrapping data/methods together
D · incorrect — Many forms of behavior, rather than the transfer relation
Question 177
According to the introductory module’s language-characteristics list, which description contradicts its characterization of Java?
A. Java is Object-Oriented
B. Java is Platform Independent
C. Java is difficult to learn
D. Java is architecture neutral
Hint / Module Reference (Where to Read)
Read the cited conceptual rules, state the model, and apply them before comparing the alternatives.
Java is commonly characterized as object oriented, platform independent and simple. Architecture-neutral bytecode is executed by a compatible platform-specific JVM. Difficult to learn conflicts with the module’s intended simple characterization, making C the requested mismatch. This is a question about the module’s description, not an objective claim that every learner finds Java easy or that every program runs unchanged in every environment.
Evidence in the complete study note
Java is commonly characterized as object oriented, platform independent and simple. Its architecture-neutral bytecode is executed by a compatible platform-specific JVM. “Simple” is a teaching characterization relative to language design, not a promise that every learner finds every Java program easy.OOP-S06
Java source normally compiles to JVM bytecode, and a compatible JVM plus libraries supports portability across systems.OOP39
Choice by choice
A · incorrect — Object orientation is part of the stated introductory characterization.
B · incorrect — Platform independence is part of the stated characterization, subject to a compatible JVM and environment.
C · correct — Difficult to learn conflicts with the module’s intended simple characterization.
D · incorrect — Architecture-neutral bytecode supports this characteristic within the specified compatible-runtime model.
Question 178
Which statement about Java interfaces is false? In A, “interface instance” means an object made by directly instantiating the interface itself, without an implementation. C means interfaces may include abstract methods.
A. An interface can be instantiated directly without supplying an implementation, and its abstract methods can then be invoked
B. Like a class, an interface is a reference data type
C. Interface includes abstract methods
D. One class can implement multiple interfaces
Hint / Module Reference (Where to Read)
Identify the interface contract, effective modifiers and permitted implementation forms.
Correct answer: A — An interface can be instantiated directly without supplying an implementation, and its abstract methods can then be invoked
An interface cannot be instantiated directly without an implementation. An interface reference can instead hold an implementing object and invoke its contract methods. Interfaces are reference types, can declare abstract operations, and can be implemented alongside other interfaces by one class. Clarifying A’s construction meaning isolates the false statement without incorrectly rejecting ordinary calls through interface-typed references.
Evidence in the complete study note
interface Payable{double getPaymentAmount();} declares an abstract public operation. class Invoice implements Payable must provide public double getPaymentAmount(), perhaps returning getQuantity()*getPricePerItem(). A class can extend a superclass and implement zero or more interfaces. An interface can extend several interfaces.OOP19
Interfaces cannot be instantiated directly, but references may hold implementing objects, anonymous implementations or suitable functional-interface lambdas.OOP19
Choice by choice
A · correct — Direct interface instantiation without an implementation is forbidden, so A is false.
B · incorrect — An interface is a reference type usable for implementation references, so B is true.
C · incorrect — An interface may declare abstract methods, so C is true.
D · incorrect — One class can implement multiple interfaces, so D is true.
Question 179
The following UML design shows Student class. Assume that the attributes have declared as private and the methods as public. The get methods
return the value of the attributes and the calculateAge() returns the Student age. Which of the following would not raise an error when you run this
program?
A. Student st1 = new Student ("John","CS","0913222222","25");
B. Student st1 = new Student ("John","SE","0913222222",20);
C. st1 Student = new Student ("John","CS","02085332455", 23);
D. Student st1 = new Student ("John","IT","2000");
Hint / Module Reference (Where to Read)
Read the notation and distinguish a class description from a particular instance.
Correct answer: B — Student st1 = new Student ("John","SE","0913222222",20);
The UML specifies Student parameters of types String, String, String and int, in that order. B supplies exactly those four argument types. Distinct String and int primitives/reference types rule out the quoted age in A.
Evidence in the complete study note
A UML class box normally contains name, attributes and operations. Visibility uses + public, - private and # protected. A field can be written name:String and an operation getName():String. A constructor Student(String,String,String,int) requires three strings and an integer, so an age argument "25" has the wrong type.OOP04
Student s; declares a reference variable; it creates no Student object. Student s=new Student(); allocates and initializes an instance.OOP03
Choice by choice
A · incorrect — Fourth argument is String 25 rather than int
B · correct — Three String arguments and an int age match the UML
C · incorrect — Reverses the required type/name declaration order
D · incorrect — Only three String arguments; missing the required int age
Question 180
What we use to pass the data between activities in Android?
A. Broadcast receiver
B. PostgreSQL Database
C. Intent
D. Content Provider
Hint / Module Reference (Where to Read)
Distinguish an interactive entry point, a requested action and attached data.
OOP35 says an Intent describes an action or target and extras carry values between activities. Its putExtra("id",17) example supplies a concrete transfer. A broadcast receiver handles broadcasts and a content provider shares structured data; neither is the ordinary activity-start-with-parameters mechanism. A PostgreSQL database is not the inter-activity carrier described here.
Evidence in the complete study note
An Intent describes a requested action or explicit target; extras carry values between activities. For example, putExtra("id",17) attaches an ID for the destination to read. A content provider shares structured data, while a broadcast receiver handles broadcast messages; neither is the ordinary mechanism for starting an activity with parameters.OOP35
Choice by choice
A · incorrect — A broadcast receiver handles broadcasts rather than serving as the ordinary activity-to-activity parameter carrier.
B · incorrect — A database can store data but is not the Intent-and-extras transfer mechanism specified in OOP35.
C · correct — An Intent selects the action/target and carries values between activities using extras.
D · incorrect — A content provider shares structured data, rather than being the ordinary parameterized activity-start mechanism.
Question 181
What Is Manifest.xml in android?
A. It has the information about activities in an application
B. It has all the information about an application
C. Itis an executable file of the application
D. It has information about layout in an application
Hint / Module Reference (Where to Read)
Separate application declarations, view containers and installation packaging.
Correct answer: A — The manifest declares essential metadata, including application activities.
OOP36 says AndroidManifest.xml declares essential metadata such as components, permissions and intent filters. Activities are components, so A states a supported part of its contents. B overstates the scope by claiming all application information, which the note explicitly rejects. The image’s reordered highlighted all-information choice cannot override that rule or the main option labels.
Evidence in the complete study note
AndroidManifest.xml declares essential app metadata such as components, permissions and intent filters. It is not executable code and does not contain all source or layout details.OOP36
A manifest describes the package, while layout resources describe views.OOP36
Choice by choice
A · correct — Activities are application components whose declarations form part of the manifest’s essential metadata.
B · incorrect — All information is too broad; the manifest does not contain all source code or layout details.
C · incorrect — The manifest declares metadata and is explicitly not executable application code.
D · incorrect — Layout resources describe views; the manifest does not contain the layout details asserted here.
Question 182
Assume you have an interface called Payable as follows:
public interface Payable {
double getPaymentAmount();
}
If you have another class Invoice that implements this interface and getQuantity() and getPricePerItem() methods that return quantity and price per item, which options correctly implement the Payable contract? Treat each option as an independent class skeleton with accessible getQuantity() and getPricePerItem() methods supplied and compatible with multiplication returning double. An abstract class may supply a concrete implementation. Select all that apply.
A. public abstract class Invoice implements Payable {
public double getPaymentAmount() {
return getQuantity() * getPricePerItem();
}
}
B. public class Invoice implements Payable {
public double getPaymentAmount() {
return getQuantity() * getPricePerItem();
}
}
C. public class Invoice implements Payable {
public getPaymentAmount() {
return getQuantity() * getPricePerItem();
}
}
D. public class Invoice extends Payable {
public double getPaymentAmount() {
return getQuantity() * getPricePerItem();
}
}
Hint / Module Reference (Where to Read)
Identify the interface contract, effective modifiers and permitted implementation forms.
Correct answers (select all): A, B — public abstract class Invoice implements Payable {
public double getPaymentAmount() {
return getQuantity() * getPricePerItem();
}
}; public class Invoice implements Payable {
public double getPaymentAmount() {
return getQuantity() * getPricePerItem();
}
}
Both A and B provide public double getPaymentAmount() with the required quantity-times-unit-price result. Declaring A abstract does not prevent it from implementing the interface method concretely; it only prevents direct construction of Invoice itself. The assumed helper methods make both skeletons complete for this comparison. C omits the return type, while D incorrectly uses extends for the interface relationship. Thus A and B satisfy the contract.
Evidence in the complete study note
interface Payable{double getPaymentAmount();} declares an abstract public operation. class Invoice implements Payable must provide public double getPaymentAmount(), perhaps returning getQuantity()*getPricePerItem(). A class can extend a superclass and implement zero or more interfaces.OOP19
An abstract class cannot be directly instantiated but can define fields, constructors, abstract methods and concrete methods.OOP18
A method has modifiers, return type, name, parameter list and body: public int getAge(){return age;}.OOP11
Choice by choice
A · correct — An abstract class may still provide this concrete public double implementation.
B · correct — The concrete class provides the required public double implementation.
C · incorrect — The method lacks a return type and is not a valid implementation declaration.
D · incorrect — A class implements Payable; it cannot extend that interface as a superclass.
Question 183
Which statement is wrong about a Java try-catch construct? Assume any exception considered has a matching catch, and no earlier control transfer prevents reaching it.
A. The execution control is moved to catch block after exception occur in try block
B. When exception occurs, the execution of try block is interrupted
C. The catch block is executed once regardless of exceptions in try block
D. The catch block is used to handle exceptions that occur in try block
Hint / Module Reference (Where to Read)
Check the thrown type and catch order before tracing propagation or handler output.
Correct answer: C — The catch block is executed once regardless of exceptions in try block
If the try block completes normally, its catch does not execute. If an exception occurs, normal execution of the try is interrupted and the matching handler runs. Thus the claim that catch runs once regardless of exceptions is false. Catch is conditional handling, whereas finally normally provides cleanup after the try and any selected handler. The matching-handler assumption makes the other transfer statements precise.
Evidence in the complete study note
try encloses guarded operations; a matching catch handles the thrown type or a subtype. Execution skips the remainder of the try when a throw occurs.OOP30
finally normally executes after try and any selected catch, including when leaving by return or propagating an exception.OOP31
Choice by choice
A · incorrect — With the stated matching-handler assumption, an exception transfers control to that catch.
B · incorrect — The exception interrupts normal execution and skips the remaining try body.
C · correct — This is false: normal completion of try does not execute catch.
D · incorrect — The matching catch handles the exception thrown during try.
Question 184
An accessible abstract Class_A declares public abstract String welcome(); and has an accessible no-argument constructor. Which independent concrete definition of Class_B compiles? Each public class is in its own correctly named source file. These options restore the complete A–D code blocks from the source images.
A. public class Class_B extends Class_A {
public String whatObjectAmI() { return "I am a class B object"; }
}
B. public class Class_B extends Class_A {
public int welcome() { int x = 10; return x; }
}
C. public class Class_B extends Class_A {
public String whatObjectAmI() { return "I am a class D object"; }
public String welcome() { return "I am a class C object"; }
public int welcome(int y) { int x = 2 * y; return x; }
}
D. public class Class_B extends Class_A {
public void welcome(String str) { }
}
Hint / Module Reference (Where to Read)
Check whether a class is concrete and whether every inherited abstract contract has an implementation.
Correct answer: C — public class Class_B extends Class_A {
public String whatObjectAmI() { return "I am a class D object"; }
public String welcome() { return "I am a class C object"; }
public int welcome(int y) { int x = 2 * y; return x; }
}
The required inherited method has no parameters and returns String. C supplies that exact public implementation and may additionally overload welcome with an int parameter. A has no welcome implementation, B returns an incompatible int, and D supplies only a different-parameter overload. Those concrete subclasses leave the abstract contract unsatisfied or violate return compatibility.
Evidence in the complete study note
A concrete subclass must provide or inherit implementations of all required abstract methods; otherwise it must itself be abstract. If parent declares abstract String welcome(), a String welcome() implementation is required; int welcome() is incompatible, and welcome(int) merely adds an overload. A valid class can contain both the required implementation and an unrelated overload.OOP18
Overloaded methods share a name but have different parameter types, counts or type order. Return type alone is insufficient in Java and C++.OOP12
Choice by choice
A · incorrect — whatObjectAmI() does not implement the required welcome() contract.
B · incorrect — int is incompatible with the required String return for the same signature.
C · correct — The exact public String welcome() implementation is present; welcome(int) is an allowed overload.
D · incorrect — welcome(String) is an overload and does not implement no-argument welcome().
Question 185
For traditional Android View-based layout containers, which class is their common container superclass?
A. android.view.Layout
B. android.view.RelativeLayout
C. android.view.ViewGroup
D. android.view.Widget
Hint / Module Reference (Where to Read)
Separate application declarations, view containers and installation packaging.
Correct answer: C — android.view.ViewGroup, for traditional view-based layout containers.
Traditional Android View-based layout containers, including LinearLayout and RelativeLayout, derive from android.view.ViewGroup. ViewGroup contains child views, matching the container role. RelativeLayout is one particular container rather than the common superclass, and the other supplied names do not identify that superclass. The View-system scope avoids extending this claim to every modern Android layout abstraction.
Evidence in the complete study note
Traditional view-based layout containers such as LinearLayout and RelativeLayout derive from android.view.ViewGroup, which contains child views.OOP36
Choice by choice
A · incorrect — This is not the named View-system container superclass.
B · incorrect — RelativeLayout is a particular layout container, not the common superclass of the layout containers.
C · correct — android.view.ViewGroup is the child-view container superclass for this traditional View-system scope.
D · incorrect — This does not name the View-system container superclass.
Question 186
Which statements about a Java abstract class are true? Select all that apply.
A. Cannot be instantiated directly
B. Must contain at least one abstract method
C. Can contain both abstract and non-abstract methods
D. Cannot be inherited
Hint / Module Reference (Where to Read)
Check whether a class is concrete and whether every inherited abstract contract has an implementation.
Correct answers (select all): A, C — Cannot be instantiated directly; Can contain both abstract and non-abstract methods
An abstract class cannot be constructed directly, but it can contain both abstract and concrete methods. It can also be abstract without declaring any abstract method, so B is false. Abstract classes may be inherited; a concrete subclass must fulfill outstanding abstract method contracts. Cleaning the source marking noise and replacing the vague encapsulation slogan leaves two precise true properties at A and C.
Evidence in the complete study note
An abstract class cannot be directly instantiated but can define fields, constructors, abstract methods and concrete methods. It need not contain an abstract method. An abstract method has no body; abstract and final conflict because an operation cannot require overriding while forbidding it.OOP18
A concrete subclass must provide or inherit implementations of all required abstract methods; otherwise it must itself be abstract.OOP18
Choice by choice
A · correct — Direct instantiation of an abstract class is prohibited.
B · incorrect — An abstract class need not declare any abstract method.
C · correct — Abstract and concrete methods may coexist in an abstract class.
D · incorrect — Abstract classes can be inherited; concrete subclasses must fulfill their contracts.
Question 187
What is an activity in android?
A. A single screen in an application with supporting java code
B. android class used to configure the android application
C. Itis an intent
D. android package file holding all the packages used
Hint / Module Reference (Where to Read)
Distinguish an interactive entry point, a requested action and attached data.
Correct answer: A — An Activity is a user-interaction entry component, often a screen.
An Android Activity is a component providing an entry point for user interaction, often corresponding to a screen. A is the introductory screen-and-code description that best matches this definition, though a one-to-one screen mapping is not universal. Configuration, Intents and package archives are separate concepts.
Evidence in the complete study note
An Android Activity is a component providing an entry point for user interaction, often corresponding to a screen. An Intent describes a requested action or explicit target; extras carry values between activities. For example, putExtra("id",17) attaches an ID for the destination to read. A content provider shares structured data, while a broadcast receiver handles broadcast messages; neither is the ordinary mechanism for starting an activity with parameters.OOP35
An .apk is an Android package archive used for installation and runtime contents.OOP36
Choice by choice
A · correct — The screen with supporting code is the introductory description closest to the note’s interaction-entry component.
B · incorrect — Configuring the application describes a different responsibility than providing the Activity’s user-interaction entry point.
C · incorrect — An Intent describes a requested action or target; it is not itself an Activity.
D · incorrect — An Android package archive is installation/runtime packaging, rather than a user-interaction component.
Question 188
Assume that there is a Pet family from which Pets like Dog and Cat share behavior from.Every Pet family has a name. However, the pet families have
some specific behaviors that are exhibited by only particular Pets. For instance, only Dogs can fetch something while both cats and dogs can speak.
Which of the following object oriented designprinciple would be suitable for this case?
A. Polymorphism
B. Encapsulation
C. Inheritance
D. _ Information hiding
Hint / Module Reference (Where to Read)
Identify the subtype or ownership relationship and distinguish class inheritance from interface contracts.
A shared Pet superclass can hold name and common speak behavior; Dog and Cat specialize it, with fetch only in Dog. This directly uses inheritance. Overriding speak could also yield polymorphism but is not required by the stem.
Evidence in the complete study note
Use inheritance when a subtype can satisfy the parent’s contract: Dog is an Animal. For shared Pet.name and speak(), put common state/contract in Pet, specialized fetch() in Dog, and appropriate speak() implementations in Dog and Cat. Composition represents has-a, such as Car containing Engine. Reuse alone does not justify an invalid is-a relationship.OOP13
Encapsulation groups related state and operations and controls access. Information hiding keeps implementation decisions behind a stable interface. Abstraction presents the essential operations while omitting details irrelevant to the caller.OOP02
Choice by choice
A · incorrect — Would apply if speak were dispatched to different overrides, which is not stated
B · incorrect — Groups data/methods but does not establish shared family specialization
C · correct — Models shared parent features plus subclass-specific behavior
D · incorrect — Hides details rather than defining the family hierarchy
Question 189
Which method has the same name as that of its class?
A. constructor
B. class
C. delete
D. finalize
Hint / Module Reference (Where to Read)
Check the class name, return-type absence and the constructors actually declared.
Correct answer: D — Android Package Kit is the common exam expansion.
Android Package Kit is a common exam expansion of APK; the artifact is an Android package archive. Thus D is appropriate under this expansion convention. None of the Phone, Page or Platform alternatives describes this package archive.
Evidence in the complete study note
An .apk is an Android package archive used for installation and runtime contents. “Android Package Kit” is a common exam expansion; Android’s documentation calls it an Android package.OOP36
Choice by choice
A · incorrect — Phone Kit does not match the common expansion or the package-archive meaning given in OOP36.
B · incorrect — Page Kit does not describe the installation package archive identified here.
C · incorrect — Platform Kit is not the bank expansion explicitly documented in OOP36.
D · correct — Package Kit is the common exam expansion expressly stated, with Android package as the official artifact terminology.
Question 191
Which option specifically describes encapsulation’s bundling of related state and operations, rather than focusing on hiding implementation decisions behind an interface?
A. Combining data and methods into a single entity.
B. Hiding implementation details and providing a public interface.
C. Creating multiple instances of a class.
D. Inheriting properties and behavior from a base class.
Hint / Module Reference (Where to Read)
Identify whether the emphasis is grouping state, hiding implementation, exposing essentials or varying behavior.
Correct answer: A — Combining data and methods into a single entity.
Encapsulation groups related state and operations and controls access to them. A directly describes the grouping or bundling aspect requested here. B describes information hiding and can accompany encapsulation, but the stem deliberately asks for the grouping emphasis. Creating instances is object construction, while inheriting base properties is inheritance. This specific emphasis makes A the unique answer without denying the overlap of the broader principles.
Evidence in the complete study note
Encapsulation groups related state and operations and controls access. Information hiding keeps implementation decisions behind a stable interface. Abstraction presents the essential operations while omitting details irrelevant to the caller. These ideas overlap: a private balance plus deposit(amount) can demonstrate all three, depending on what the question emphasizes.OOP02
Use inheritance when a subtype can satisfy the parent’s contract: Dog is an Animal.OOP13
Student s; declares a reference variable; it creates no Student object. Student s=new Student(); allocates and initializes an instance.OOP03
Choice by choice
A · correct — Combining data and methods directly describes the requested bundling aspect.
B · incorrect — This emphasizes information hiding rather than the specific grouping mechanism asked for.
C · incorrect — Creating instances is object construction rather than encapsulation’s grouping.
D · incorrect — Reusing base-class properties describes inheritance.
Question 192
What is inheritance in Java?
A. The process of creating objects from classes.
B. The ability of a class to inherit properties and behavior from another class.
C. Creating multiple instances of a class.
D. The ability to access variables and methods of a different class.
Hint / Module Reference (Where to Read)
Identify the subtype or ownership relationship and distinguish class inheritance from interface contracts.
Correct answer: B — The ability of a class to inherit properties and behavior from another class.
Inheritance means acquiring another class's fields and methods, matching the properties-and-behavior description.
Evidence in the complete study note
class Dog extends Animal declares a subclass/derived/child of a superclass/base/parent.OOP13
Student s; declares a reference variable; it creates no Student object. Student s=new Student(); allocates and initializes an instance. Member access uses s.name or s.study(), subject to visibility.OOP03
Choice by choice
A · incorrect — Instantiation rather than inheritance
B · correct — Matches acquisition from a parent class
C · incorrect — Instance creation rather than inheritance
D · incorrect — Too broad: arbitrary access to another class is not inheritance
Question 193
What is the concept of polymorphism in Java?
A. The ability to create multiple objects from a single class.
B. The ability to hide implementation details.
C. The ability to override methods in a subclass.
D. The ability of an object to take many forms and be treated as an instance of its superclass.
Hint / Module Reference (Where to Read)
Identify whether the emphasis is grouping state, hiding implementation, exposing essentials or varying behavior.
Correct answer: D — The ability of an object to take many forms and be treated as an instance of its superclass.
Polymorphism means many forms and can be illustrated by a parent reference to a child object. Overriding is one mechanism, not the full concept.
Evidence in the complete study note
Inheritance forms a subtype relationship and may reuse implementation. Polymorphism lets code using a common type invoke behavior appropriate to different concrete objects.OOP02
For Animal a=new Dog(), Animal is the declared type and Dog the actual type. The declared type determines which member operations compile. If fetch() exists only in Dog, a.fetch() fails compilation. For an eligible overridden sound(), a.sound() invokes Dog.sound() at runtime.OOP15
Information hiding keeps implementation decisions behind a stable interface. Abstraction presents the essential operations while omitting details irrelevant to the caller.OOP02
Choice by choice
A · incorrect — Creating several same-class objects does not imply many type forms
B · incorrect — Hiding details describes abstraction
C · incorrect — Overriding supports runtime polymorphism but is a narrower mechanism
D · correct — Matches both many forms and common-superclass treatment
Question 194
What is the purpose of the super keyword in Java?
A. To access the superclass of a derived class.
B. To instantiate a new object.
C. To access the current object.
D. To define a method within a class.
Alternative version 1
Inside an instance method declared in the current subclass, which descriptions correctly identify the parent-class context selected by Java super? Select all that apply.
A. It refers to the current object instance.
B. It refers to the superclass of the current class.
C. It refers to the class that contains the current method.
D. It refers to the class from which the current class is derived.
Hint / Module Reference (Where to Read)
Distinguish the current instance, parent context, hidden fields and static dispatch.
Correct answer: A — To access the superclass of a derived class.
super selects the superclass context for member access and can request a superclass implementation. A hidden parent field can be selected with super.name, and super.sound() directly calls the parent version. It does not allocate a separate parent object or name the current instance; this is the current-object reference. Method definitions use declarations, so A is the valid purpose among the primary choices.
Evidence in the complete study note
Java this denotes the current object; this.name=name distinguishes a field from a parameter. super.name selects a hidden superclass field; super.sound() directly requests the parent implementation. It does not create a second parent object. An unqualified instance call may dispatch dynamically; an explicit super call is different.OOP16
class Dog extends Animal declares a subclass/derived/child of a superclass/base/parent.OOP13
Choice by choice
A · correct — This describes selecting the superclass context and its members.
B · incorrect — super does not allocate a separate object.
C · incorrect — this denotes the current object; super selects parent context.
D · incorrect — A method declaration defines a method; super does not do that.
Alternative version 1
Correct answers (select all): B, D — Both B and D describe the superclass context selected by super.
The superclass of the current class and the class from which the current class derives name the same parent relationship, so B and D both apply. super selects that parent context for member access or explicit parent implementation calls. A instead describes this, while C identifies the current subclass containing the declared method. The variant therefore needs multiple selection even though the primary choices have one correct answer.
Java this denotes the current object; this.name=name distinguishes a field from a parameter. super.name selects a hidden superclass field; super.sound() directly requests the parent implementation. It does not create a second parent object. An unqualified instance call may dispatch dynamically; an explicit super call is different.OOP16
class Dog extends Animal declares a subclass/derived/child of a superclass/base/parent.OOP13
A · incorrect — The current object instance is denoted by this, not the parent-context selector super.
B · correct — The superclass is the parent context selected by super.
C · incorrect — The method is declared in the current subclass, whereas super selects its parent context.
D · correct — The class from which the current class derives is its superclass, equivalent to B.
Question 195
What is the difference between an abstract class and an interface in Java?
A. An abstract class can have concrete methods, while an interface cannot.
B. An interface can have static methods, while an abstract class cannot.
C. An abstract class can be instantiated, while an interface cannot.
D. An interface can extend multiple interfaces, while an abstract class cannot.
Hint / Module Reference (Where to Read)
Identify the interface contract, effective modifiers and permitted implementation forms.
Correct answer: D — Interfaces can extend multiple interfaces; an abstract class instead implements interfaces and extends one class.
OOP19 permits an interface to extend several interfaces and a class to extend one superclass while implementing multiple interfaces. Thus D is correct when extend retains its Java declaration meaning. It must not be paraphrased as abstract classes cannot implement multiple interfaces. A is outdated for modern interfaces, B wrongly excludes class static methods, and C wrongly permits abstract instantiation.
Evidence in the complete study note
A class can extend a superclass and implement zero or more interfaces. An interface can extend several interfaces.OOP19
A method declaration without private, default or static is implicitly public abstract. Modern interfaces may also have default/static method bodies, and Java 9+ private helper methods.OOP19
An abstract class cannot be directly instantiated but can define fields, constructors, abstract methods and concrete methods.OOP18
static gives one field per loaded class, shared by its instances. If count starts at zero and every constructor increments it, three creations leave count=3. Prefer ClassName.count and ClassName.utility().OOP07
Choice by choice
A · incorrect — Modern interfaces can contain default/static bodies, so concrete behavior is not exclusive to abstract classes.
B · incorrect — Abstract classes can have static methods; their abstract modifier does not prohibit class-level methods.
C · incorrect — An abstract class cannot be directly instantiated, so the first half of this distinction is false.
D · correct — An interface extends multiple interfaces; a class implements them instead and has one direct superclass.
Question 196
Which access modifier provides the widest accessibility in Java?
A. private
B. protected
C. public
D. default (no modifier)
Hint / Module Reference (Where to Read)
Locate the accessing code, declaring type, package and receiver before applying visibility rules.
World-visible public access is wider than class-only, package-only or package-plus-subclasses access.
Evidence in the complete study note
For ordinary members: private restricts access to the declaring class/nest; no modifier grants package access; protected grants same-package access plus qualified subclass access; public is widest, provided the declaring type itself is accessible.OOP08
Choice by choice
A · incorrect — Class-only
B · incorrect — Package and subclasses
C · correct — Visible to the world
D · incorrect — Package-only
Question 197
What is the purpose of the this keyword in Java?
A. To refer to the superclass of a class.
B. To instantiate a new object.
C. To access the current object's variables and methods.
D. To define a method within a class.
Hint / Module Reference (Where to Read)
Distinguish the current instance, parent context, hidden fields and static dispatch.
Correct answer: C — Access the current object’s variables and methods.
OOP16 says this denotes the current object and demonstrates this.name=name to distinguish a field from a parameter. That makes C the requested purpose. super selects parent context, new creates an object, and method declarations define methods. this neither creates a new instance nor denotes the superclass or the class itself.
Evidence in the complete study note
Java this denotes the current object; this.name=name distinguishes a field from a parameter. super.name selects a hidden superclass field; super.sound() directly requests the parent implementation. It does not create a second parent object.OOP16
Student s; declares a reference variable; it creates no Student object. Student s=new Student(); allocates and initializes an instance.OOP03
Choice by choice
A · incorrect — Superclass context is selected using super, whereas this denotes the current object.
B · incorrect — Object instantiation uses new and constructor invocation, not the this current-object reference.
C · correct — this refers to the current object, enabling its instance fields and methods to be selected.
D · incorrect — A method is defined by a declaration and body; this is an expression referring to the current object.
Question 198
Which keyword is used to explicitly indicate that a method does not return any value in
Java?
A. void
B. null
C. final
D. static
Hint / Module Reference (Where to Read)
Separate parameters from arguments and operations that read state from operations that change it.
Correct answer: A — Defining multiple methods with the same name but different parameters in the same class.
The definition retains one method name while differentiating parameter lists. Return type alone is insufficient, so signature differences must be in parameters.
Evidence in the complete study note
Overloaded methods share a name but have different parameter types, counts or type order. Return type alone is insufficient in Java and C++. Overloads can also arise through inherited methods; “same class only” is a teaching simplification. f(int), f(double) and f(int,int) are distinct, but changing a parameter name does not create an overload.OOP12
Student s; declares a reference variable; it creates no Student object. Student s=new Student(); allocates and initializes an instance.OOP03
Choice by choice
A · correct — Matches same name and different parameters
B · incorrect — Nested method definition is not overloading
C · incorrect — Self-invocation is recursion
D · incorrect — Multiple objects are instantiation, not overloaded methods
Alternative version 1
Correct answer: B — Creating multiple methods with the same name but different parameter lists.
Apply the same study-note rule to this alternative source set; the choice contrasts below show the derivation.
Overloaded methods share a name but have different parameter types, counts or type order. Return type alone is insufficient in Java and C++.OOP12
A return type is not part of an ordinary Java method signature.OOP12
A · incorrect — Same-name/different-return methods are not necessarily overloads; return type alone is explicitly insufficient
B · correct — Same name with different parameter lists is the exact overloading definition
C · incorrect — Same parameter list prevents return-type-only overloading
D · incorrect — Access-modifier differences do not supply the required parameter difference
Question 200
What is the purpose of the new keyword in Java?
A. To instantiate a new object.
B. To invoke a method.
C. To define a variable.
D. To define a class.
Hint / Module Reference (Where to Read)
Separate a reference declaration, object allocation, reference copying and changes to the shared object.
A reference declaration is distinct from new Dog(), which creates the actual instance and triggers initialization.
Evidence in the complete study note
Student s; declares a reference variable; it creates no Student object. Student s=new Student(); allocates and initializes an instance.OOP03
A constructor has the class’s exact name and no return type, not even void. It initializes the new object and can be overloaded or private.OOP09
Choice by choice
A · correct — Matches object creation
B · incorrect — An ordinary method call does not by itself state the new allocation
C · incorrect — A variable declaration can exist without an object
D · incorrect — class declares the blueprint, not its instance
Question 201
What is the output of the following Java code snippet?
class MyClass {
public static void main(String[] args) {
int x = 5;
System.out.println(x++);
System.out.println(++x);
}
}
A. 5, 6
B. 5, 7
C. 6, 6
D. 6, 7
Hint / Module Reference (Where to Read)
Track the old and updated values separately and distinguish a character operand from a string.
OOP24 gives this exact sequence: postfix x++ supplies the old value 5 and then stores 6; prefix ++x then stores and supplies 7. The two println calls print those values on separate lines. The commas in the choices describe the sequence rather than literal commas emitted by the program.
Evidence in the complete study note
Starting x=5, printing x++ then ++x gives 5 then 7.OOP24
A print call emits its value without inserting a separator or ending the line. A println call emits its value followed by a line terminator. Spaces must come from the supplied text or explicit output operations; adjacent calls do not automatically separate their values.OOP-S02
Choice by choice
A · incorrect — The second prefix increment advances the stored 6 to 7 before printing, so the second value is not 6.
B · correct — Postfix prints the old 5, then prefix increments the stored 6 and prints 7.
C · incorrect — The first postfix expression supplies 5 rather than the incremented 6.
D · incorrect — The second value is 7, but the first remains 5 because its increment is postfix.
Question 202
Which Java keyword directly exits the enclosing loop prematurely while allowing execution to continue after that loop in the same method?
A. break
B. continue
C. return
D. exit
Hint / Module Reference (Where to Read)
Trace condition tests, control transfers and printing as separate steps.
break exits the enclosing loop and transfers control to the statement after it. continue skips the remaining body of the current iteration and may begin another iteration. return leaves the entire method, so it does not satisfy the stated requirement to continue after the loop in that same method. exit is not a Java loop-control keyword. The narrower control-flow target makes break unique.
Evidence in the complete study note
break exits the loop; continue skips its remaining body and then runs a for update.OOP25
An unlabeled break leaves the innermost enclosing loop or switch. continue moves to the next iteration step, while return leaves the current method and may supply a return value. These transfers have different destinations; return is not merely a loop exit.OOP-S03
Choice by choice
A · correct — break exits the loop and resumes after it within the method.
B · incorrect — continue proceeds toward another iteration rather than exiting the loop.
C · incorrect — return exits the entire method, contrary to the required continuation.
D · incorrect — exit is not a Java loop-control keyword.
Question 203
What is the purpose of the try-catch block in Java?
A. To handle exceptions and prevent program crashes.
B. To define a custom class.
C. To declare variables with restricted access.
D. To instantiate objects.
Hint / Module Reference (Where to Read)
Check the thrown type and catch order before tracing propagation or handler output.
Correct answer: A — To handle exceptions and prevent program crashes.
An exception disrupts execution, and try/catch monitors code and supplies a handler, as shown for an input mismatch. It can handle matched exceptions, not guarantee prevention of every crash.
Evidence in the complete study note
try encloses guarded operations; a matching catch handles the thrown type or a subtype. Execution skips the remainder of the try when a throw occurs.OOP30
Student s; declares a reference variable; it creates no Student object. Student s=new Student(); allocates and initializes an instance.OOP03
For ordinary members: private restricts access to the declaring class/nest; no modifier grants package access; protected grants same-package access plus qualified subclass access; public is widest, provided the declaring type itself is accessible.OOP08
Choice by choice
A · correct — Matches exception handling, with no universal recovery guarantee
B · incorrect — Class definition is a different construct
C · incorrect — Visibility modifiers govern access
D · incorrect — new and constructors instantiate objects
Question 204
Which independent Java declarations correctly create an int array? Select all that apply.
A. int[] numbers = {1, 2, 3};
B. int numbers[] = new int[3];
C. int numbers = new int[]{1, 2, 3};
D. int numbers[] = {1, 2, 3};
Hint / Module Reference (Where to Read)
Check declared dimensions, initializer shape, fixed length and zero-based index bounds.
Correct answers (select all): A, B, D — int[] numbers = {1, 2, 3};; int numbers[] = new int[3];; int numbers[] = {1, 2, 3};
A and D use legal bracket placements with a brace initializer to create arrays containing 1, 2 and 3. B also declares an int array and allocates three elements, initially zero. C instead declares numbers as a scalar int but supplies an int-array value, producing a type mismatch. Both bracket placement styles and both allocation forms are allowed, so A, B and D are selected.
Evidence in the complete study note
int[] a=new int[5]; and int a[]={1,2,3}; are valid. int[] a={}; creates a zero-length array; explicit new is unnecessary in a declaration initializer. int a[],b; makes only a an array; int[] c,d; makes both arrays. Array objects have fixed length after creation, although the reference may be reassigned.OOP26
Java fields and array elements receive defaults: numeric zero, char '\u0000', boolean false and references null.OOP05
Choice by choice
A · correct — The int[] type and brace initializer create a three-element int array.
B · correct — Brackets after the variable name and new int[3] are valid.
C · incorrect — The scalar int variable cannot hold the int[] initializer value.
D · correct — The name[] form with a brace initializer is valid.
Question 205
Which method is automatically called when an object is created in Java?
A. start()
B. run()
C. main()
D. constructor
Hint / Module Reference (Where to Read)
Check the class name, return-type absence and the constructors actually declared.
Correct answer: B — To invoke a method from the superclass.
super.member may name a method or instance variable of the immediate superclass. This directly covers invoking a superclass method.
Evidence in the complete study note
Java this denotes the current object; this.name=name distinguishes a field from a parameter. super.name selects a hidden superclass field; super.sound() directly requests the parent implementation. It does not create a second parent object.OOP16
final prevents reassignment of a variable, overriding of a method or extension of a class.OOP07
Student s=new Student(); allocates and initializes an instance.OOP03
Choice by choice
A · incorrect — Current-object role is this rather than super
B · correct — Matches superclass method access
C · incorrect — final is the separate class modifier
D · incorrect — new is the allocation operation
Question 207
What does the static keyword mean in Java?
A. It denotes that a variable or method belongs to the superclass.
B. It indicates that a variable or method can only be accessed within the same class.
C. It allows a variable or method to be accessed without creating an instance of the class.
D. It specifies that a variable or method cannot be modified.
Hint / Module Reference (Where to Read)
Decide whether a member belongs to a class or an object, then check initialization and final restrictions.
Correct answer: C — It allows a variable or method to be accessed without creating an instance of the class.
Static members belong to the class, and the static method is accessible by class name without an object. Visibility and immutability are separate properties.
Evidence in the complete study note
static gives one field per loaded class, shared by its instances. If count starts at zero and every constructor increments it, three creations leave count=3. Prefer ClassName.count and ClassName.utility(). A static method has no current instance, but can still use instance members through an explicit object reference.OOP07
final prevents reassignment of a variable, overriding of a method or extension of a class.OOP07
For ordinary members: private restricts access to the declaring class/nest; no modifier grants package access; protected grants same-package access plus qualified subclass access; public is widest, provided the declaring type itself is accessible.OOP08
Choice by choice
A · incorrect — Class membership does not mean belonging to the superclass
B · incorrect — Private is the visibility restriction
C · correct — Matches class access without creating an instance
D · incorrect — final, not static, prevents modification
Question 208
What is the output of the following Java code snippet?
class MyClass {
public static void main(String[] args) {
String text = "Hello";
text += " World";
System.out.println(text);
}
}
A. Hello
B. World
C. Hello World
D. Compile error
Hint / Module Reference (Where to Read)
Separate identity, content equality, immutable values and references that may be reassigned.
OOP22 directly explains that text += " World" assigns a reference to a new concatenated result rather than mutating the original String. The variable therefore refers to "Hello World" before printing. String immutability does not prevent rebinding a non-final variable, so the code is valid and prints the combined text with its space.
Evidence in the complete study note
Java String objects are immutable. text += " World" assigns a reference to a new concatenated result and can print Hello World without mutating the original String object. final class String prevents subclassing; final alone does not make arbitrary objects immutable.OOP22
Once a String operand is encountered, + concatenates in left-to-right groups: 1+2+"x" gives "3x", while "x"+1+2 gives "x12".OOP24
Choice by choice
A · incorrect — The variable is rebound to the concatenated result, so it no longer prints only its initial text.
B · incorrect — Concatenation retains Hello and appends the space and World; it does not replace the entire content with World.
C · correct — The new concatenated String contains Hello, a space and World, and text refers to that result.
D · incorrect — String immutability permits this reference reassignment; the code does not attempt to mutate the original String.
Question 209
Which access modifier allows a class member to be accessible only within the same
package?
A. public
B. private
C. protected
D. Default (no modifier specified)
Hint / Module Reference (Where to Read)
Locate the accessing code, declaring type, package and receiver before applying visibility rules.
Correct answer: D — Default (no modifier specified)
No modifier/default is explicitly package-private. Other modifiers are narrower or wider than the package-only requirement.
Evidence in the complete study note
For ordinary members: private restricts access to the declaring class/nest; no modifier grants package access; protected grants same-package access plus qualified subclass access; public is widest, provided the declaring type itself is accessible.OOP08
Across packages, a subclass accessing a protected instance member must do so through its own inherited context or an appropriate subclass-typed receiver, not any arbitrary superclass object. protected therefore does not mean “subclasses only”: unrelated classes in the same package also have access.OOP08
Choice by choice
A · incorrect — World-visible, too broad
B · incorrect — Class-only, too narrow
C · incorrect — Also includes out-of-package subclasses
D · correct — Exactly the package-private scope
Question 210
What is the output of the following Java code snippet?
class MyClass {
private int x = 5;
public int getX() {
return x;
}
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.x = 10;
System.out.println(obj.getX());
}
}
A. 5
B. 10
C. Compile error
D. Runtime exception
Hint / Module Reference (Where to Read)
Locate the accessing code, declaring type, package and receiver before applying visibility rules.
The write to obj.x is inside MyClass itself, even though main is static; private is class-based, not object-based. obj.x=10 updates the instance, and getX returns that field.
Evidence in the complete study note
A class’s own main method can access private fields of an instance of that class.OOP08
A static method has no current instance, but can still use instance members through an explicit object reference.OOP07
An accessor/getter returns information; a mutator/setter changes state.OOP11
A later assignment overwrites an earlier value.OOP-S03
Choice by choice
A · incorrect — Old initializer is replaced by the assignment
B · correct — Getter returns the updated field value 10
C · incorrect — Same-class code may access private fields through obj
D · incorrect — No exceptional operation is indicated by these class-local accesses
Question 211
What is the purpose of the toString() method in Java?
A. To convert an object to a string representation.
B. To compare two objects for equality.
C. To perform arithmetic calculations.
D. To access the superclass methods.
Hint / Module Reference (Where to Read)
Separate identity, content equality, immutable values and references that may be reassigned.
Correct answer: A — Return an object’s textual representation.
OOP22 defines toString as giving a textual representation and distinguishes it from an equality test. A states that purpose. Comparing objects is the role of equals under the class’s policy, while arithmetic and superclass method access are separate operations. The representation need not create a new copy of the original object.
Evidence in the complete study note
For object references, == tests identity; equals invokes the class’s equality policy. Object.equals uses identity unless overridden; String.equals compares character content. Equal objects must have equal hashCode values when that contract is implemented. toString gives a textual representation, not an equality test.OOP22
super.name selects a hidden superclass field; super.sound() directly requests the parent implementation.OOP16
Choice by choice
A · correct — A textual String representation of an object is the purpose explicitly assigned to toString in OOP22.
B · incorrect — Object equality is handled by equals under the class’s equality policy, not by toString.
C · incorrect — Arithmetic calculations are not the defining contract of an object’s textual representation method.
D · incorrect — Superclass access uses super; it is not the purpose of toString.
Question 212
What is the purpose of the equals() method in Java?
A. To convert an object to a string representation.
B. To compare two objects for equality.
C. To perform arithmetic calculations.
D. To access the superclass methods.
Hint / Module Reference (Where to Read)
Separate identity, content equality, immutable values and references that may be reassigned.
Correct answer: B — Compare objects according to the class’s equality policy.
OOP22 says equals invokes a class’s equality policy; Object.equals uses identity unless overridden, while String.equals compares content. B is therefore correct without assuming every class implements value equality. The other choices describe textual representation, arithmetic or superclass access, none of which is equals’ comparison purpose.
Evidence in the complete study note
For object references, == tests identity; equals invokes the class’s equality policy. Object.equals uses identity unless overridden; String.equals compares character content. Equal objects must have equal hashCode values when that contract is implemented. toString gives a textual representation, not an equality test.OOP22
super.name selects a hidden superclass field; super.sound() directly requests the parent implementation.OOP16
Choice by choice
A · incorrect — Textual representation is the purpose of toString, rather than equals.
B · correct — equals compares objects using the class’s policy, which may be identity or an overridden value/content policy.
C · incorrect — equals supplies an equality result rather than being an arithmetic calculation mechanism.
D · incorrect — Superclass access uses super and is distinct from the equality comparison performed by equals.
Question 213
What is the correct way to create an instance of a class in Java?
A. MyClass obj = new MyClass();
B. MyClass obj = MyClass();
C. MyClass obj = create MyClass();
D. MyClass obj = instance MyClass();
Hint / Module Reference (Where to Read)
Separate a reference declaration, object allocation, reference copying and changes to the shared object.
Correct answer: B — It allows the method to be accessed without creating an instance of the class.
Static methods can be called directly by class name without an object and cannot be overridden; a subclass declaration can hide them.
Evidence in the complete study note
static gives one field per loaded class, shared by its instances. If count starts at zero and every constructor increments it, three creations leave count=3. Prefer ClassName.count and ClassName.utility(). A static method has no current instance, but can still use instance members through an explicit object reference.OOP07
Constructors, final methods, static methods and private parent methods are not overridden.OOP14
For ordinary members: private restricts access to the declaring class/nest; no modifier grants package access; protected grants same-package access plus qualified subclass access; public is widest, provided the declaring type itself is accessible.OOP08
Choice by choice
A · incorrect — Contradicts the static non-overriding rule
B · correct — Matches object-free class access
C · incorrect — Visibility depends on access modifiers, not static alone
D · incorrect — Immutability/non-overriding is not the same as prohibition on modifying the method
Question 215
What is the role of the this keyword in Java?
A. It refers to the current object instance.
B. It refers to the superclass of the current class.
C. It refers to the class that contains the current method.
D. It refers to the class from which the current class is derived.
Alternative version 1
A. It refers to the superclass of the current class.
B. It refers to the subclass of the current class.
C. It refers to the current object instance.
D. It refers to the class that contains the current method.
Hint / Module Reference (Where to Read)
Distinguish the current instance, parent context, hidden fields and static dispatch.
Correct answer: A — this refers to the current object instance.
OOP16 defines this as the current object. In the main options that statement is A; it denotes an instance rather than its class, subclass or superclass. The source variant moves the same correct statement to C, so its labels must be reviewed separately. super is the distinct parent-context mechanism.
Evidence in the complete study note
Java this denotes the current object; this.name=name distinguishes a field from a parameter. super.name selects a hidden superclass field; super.sound() directly requests the parent implementation. It does not create a second parent object.OOP16
class Dog extends Animal declares a subclass/derived/child of a superclass/base/parent.OOP13
Choice by choice
A · correct — The current object instance is exactly what Java this denotes in ordinary instance context.
B · incorrect — Superclass context is selected by super, not by the current-object reference this.
C · incorrect — this refers to an instance, not to the class declaration containing a method.
D · incorrect — The class from which the current class derives is its superclass, not the meaning of this.
Alternative version 1
Correct answer: C — this refers to the current object instance.
OOP16 defines this as the current object. This source variant places that definition at C, rather than main-option A. The superclass and subclass alternatives name type relationships, and the containing-class alternative denotes a type rather than the current instance.
Java this denotes the current object; this.name=name distinguishes a field from a parameter. super.name selects a hidden superclass field; super.sound() directly requests the parent implementation. It does not create a second parent object.OOP16
class Dog extends Animal declares a subclass/derived/child of a superclass/base/parent.OOP13
A · incorrect — Superclass context is associated with super, rather than the current-instance reference this.
B · incorrect — A subclass is a type relationship; this denotes the current object, not a subclass.
C · correct — This variant places the exact current-object-instance definition from OOP16 at label C.
D · incorrect — The containing class is a type; this refers to the current object instance of a class.
Question 216
What is a constructor in Java?
A. A method that returns a value.
B. A method used for exception handling.
C. A special method used to initialize objects.
D. A method used to override a superclass method.
Hint / Module Reference (Where to Read)
Check the class name, return-type absence and the constructors actually declared.
Correct answer: C — A special method used to initialize objects.
Constructors automatically initialize objects, have the same name as their class and have no return type.
Evidence in the complete study note
A constructor has the class’s exact name and no return type, not even void. It initializes the new object and can be overloaded or private.OOP09
In Java’s class-declaration terminology, constructors are not members and are not inherited.OOP-S05
try encloses guarded operations; a matching catch handles the thrown type or a subtype. Execution skips the remainder of the try when a throw occurs.OOP30
Choice by choice
A · incorrect — Contradicts the no-return-type rule
B · incorrect — Exception handling uses try/catch
C · correct — Matches automatic initialization of new objects
D · incorrect — Constructors are not inherited overriding methods
Question 217
Assume an accessible inherited instance method is non-final, the subclass supplies the same name and parameter list with a compatible return type, and visibility is not reduced. Which descriptions fit the resulting method overriding? Select all that apply.
A. Creating multiple methods with the same name but different return types.
B. Creating multiple methods with the same name but different parameter lists.
C. Creating a new method with the same name and parameter list in the subclass.
D. Redefining a method in the subclass that already exists in the superclass.
Hint / Module Reference (Where to Read)
Check inheritance, signature compatibility, visibility and eligibility for an override.
Correct answers (select all): C, D — Creating a new method with the same name and parameter list in the subclass.; Redefining a method in the subclass that already exists in the superclass.
Under the stated eligibility, signature, return and visibility conditions, the subclass method overrides the inherited method. C describes the same name and parameters, and D describes redefining the inherited superclass operation, so both describe this case. Different parameter lists denote overloading instead. Merely changing return types does not define overriding or a valid overload. The assumptions make the two overlapping valid descriptions explicit.
Evidence in the complete study note
A subclass overrides an eligible inherited instance method with the same signature and a compatible return type; a covariant reference return may be a subtype. Visibility cannot become more restrictive, and checked exceptions cannot be broadened incompatibly.OOP14
Overloaded methods share a name but have different parameter types, counts or type order. Return type alone is insufficient in Java and C++.OOP12
Choice by choice
A · incorrect — Different return types alone do not define overriding or distinguish valid overloads.
B · incorrect — Different parameter lists describe overloading rather than this same-signature override.
C · correct — The same-name, same-parameter subclass declaration is an override under the supplied conditions.
D · correct — It redefines the eligible inherited superclass operation under the supplied conditions.
Question 218
What is polymorphism in Java?
A. The ability to create multiple objects of the same class.
B. The process of converting an object to a string representation.
C. The ability of an object to take on many forms through inheritance.
D. The process of comparing two objects for equality.
Hint / Module Reference (Where to Read)
Identify whether the emphasis is grouping state, hiding implementation, exposing essentials or varying behavior.
Correct answer: C — The ability of an object to take on many forms through inheritance.
Polymorphism means many forms, typically illustrated by a superclass reference pointing at child objects; inheritance supplies those related forms.
Evidence in the complete study note
Inheritance forms a subtype relationship and may reuse implementation. Polymorphism lets code using a common type invoke behavior appropriate to different concrete objects.OOP02
For Animal a=new Dog(), Animal is the declared type and Dog the actual type. The declared type determines which member operations compile.OOP15
For object references, == tests identity; equals invokes the class’s equality policy. Object.equals uses identity unless overridden; String.equals compares character content. Equal objects must have equal hashCode values when that contract is implemented. toString gives a textual representation, not an equality test.OOP22
Choice by choice
A · incorrect — Several objects of the same class is multiplicity of instances
B · incorrect — Object-to-string conversion is unrelated
C · correct — Matches many forms through a hierarchy
D · incorrect — Equality comparison is unrelated
Question 219
Which object-oriented principle promotes the concept of reusing code and creating
relationships between classes?
A. Encapsulation
B. Inheritance
C. Polymorphism
D. Abstraction
Hint / Module Reference (Where to Read)
Identify whether the emphasis is grouping state, hiding implementation, exposing essentials or varying behavior.
The inheritance section explicitly links reuse to creating a new class that inherits Person without changing Person, forming the parent/child relationship.
Evidence in the complete study note
Inheritance forms a subtype relationship and may reuse implementation. Polymorphism lets code using a common type invoke behavior appropriate to different concrete objects. Prefer a precise mechanism over a vague slogan: wrapping fields and methods points to encapsulation; showing what an operation does while hiding how points to abstraction.OOP02
Encapsulation groups related state and operations and controls access. Information hiding keeps implementation decisions behind a stable interface. Abstraction presents the essential operations while omitting details irrelevant to the caller.OOP02
Use inheritance when a subtype can satisfy the parent’s contract: Dog is an Animal. For shared Pet.name and speak(), put common state/contract in Pet, specialized fetch() in Dog, and appropriate speak() implementations in Dog and Cat. Composition represents has-a, such as Car containing Engine.OOP13
Choice by choice
A · incorrect — Wraps and hides data rather than deriving related classes
B · correct — Directly supplies reuse through inherited relationships
C · incorrect — Uses varying behavior through types rather than creating the reuse relationship
D · incorrect — Suppresses details rather than acquiring reusable members
Question 220
What is the purpose of encapsulation in object-oriented programming?
A. To create relationships between classes
B. To allow classes to inherit properties and behaviors
C. To hide internal implementation details and expose a public interface
D. To provide different implementations of a method based on the object's type
Hint / Module Reference (Where to Read)
Identify whether the emphasis is grouping state, hiding implementation, exposing essentials or varying behavior.
Correct answer: C — To hide internal implementation details and expose a public interface
The hidden-data part of encapsulation exposes access through methods, which is the public interaction boundary described by C. A/B describe inheritance and D describes polymorphic overriding.
Evidence in the complete study note
Encapsulation groups related state and operations and controls access. Information hiding keeps implementation decisions behind a stable interface. Abstraction presents the essential operations while omitting details irrelevant to the caller. These ideas overlap: a private balance plus deposit(amount) can demonstrate all three, depending on what the question emphasizes.OOP02
Inheritance forms a subtype relationship and may reuse implementation. Polymorphism lets code using a common type invoke behavior appropriate to different concrete objects.OOP02
Choice by choice
A · incorrect — Describes class relationships generally
B · incorrect — Describes inheritance specifically
C · correct — Matches hidden data accessed through methods
D · incorrect — Describes different behavior based on receiver type
Question 221
Which object-oriented principle allows an object to exhibit different behaviors based on its
data type?
A. Encapsulation
B. Inheritance
C. Polymorphism
D. Abstraction
Hint / Module Reference (Where to Read)
Identify whether the emphasis is grouping state, hiding implementation, exposing essentials or varying behavior.
An operation can behave differently for different subclasses, with method behavior determined by the object acted upon.
Evidence in the complete study note
Encapsulation groups related state and operations and controls access. Information hiding keeps implementation decisions behind a stable interface. Abstraction presents the essential operations while omitting details irrelevant to the caller.OOP02
Inheritance forms a subtype relationship and may reuse implementation. Polymorphism lets code using a common type invoke behavior appropriate to different concrete objects.OOP02
For an eligible overridden sound(), a.sound() invokes Dog.sound() at runtime.OOP15
Choice by choice
A · incorrect — Groups and hides data
B · incorrect — Creates the subtype relation but does not name varying operation behavior
C · correct — Matches behavior varying with object type
D · incorrect — Shows essentials while suppressing details
Question 222
What is the purpose of abstraction in object-oriented programming?
A. To create relationships between classes
B. To allow classes to inherit properties and behaviors
C. To hide internal implementation details and expose a public interface
D. To provide different implementations of a method based on the object's type
Hint / Module Reference (Where to Read)
Identify whether the emphasis is grouping state, hiding implementation, exposing essentials or varying behavior.
Correct answer: C — To hide internal implementation details and expose a public interface
Abstraction represents needed/essential information while hiding background details, matching a public-facing interface to hidden implementation.
Evidence in the complete study note
Encapsulation groups related state and operations and controls access. Information hiding keeps implementation decisions behind a stable interface. Abstraction presents the essential operations while omitting details irrelevant to the caller. These ideas overlap: a private balance plus deposit(amount) can demonstrate all three, depending on what the question emphasizes.OOP02
Inheritance forms a subtype relationship and may reuse implementation. Polymorphism lets code using a common type invoke behavior appropriate to different concrete objects.OOP02
Choice by choice
A · incorrect — Describes relationships rather than the essential view
B · incorrect — Describes inheritance
C · correct — Matches essential information with background details hidden
D · incorrect — Describes polymorphic differing implementations
Question 223
Which Java keyword declares that one class inherits from another class?
A. super
B. extends
C. implements
D. this
Hint / Module Reference (Where to Read)
Identify the subtype or ownership relationship and distinguish class inheritance from interface contracts.
A class declaration uses extends to name its direct superclass, as in class Dog extends Animal. A class implements interface contracts using implements, which is a different declaration relationship. super selects parent context inside a class, while this denotes the current instance. Restricting the question to class-to-class inheritance makes extends the unique keyword among these choices.
Evidence in the complete study note
class Dog extends Animal declares a subclass/derived/child of a superclass/base/parent. A class extends one direct class and can implement multiple interfaces.OOP13
Java this denotes the current object; this.name=name distinguishes a field from a parameter. super.name selects a hidden superclass field; super.sound() directly requests the parent implementation.OOP16
A class can extend a superclass and implement zero or more interfaces. An interface can extend several interfaces.OOP19
Choice by choice
A · incorrect — Refers to superclass members/constructor
B · correct — Matches class Sub extends Super
C · incorrect — Used for interface implementation instead
D · incorrect — Refers to current-instance context, not an inheritance declaration
Question 224
Which Java annotation requests compiler checking that a method overrides or implements an inherited method contract?
A. super
B. extends
C. implements
D. @Override
Hint / Module Reference (Where to Read)
Check inheritance, signature compatibility, visibility and eligibility for an override.
@Override asks the compiler to verify that a declaration satisfies overriding rules. Java does not have an override keyword, and the annotation does not create an override by itself; the declaration must still meet the inherited-contract conditions. super selects parent context, extends declares class inheritance, and implements declares interface relationships. Correcting the requested construct to an annotation preserves the intended override-checking concept.
Evidence in the complete study note
A subclass overrides an eligible inherited instance method with the same signature and a compatible return type; a covariant reference return may be a subtype. Visibility cannot become more restrictive, and checked exceptions cannot be broadened incompatibly. @Override requests compiler checking; Java has no override keyword. Constructors, final methods, static methods and private parent methods are not overridden.OOP14
class Dog extends Animal declares a subclass/derived/child of a superclass/base/parent. A class extends one direct class and can implement multiple interfaces.OOP13
super.name selects a hidden superclass field; super.sound() directly requests the parent implementation.OOP16
Choice by choice
A · incorrect — super selects parent members or construction rather than checking a declaration’s override status.
B · incorrect — extends establishes class inheritance rather than annotating a method.
C · incorrect — implements establishes an interface relationship rather than checking one method declaration.
D · correct — @Override requests compiler verification of the overriding/implementation relationship.
Question 225
Which object-oriented principle promotes the concept of grouping related properties and
behaviors into a single unit?
A. Encapsulation
B. Inheritance
C. Polymorphism
D. Abstraction
Hint / Module Reference (Where to Read)
Identify whether the emphasis is grouping state, hiding implementation, exposing essentials or varying behavior.
The stem repeats the definition of grouping data and methods into a single class unit.
Evidence in the complete study note
Encapsulation groups related state and operations and controls access. Information hiding keeps implementation decisions behind a stable interface. Abstraction presents the essential operations while omitting details irrelevant to the caller. These ideas overlap: a private balance plus deposit(amount) can demonstrate all three, depending on what the question emphasizes.OOP02
Inheritance forms a subtype relationship and may reuse implementation. Polymorphism lets code using a common type invoke behavior appropriate to different concrete objects.OOP02
Choice by choice
A · correct — Direct wrapping-up/grouping principle
B · incorrect — Acquires another class's members
C · incorrect — Many behavior forms
D · incorrect — Essential-information view rather than grouping
Question 226
Which object-oriented concept is used to create objects based on a predefined blueprint or
class?
A. Polymorphism
B. Inheritance
C. Encapsulation
D. Instantiation
Hint / Module Reference (Where to Read)
Separate a reference declaration, object allocation, reference copying and changes to the shared object.
A class is the template and an object its instance; new creates that actual object. Instantiation names creating the instance from the template.
Evidence in the complete study note
Student s; declares a reference variable; it creates no Student object. Student s=new Student(); allocates and initializes an instance.OOP03
Encapsulation groups related state and operations and controls access.OOP02
Inheritance forms a subtype relationship and may reuse implementation. Polymorphism lets code using a common type invoke behavior appropriate to different concrete objects.OOP02
Choice by choice
A · incorrect — Many forms rather than creation from a blueprint
B · incorrect — Deriving classes rather than objects
C · incorrect — Grouping data/methods rather than object creation
D · correct — Matches creating the actual instance from a class template
Question 227
Which one of the following is true regarding constructors in Java?
A. Constructors are invoked to create objects without using the new operator
B. Constructors can have a return type
C. A constructor can have a different name from its class name
D. Constructors play the role of initializing objects
Hint / Module Reference (Where to Read)
Check the class name, return-type absence and the constructors actually declared.
Public means visible to the world, including unrelated classes in other packages.
Evidence in the complete study note
For ordinary members: private restricts access to the declaring class/nest; no modifier grants package access; protected grants same-package access plus qualified subclass access; public is widest, provided the declaring type itself is accessible.OOP08
Choice by choice
A · incorrect — Only package and subclasses, not every class
B · incorrect — Only the package
C · correct — World-visible, satisfying all classes/packages
D · incorrect — Only the declaring class
Question 229
Which one of the following is NOT correct about function overloading in C++?
A. Two or more overloaded functions may differ in their number of parameters
B. Two or more overloaded functions may differ in data types of their parameters
C. Two or more overloaded functions should have the same function name
D. Two or more overloaded functions may differ only in their return types
Hint / Module Reference (Where to Read)
Compare names and parameter signatures before considering return types or access modifiers.
Correct answer: D — Return type alone cannot distinguish C++ overloads.
OOP12 states that overloaded methods/functions share a name and differ in parameter types, counts or order. It expressly rejects return type alone as sufficient in Java and C++. D is therefore the incorrect overloading claim. A, B and C describe valid differences or the shared-name requirement rather than violating the overload rule.
Evidence in the complete study note
Overloaded methods share a name but have different parameter types, counts or type order. Return type alone is insufficient in Java and C++.OOP12
Choice by choice
A · incorrect — Different parameter counts can distinguish overloads, so this is a correct overloading statement.
B · incorrect — Different parameter data types can distinguish overloads, so this is a correct overloading statement.
C · incorrect — Overloads share a function name, so this statement correctly describes their naming requirement.
D · correct — This is the false claim: return type alone cannot distinguish C++ overloads with otherwise identical signatures.
Question 230
Which purposes apply to Java interfaces? “Blueprint” means an operation contract, “state and behavior” in B means complete per-instance state and implementation, and “multiple inheritance” means type inheritance. Select all that apply.
A. To create multiple constructors for a class
B. To define the state and behavior of an object
C. To define a blueprint of a class
D. To achieve multiple inheritance
Hint / Module Reference (Where to Read)
Identify the interface contract, effective modifiers and permitted implementation forms.
Correct answers (select all): C, D — To define a blueprint of a class; To achieve multiple inheritance
An interface gives implementing classes an operation contract, so the defined blueprint purpose is valid. A class can implement multiple interfaces, supporting multiple type inheritance. Interfaces have no constructors or per-instance fields, so they do not create a class’s constructors or define an object’s complete state and implementation. With those meanings explicit, C and D are valid purposes and the other two are excluded.
Evidence in the complete study note
interface Payable{double getPaymentAmount();} declares an abstract public operation. class Invoice implements Payable must provide public double getPaymentAmount(), perhaps returning getQuantity()*getPricePerItem(). A class can extend a superclass and implement zero or more interfaces. An interface can extend several interfaces. No interface instance fields or constructors exist; fields are implicitly public static final.OOP19
Use an abstract class for shared state, construction and common implementation; use an interface for a capability across unrelated classes and multiple type inheritance.OOP20
Choice by choice
A · incorrect — Interfaces have no constructors and do not create class constructors.
B · incorrect — The complete per-instance state and implementation belong to classes, not interface capability contracts.
C · correct — The blueprint is an operation contract for implementing classes.
D · correct — Multiple implemented interfaces provide multiple type inheritance.
Question 231
Consider this C++17 class and statements inside a valid main function:
struct Meter {
int reading = 0;
void set(int reading) { this->reading = reading; }
static int twice(int x) { return 2 * x; }
};
Meter first, second;
first.set(4);
second.set(9);
int doubled = Meter::twice(3);
Which statement correctly describes the implicit object context during second.set(9) and the call to twice?
A. In set, this points to second; twice has no this pointer.
B. In set, this points to first; twice has no this pointer.
C. In set, this points to second; twice reuses second as its implicit object.
D. The hidden object argument is passed to the reading data member rather than to set.
Hint / Module Reference (Where to Read)
Use the stated language rules and identify whether a member call has an implicit current object.
Correct answer: A — In set, this points to second; twice has no this pointer.
Each non-static set call has an implicit object: first for first.set(4) and second for second.set(9). During the latter call, this therefore points to second, and this->reading selects that object’s field. The static twice function has no current object or this pointer, regardless of which instance method ran most recently. Data members themselves do not receive hidden call arguments.
Evidence in the complete study note
In ordinary C++17 non-static member functions, this is a pointer to the object on which the function is called; this->field selects a member. It is often explained as an implicit object argument to a member function call. It is not an argument passed to member variables, and a static member function has no this pointer.OOP17
Choice by choice
A · correct — second is the receiver of second.set(9); the static twice call has no implicit object.
B · incorrect — The earlier call on first does not make first the receiver of the later call on second.
C · incorrect — twice is static and does not acquire a this pointer from the most recent instance call.
D · incorrect — The implicit object belongs to the non-static function call; the reading data member does not receive a hidden argument.
Question 232
What will be the output of the following program segment?
public class Calculation {
public static void main(String[] args) {
int sum = 0;
for(int j = 1; j<=10; j++) {
sum = sum + j;
}
System.out.println(+sum);
}
A. 55
B. 44
C. 33
D. 66
Hint / Module Reference (Where to Read)
Trace condition tests, control transfers and printing as separate steps.
Correct answer: A — 55 for the shown program segment.
The shown program segment initializes sum to zero and adds j for all values 1 through 10 inclusive. Its numerical result is 55. The unary plus in println(+sum) preserves that value. This is a program segment; a complete compilation unit also requires the outer class’s closing brace.
Evidence in the complete study note
Count executions independently from printing.OOP25
A loop summing j=1..10 yields 55.OOP25
Prefix ++ and -- update a variable before supplying its value; postfix forms supply the old value before the update. Multiplication, division and remainder bind before addition and subtraction; same-level binary arithmetic groups left to right. Integer division truncates toward zero. Unary plus preserves its numeric operand’s value.OOP-S03
Choice by choice
A · correct — The ten inclusive additions produce 55; unary plus leaves that integer unchanged.
B · incorrect — 44 is not the sum of the stated inclusive sequence 1 through 10.
C · incorrect — 33 does not match all ten additions performed by the shown loop.
D · incorrect — 66 would correspond to including an additional 11, which this condition excludes.
Question 233
Which OOP principle specifically defines the boundary that groups an object’s state with its methods and controls clients’ access to that state?
A. Abstraction
B. Inheritance
C. Polymorphism
D. Encapsulation
Hint / Module Reference (Where to Read)
Identify whether the emphasis is grouping state, hiding implementation, exposing essentials or varying behavior.
Encapsulation groups related state and operations and controls access to them. That grouping and access boundary is the mechanism requested. Abstraction emphasizes the essential public view while omitting irrelevant details; it can coexist with encapsulation but does not name this specific boundary. Inheritance forms subtype relationships, and polymorphism supplies appropriate behavior through a common type.
Evidence in the complete study note
Encapsulation groups related state and operations and controls access. Information hiding keeps implementation decisions behind a stable interface. Abstraction presents the essential operations while omitting details irrelevant to the caller. These ideas overlap: a private balance plus deposit(amount) can demonstrate all three, depending on what the question emphasizes.OOP02
Inheritance forms a subtype relationship and may reuse implementation. Polymorphism lets code using a common type invoke behavior appropriate to different concrete objects.OOP02
Choice by choice
A · incorrect — Abstraction concerns the essential view presented to callers, rather than the specific grouping/access boundary requested.
B · incorrect — Inheritance forms a subtype relationship rather than a state-access boundary.
C · incorrect — Polymorphism provides behavior through common types rather than defining this grouping and access control.
D · correct — Encapsulation specifically groups state with operations and controls client access.
Question 234
Consider the following code snippet
class Animal { void sound() { System.out.println("Animal sound"); } }
class Dog extends Animal { void sound() { System.out.println("Bark!"); } }
Which OOP concept is illustrated when Dog provides its own version of sound?
A. Method overriding
B. Method overloading
C. Abstraction
D. Encapsulation
Hint / Module Reference (Where to Read)
Check inheritance, signature compatibility, visibility and eligibility for an override.
Dog extends Animal and declares its own sound() with the same name, no parameters and the same void result. Neither method is static, private or final in the shown code. Dog therefore overrides the inherited instance method, providing subtype-specific behavior. No changed parameter list exists to make this an overload.
Evidence in the complete study note
A subclass overrides an eligible inherited instance method with the same signature and a compatible return type; a covariant reference return may be a subtype. Visibility cannot become more restrictive, and checked exceptions cannot be broadened incompatibly. @Override requests compiler checking; Java has no override keyword. Constructors, final methods, static methods and private parent methods are not overridden.OOP14
Overloaded methods share a name but have different parameter types, counts or type order. Return type alone is insufficient in Java and C++.OOP12
Encapsulation groups related state and operations and controls access. Information hiding keeps implementation decisions behind a stable interface. Abstraction presents the essential operations while omitting details irrelevant to the caller.OOP02
Choice by choice
A · correct — Dog supplies the same eligible inherited sound() signature with its own behavior, which is overriding.
B · incorrect — Overloading requires a different parameter list; both sound methods have the same no-argument signature.
C · incorrect — Abstraction is broader essential-interface design, not the specific same-signature subclass mechanism shown.
D · incorrect — Encapsulation concerns grouped state/access control rather than this replacement of inherited method behavior.
Question 235
A member declared in package p must be usable by an unrelated helper in p and by a subclass in package q through its inherited context. Unrelated classes outside p must be excluded. Which access category fits these requirements?
A. Public
B. Default
C. Private
D. Protected
Hint / Module Reference (Where to Read)
Locate the accessing code, declaring type, package and receiver before applying visibility rules.
Correct answer: D — Protected, with qualified subclass access across packages.
Protected permits same-package access, including an unrelated helper, and qualified subclass access from another package. It does not grant access to unrelated clients in other packages. Public violates that exclusion, package/default access cannot reach the other-package subclass, and private cannot admit the unrelated same-package helper. For an instance member, the cross-package receiver restriction remains part of the protected rule.
Evidence in the complete study note
For ordinary members: private restricts access to the declaring class/nest; no modifier grants package access; protected grants same-package access plus qualified subclass access; public is widest, provided the declaring type itself is accessible.OOP08
Across packages, a subclass accessing a protected instance member must do so through its own inherited context or an appropriate subclass-typed receiver, not any arbitrary superclass object. protected therefore does not mean “subclasses only”: unrelated classes in the same package also have access.OOP08
Choice by choice
A · incorrect — Public would also admit the unrelated other-package clients that the stem excludes.
B · incorrect — Default/package access would exclude the subclass in q.
C · incorrect — Private would exclude the unrelated helper in p.
D · correct — Protected provides both requested contexts while retaining the stated other-package exclusion.
Question 236
Consider these Java 17 classes:
class Employee {
public final double calculateTax() { return 100.0; }
}
class Manager extends Employee {
// Insert exactly one candidate declaration here.
}
Which candidate fails compilation because it attempts to override the inherited final method? Evaluate each candidate independently.
A. public double calculateTax(double income) { return income * 0.1; }
Correct answer: B — public double calculateTax() { return 200.0; }
Employee’s no-argument calculateTax method is final, so Manager cannot provide another instance method with that same signature. B attempts exactly that override and fails compilation. A and C have different parameter types and therefore declare overloads. D also has a different parameter list; its static declaration is a separate overload, not a replacement for the inherited no-argument instance method. The final restriction does not prohibit every reuse of the name.
Evidence in the complete study note
Constructors, final methods, static methods and private parent methods are not overridden.OOP14
Overloaded methods share a name but have different parameter types, counts or type order. Return type alone is insufficient in Java and C++.OOP12
final prevents reassignment of a variable, overriding of a method or extension of a class.OOP07
Choice by choice
A · incorrect — The double parameter creates a different signature, so this overload does not override the final no-argument method.
B · correct — This has the inherited no-argument signature and attempts to override the final method.
C · incorrect — The int parameter creates an independent overload; its private access does not reduce the inherited method’s visibility.
D · incorrect — The String parameter creates a distinct static overload and leaves the inherited no-argument method unchanged.
Question 237
A class has a constructor: public Circle(double r) { this.radius = r; }. What happens when you write: Circle c = new Circle(); ?
Hint / Module Reference (Where to Read)
Check the class name, return-type absence and the constructors actually declared.
Answer: Compilation fails unless Circle also declares an accessible no-argument constructor.
Declaring Circle(double r) prevents Java from supplying the implicit default constructor. new Circle() requests a no-argument constructor, not the existing one-argument signature. OOP09 therefore predicts a compilation error unless another accessible no-argument constructor has been provided. Passing a double argument would instead target the shown constructor.
Evidence in the complete study note
If a class declares no constructor, Java supplies a default constructor. If Circle(double r) is declared, new Circle() fails unless a no-argument constructor is also declared.OOP09
Question 238
Which of the following is TRUE about instance variables that are not explicitly initialized?
Hint / Module Reference (Where to Read)
Locate the declaration scope and check default initialization versus definite assignment.
Answer: Uninitialized instance fields receive type defaults: numeric zero, false, null, or the zero char.
Instance variables are fields, so OOP05 gives them automatic defaults before explicit initialization. Numeric fields receive zero, boolean fields false, references null and char the zero code unit. This does not authorize reading an unassigned local variable: locals obey a separate definite-assignment requirement rather than receiving these field defaults.
Evidence in the complete study note
Java fields and array elements receive defaults: numeric zero, char '\u0000', boolean false and references null. A local int t; followed by printing t is a compilation error.OOP05
Question 239
What is the output of: static int count = 0; in a class, after creating 3 objects each incrementing count++ in their constructor?
Hint / Module Reference (Where to Read)
Decide whether a member belongs to a class or an object, then check initialization and final restrictions.
Answer: The shared count becomes 3; printing it would output 3.
static makes count a single field shared by the instances, not three independent counters. Starting at zero, each of the three constructor increments adds one to that same field, leaving three. The declaration itself prints nothing; 3 is the stored value and the result if the question’s output means subsequently printing count.
Evidence in the complete study note
static gives one field per loaded class, shared by its instances. If count starts at zero and every constructor increments it, three creations leave count=3. Prefer ClassName.count and ClassName.utility().OOP07
A print call emits its value without inserting a separator or ending the line.OOP-S02
Question 240
You declare: int number; inside a method and try to print it without assigning a value. What happens?
Hint / Module Reference (Where to Read)
Locate the declaration scope and check default initialization versus definite assignment.
Answer: Compilation fails because the local variable has not been definitely assigned.
number is declared inside a method, making it a local rather than an instance or static field. OOP05 requires a local to be definitely assigned before use. Printing it is a read, so the compiler rejects that read. Java does not substitute field-style zero or permit an arbitrary garbage output for the local.
Evidence in the complete study note
Locals occur in methods, constructors or blocks; they must be definitely assigned before use and cannot have public/private/protected modifiers.OOP05
Java fields and array elements receive defaults: numeric zero, char '\u0000', boolean false and references null. A local int t; followed by printing t is a compilation error.OOP05
Question 241
In UML class diagrams, how is an instance shown differently from a class?
Hint / Module Reference (Where to Read)
Read the notation and distinguish a class description from a particular instance.
Answer: An instance uses an underlined instanceName:ClassName label, often with slot values.
OOP04 gives an underlined label such as sara:Student for one particular object. A class box describes the common type with its name, attributes and operations; an instance notation can show actual slot values. Underlining static class features is a separate UML convention, so the full instanceName:ClassName pattern identifies the object here.
Evidence in the complete study note
A UML class box normally contains name, attributes and operations. Visibility uses + public, - private and # protected. A field can be written name:String and an operation getName():String.OOP04
An instance is conventionally labeled with an underlined instanceName:ClassName, such as sara:Student. Class notation describes a type; instance notation describes one particular object and may show its slot values. Underlining static class features has a different purpose; read the whole notation rather than assuming every underline means the same thing.OOP04
Question 242
Under Java 17, what is the key restriction on an explicit this(...) invocation inside a constructor?
Hint / Module Reference (Where to Read)
Trace constructor delegation and initialization in the specified Java version.
Answer: It must be the first constructor statement and delegates to another constructor in the same class.
Under Java 17, an explicit this(...) invocation must be the first constructor statement and delegates to another constructor of the same class. The constructor cannot also explicitly invoke super(...); the delegation chain reaches superclass construction through another constructor. The version qualification matters because later Java versions permit a restricted prologue, so the Java 17 rule should not be presented as timeless.
Evidence in the complete study note
Under Java 17 rules, an explicit this(args) or super(args) invocation must be the first constructor statement. this invokes another constructor in the same class; super invokes the immediate superclass constructor. A constructor cannot explicitly invoke both. If there is no explicit delegation, an implicit super() is inserted; a matching accessible no-argument parent constructor must exist.OOP10
Java 25 permits restricted statements before explicit constructor invocation; the older first-statement rule must be version qualified.OOP10
Question 243
A class has: public static final int MAX = 100; Can a subclass change this value?
Hint / Module Reference (Where to Read)
Decide whether a member belongs to a class or an object, then check initialization and final restrictions.
Answer: No. final prevents assigning a new value to that MAX field.
MAX is one static field whose initialized value is 100. final prevents a subclass or other client from assigning a replacement value to that field. A subclass could declare a separate same-name hidden field, but that would not change the inherited constant. Public controls accessibility, not permission to reassign a final field.
Evidence in the complete study note
final prevents reassignment of a variable, overriding of a method or extension of a class.OOP07
Fields are hidden rather than dynamically overridden, and same-signature static methods hide rather than override.OOP16
For ordinary members: private restricts access to the declaring class/nest; no modifier grants package access; protected grants same-package access plus qualified subclass access; public is widest, provided the declaring type itself is accessible.OOP08
Question 244
Which access modifier allows access ONLY within the same package (not even subclasses in other packages)?
Hint / Module Reference (Where to Read)
Locate the accessing code, declaring type, package and receiver before applying visibility rules.
Answer: Package-private/default access: omit an access modifier.
OOP08 says an ordinary member with no access modifier grants package access. This admits other code in the same package but does not admit an other-package subclass merely through inheritance. protected would be broader because it adds qualified cross-package subclass access; private would be narrower. The answer is omission, not a default keyword modifier.
Evidence in the complete study note
For ordinary members: private restricts access to the declaring class/nest; no modifier grants package access; protected grants same-package access plus qualified subclass access; public is widest, provided the declaring type itself is accessible.OOP08
Across packages, a subclass accessing a protected instance member must do so through its own inherited context or an appropriate subclass-typed receiver, not any arbitrary superclass object. protected therefore does not mean “subclasses only”: unrelated classes in the same package also have access.OOP08
Question 245
Can a constructor be declared private? What is a use case?
Hint / Module Reference (Where to Read)
Check the class name, return-type absence and the constructors actually declared.
Answer: Yes. A private constructor can support a factory or controlled singleton creation.
OOP09 explicitly permits private constructors. Restricting constructor access prevents arbitrary outside callers from directly constructing the class, while its own permitted code can still instantiate it. A factory can control creation, or a singleton arrangement can expose a controlled instance. Private construction does not mean the class can never create any object internally.
Evidence in the complete study note
It initializes the new object and can be overloaded or private. A private constructor can support a factory or controlled singleton creation; it does not mean the class can never create an object internally.OOP09
Question 246
What is the difference between a.equals(b) and a == b when comparing objects?
Hint / Module Reference (Where to Read)
Separate identity, content equality, immutable values and references that may be reassigned.
For object references, == asks whether they denote the same object. equals invokes a method whose policy may compare content or value; Object.equals remains identity-based unless overridden. String.equals compares character content. Therefore equals does not automatically mean value equality for every class, and two distinct objects may be equal under an appropriate override.
Evidence in the complete study note
For object references, == tests identity; equals invokes the class’s equality policy. Object.equals uses identity unless overridden; String.equals compares character content. Equal objects must have equal hashCode values when that contract is implemented. toString gives a textual representation, not an equality test.OOP22
Question 247
In Java, a class extends two classes simultaneously: public class Dog extends Animal, Mammal {}. What is the result?
Hint / Module Reference (Where to Read)
Identify the subtype or ownership relationship and distinguish class inheritance from interface contracts.
Answer: Compilation fails: a Java class cannot extend two direct superclasses.
OOP13 explicitly prohibits class Dog extends Animal,Mammal. Java class inheritance permits one direct superclass, so the comma-separated extends clause is invalid rather than a runtime ambiguity to resolve. A class can instead implement multiple interfaces for multiple type contracts, and composition can combine separately held collaborators where multiple state/implementation sources are needed.
Evidence in the complete study note
class Dog extends Animal declares a subclass/derived/child of a superclass/base/parent. A class extends one direct class and can implement multiple interfaces. Single, multilevel and hierarchical inheritance mean one parent, a chain, and several children of one parent. Java does not permit class Dog extends Animal,Mammal.OOP13
Composition represents has-a, such as Car containing Engine.OOP13
Question 248
A private method in a superclass is 'overridden' in a subclass with the same name and signature. What actually happens?
Hint / Module Reference (Where to Read)
Check inheritance, signature compatibility, visibility and eligibility for an override.
Answer: The child declaration is independent; it does not override the private parent method.
OOP14 expressly treats a same-signature child method matching a private parent method as an independent declaration. The parent’s private method is not an eligible inherited method for runtime overriding. Thus equal spelling and parameters alone do not establish polymorphic replacement, and this is not ordinary static-method hiding either. Calls must follow each declaration’s own accessibility and context.
Evidence in the complete study note
A same-signature child method matching a private parent method is an independent declaration, not runtime overriding and not ordinary static-method hiding.OOP14
Constructors, final methods, static methods and private parent methods are not overridden.OOP14
Question 249
Animal a = new Dog(); — What is the declared type and actual type?
Hint / Module Reference (Where to Read)
Check what compiles from the declared type, then select behavior from the actual runtime class.
Animal is the variable’s declared compile-time type, determining which member operations may be selected by source checking. new Dog() creates the object, making Dog its actual runtime class. Assignment to the Animal reference does not turn that object into an Animal-only instance. Eligible overridden calls still use the runtime Dog implementation.
Evidence in the complete study note
For Animal a=new Dog(), Animal is the declared type and Dog the actual type. The declared type determines which member operations compile. If fetch() exists only in Dog, a.fetch() fails compilation. For an eligible overridden sound(), a.sound() invokes Dog.sound() at runtime.OOP15
Question 250
You have Animal a = new Dog(); and Dog has a method fetch() not in Animal. What happens when you call a.fetch()?
Hint / Module Reference (Where to Read)
Check what compiles from the declared type, then select behavior from the actual runtime class.
Answer: Compilation fails because fetch() is absent from the declared Animal type.
Although the object is a Dog, the reference a has declared type Animal. OOP15 checks member availability using that declared type before considering runtime overriding. Because fetch() exists only in Dog, a.fetch() is rejected. A checked/safe narrowing to a suitable Dog reference could expose Dog-specific members, but the original expression does not perform that narrowing.
Evidence in the complete study note
For Animal a=new Dog(), Animal is the declared type and Dog the actual type. The declared type determines which member operations compile. If fetch() exists only in Dog, a.fetch() fails compilation. For an eligible overridden sound(), a.sound() invokes Dog.sound() at runtime.OOP15
Use if(a instanceof Ferrari) before narrowing when the dynamic type is uncertain.OOP21
Question 251
What is dynamic binding (late binding) in Java?
Hint / Module Reference (Where to Read)
Check what compiles from the declared type, then select behavior from the actual runtime class.
Answer: Eligible overridden instance methods are selected at runtime from the actual object class.
The compiler first verifies accessible members and selects the method signature from declared types. Runtime dispatch then selects the most specific eligible override in the object’s actual class. For Animal a=new Dog(), a.sound() can therefore invoke Dog.sound(). This rule does not make Dog-only methods compile through Animal, and static methods/fields follow different selection rules.
Evidence in the complete study note
For Animal a=new Dog(), Animal is the declared type and Dog the actual type. The declared type determines which member operations compile. If fetch() exists only in Dog, a.fetch() fails compilation. For an eligible overridden sound(), a.sound() invokes Dog.sound() at runtime.OOP15
To solve dispatch questions: check the declaration and visibility, determine the compile-time signature, then identify the object’s runtime class and its most specific override.OOP15
Fields are hidden rather than dynamically overridden, and same-signature static methods hide rather than override. With Animal a=new Dog(), a.staticMethod() resolves using Animal’s compile-time type. Prefer Animal.staticMethod() for clarity.OOP16
Question 252
An abstract class has 3 abstract methods. A subclass implements only 2. What is the result?
Hint / Module Reference (Where to Read)
Check whether a class is concrete and whether every inherited abstract contract has an implementation.
Answer: The subclass must remain abstract unless it provides or inherits the third implementation; a concrete incomplete subclass fails compilation.
Implementing only two of three required methods leaves an abstract obligation. OOP18 requires a concrete subclass to provide or inherit implementations for every required method. If the third is still unimplemented, declaring the subclass abstract is permitted; declaring it concrete is not. Merely implementing a majority of the methods does not satisfy the parent contract.
Evidence in the complete study note
A concrete subclass must provide or inherit implementations of all required abstract methods; otherwise it must itself be abstract.OOP18
Question 253
Can an abstract class have a constructor? Can it be instantiated?
Hint / Module Reference (Where to Read)
Check whether a class is concrete and whether every inherited abstract contract has an implementation.
Answer: Yes, it can have constructors; no, it cannot be directly instantiated.
OOP18 allows an abstract class to define constructors alongside fields and concrete/abstract methods. Its constructor participates in initializing the inherited part of a concrete subclass object. That initialization role does not permit new of the abstract class itself. Direct instantiation remains prohibited even if the abstract class happens to contain no abstract methods.
Evidence in the complete study note
An abstract class cannot be directly instantiated but can define fields, constructors, abstract methods and concrete methods. It need not contain an abstract method.OOP18
Under Java 17 rules, an explicit this(args) or super(args) invocation must be the first constructor statement. this invokes another constructor in the same class; super invokes the immediate superclass constructor. A constructor cannot explicitly invoke both.OOP10
Question 254
What is the difference between implementing an interface and extending a class?
Hint / Module Reference (Where to Read)
Identify the subtype or ownership relationship and distinguish class inheritance from interface contracts.
Answer: extends forms a single superclass relationship; implements fulfills one or more interface contracts.
A class can extend one superclass, gaining a subtype relationship and appropriate inherited implementation/state. It can also implement multiple interfaces, satisfying their required public operations through provided or inherited methods. Interfaces supply capability contracts rather than per-instance fields or constructors. Modern default/static interface methods mean the distinction cannot simply be summarized as interfaces never contain bodies.
Evidence in the complete study note
class Dog extends Animal declares a subclass/derived/child of a superclass/base/parent. A class extends one direct class and can implement multiple interfaces.OOP13
A class can extend a superclass and implement zero or more interfaces. An interface can extend several interfaces. No interface instance fields or constructors exist; fields are implicitly public static final.OOP19
A method declaration without private, default or static is implicitly public abstract. Modern interfaces may also have default/static method bodies, and Java 9+ private helper methods. Not every interface method must lack a body in modern Java. Implementations must satisfy all inherited abstract contracts; they may inherit suitable public implementations.OOP19
Question 255
For an ordinary bodyless Java interface method declaration with no private, default or static modifier, which two method modifiers are implicit?
Hint / Module Reference (Where to Read)
Identify the interface contract, effective modifiers and permitted implementation forms.
The specified bodyless interface method is implicitly public and abstract. An implementing concrete class must satisfy the public contract without reducing its visibility. This scoped rule does not describe every modern interface method: default and static methods may have bodies, and Java 9 and later allow private helper methods. Those forms are explicitly outside the declaration being classified.
Evidence in the complete study note
A method declaration without private, default or static is implicitly public abstract. Modern interfaces may also have default/static method bodies, and Java 9+ private helper methods.OOP19
Question 256
Can an interface have instance fields (instance variables)?
Hint / Module Reference (Where to Read)
Identify the interface contract, effective modifiers and permitted implementation forms.
Answer: No. Interface fields are implicitly public static final, not per-instance variables.
OOP19 explicitly excludes interface instance fields. Any field declared in an interface is a public static final class-level constant under the note’s rule, even when some modifiers are not written. Implementing classes may define their own instance fields, but those belong to the implementing objects rather than being instance state supplied by the interface.
Evidence in the complete study note
No interface instance fields or constructors exist; fields are implicitly public static final.OOP19
Question 257
What is the output? Animal a = new Cat(); a.makeNoise(); — Cat overrides makeNoise() to print 'Meow'
Hint / Module Reference (Where to Read)
Check what compiles from the declared type, then select behavior from the actual runtime class.
Answer: Meow, from Cat.makeNoise(), assuming the inherited method is accessible and eligible for overriding.
The declared Animal type allows the makeNoise call under the stated override relationship. The actual object is a Cat, so runtime dispatch selects Cat’s overriding implementation and prints Meow. Assignment to a superclass reference does not suppress subclass behavior. The question does not specify an exact print API, so no additional punctuation or newline is invented.
Evidence in the complete study note
For Animal a=new Dog(), Animal is the declared type and Dog the actual type. The declared type determines which member operations compile. If fetch() exists only in Dog, a.fetch() fails compilation. For an eligible overridden sound(), a.sound() invokes Dog.sound() at runtime.OOP15
To solve dispatch questions: check the declaration and visibility, determine the compile-time signature, then identify the object’s runtime class and its most specific override.OOP15
Question 258
When is downcasting (Dog dog = (Dog) animal;) safe to use?
Hint / Module Reference (Where to Read)
Separate compile-time cast compatibility from the object’s actual runtime type.
Answer: For a non-null value, when the actual object is Dog or a subtype; test instanceof when uncertain.
An Animal reference may denote a Dog, another subtype or a plain Animal. Downcasting succeeds for an actual Dog-compatible object and otherwise throws ClassCastException. OOP21 recommends instanceof before narrowing when uncertain. Casting null also succeeds and yields null, but using it as an object afterward fails; therefore successful casting and safe dereferencing are distinct questions.
Evidence in the complete study note
Upcasting a subclass reference to a superclass is implicit and does not change the object. A downcast may pass compile-time type checks yet fail at runtime. Car a=new Car(); Ferrari f=(Ferrari)a; throws ClassCastException before subsequent drive() or brake() calls. It does not turn a plain Car into a Ferrari.OOP21
Use if(a instanceof Ferrari) before narrowing when the dynamic type is uncertain. null instanceof Ferrari is false; casting null yields null, although dereferencing it fails.OOP21
Question 259
What does the final keyword prevent when applied to a class like: final class String {}?
Hint / Module Reference (Where to Read)
Decide whether a member belongs to a class or an object, then check initialization and final restrictions.
Answer: It prevents subclasses from extending that class.
OOP07 says final on a class prohibits extension. Developers therefore cannot declare a subclass of String. This differs from final on a variable, which prevents reassignment, and final on a method, which prevents overriding. A final class is not automatically immutable merely because subclassing is prohibited; String’s immutability is an additional property discussed in OOP22.
Evidence in the complete study note
final prevents reassignment of a variable, overriding of a method or extension of a class. A final reference may still refer to a mutable object.OOP07
final class String prevents subclassing; final alone does not make arbitrary objects immutable.OOP22
Question 260
Can a static method be overridden in Java?
Hint / Module Reference (Where to Read)
Distinguish the current instance, parent context, hidden fields and static dispatch.
Answer: No. A same-signature subclass static method hides the parent static method.
OOP16 states that static methods hide rather than override. Selecting a static method through a reference uses the compile-time type, unlike eligible instance-method dispatch based on the object’s runtime class. Thus Animal a=new Dog(); a.staticMethod() selects Animal’s static declaration. ClassName.method() is the clearer recommended spelling and makes that selection explicit.
Evidence in the complete study note
Fields are hidden rather than dynamically overridden, and same-signature static methods hide rather than override. With Animal a=new Dog(), a.staticMethod() resolves using Animal’s compile-time type. Prefer Animal.staticMethod() for clarity. Java this and super are unavailable as current-instance references in static context.OOP16
Question 261
What is the 'is-a' relationship and how does it relate to inheritance?
Hint / Module Reference (Where to Read)
Identify the subtype or ownership relationship and distinguish class inheritance from interface contracts.
Answer: A subtype is a valid instance of its parent contract: Dog is an Animal.
OOP13 recommends inheritance when a subtype can satisfy its parent’s contract, as Dog satisfies Animal. That is the is-a relationship rather than mere code reuse. Car containing Engine is instead has-a composition. Reusing fields or methods alone does not justify declaring a subclass if its behavior cannot honor the parent’s promised operations.
Evidence in the complete study note
Use inheritance when a subtype can satisfy the parent’s contract: Dog is an Animal. For shared Pet.name and speak(), put common state/contract in Pet, specialized fetch() in Dog, and appropriate speak() implementations in Dog and Cat. Composition represents has-a, such as Car containing Engine. Reuse alone does not justify an invalid is-a relationship.OOP13
Question 262
You call super() in a subclass constructor but the superclass has no no-arg constructor. What happens?
Hint / Module Reference (Where to Read)
Trace constructor delegation and initialization in the specified Java version.
An explicit super() requests the immediate superclass’s no-argument constructor. OOP10 requires a matching accessible parent constructor, so a superclass with only parameterized constructors cannot satisfy that invocation. The subclass must instead call an appropriate super(arguments) or the superclass must provide an accessible no-argument constructor. Java does not synthesize one after another constructor has been declared.
Evidence in the complete study note
this invokes another constructor in the same class; super invokes the immediate superclass constructor. A constructor cannot explicitly invoke both. If there is no explicit delegation, an implicit super() is inserted; a matching accessible no-argument parent constructor must exist.OOP10
If a class declares no constructor, Java supplies a default constructor. If Circle(double r) is declared, new Circle() fails unless a no-argument constructor is also declared.OOP09
Question 263
What is the purpose of the protected access modifier specifically for inheritance?
Hint / Module Reference (Where to Read)
Locate the accessing code, declaring type, package and receiver before applying visibility rules.
Answer: It permits inherited access in subclasses across packages, and also same-package access.
protected supports subclass use of a parent member without making it universally public. OOP08 also grants access to unrelated code in the same package, so it is not subclasses-only. Across packages an instance member must be accessed in the inherited context or through an appropriate subclass-typed receiver, rather than any arbitrary superclass object.
Evidence in the complete study note
For ordinary members: private restricts access to the declaring class/nest; no modifier grants package access; protected grants same-package access plus qualified subclass access; public is widest, provided the declaring type itself is accessible.OOP08
Across packages, a subclass accessing a protected instance member must do so through its own inherited context or an appropriate subclass-typed receiver, not any arbitrary superclass object. protected therefore does not mean “subclasses only”: unrelated classes in the same package also have access.OOP08
Question 264
An interface Drawable extends both Shape and Colorable interfaces. A class Circle implements Drawable. What must Circle implement?
Hint / Module Reference (Where to Read)
Identify the interface contract, effective modifiers and permitted implementation forms.
Answer: A concrete Circle must satisfy all inherited abstract operations from Drawable, Shape and Colorable.
Drawable can extend both interfaces, combining their contracts. Circle implements Drawable and must therefore provide or inherit suitable public implementations of every remaining abstract operation from the full hierarchy. One compatible implementation can satisfy a shared signature; inherited defaults may supply implementations where applicable. If obligations remain unresolved, Circle must be abstract rather than an incomplete concrete class.
Evidence in the complete study note
A class can extend a superclass and implement zero or more interfaces. An interface can extend several interfaces.OOP19
Implementations must satisfy all inherited abstract contracts; they may inherit suitable public implementations.OOP19
If two compatible interfaces merely declare the same abstract signature, one public implementation can satisfy both. If return types or other contracts conflict, additional declarations may still be impossible.OOP20
A concrete subclass must provide or inherit implementations of all required abstract methods; otherwise it must itself be abstract.OOP18
Question 265
What happens if you declare the same method in both an abstract class and the interface it implements?
Hint / Module Reference (Where to Read)
Check the kind of inherited method and whether competing contracts require an explicit resolution.
Answer: Compatible declarations can coexist; implementation obligations depend on abstract, concrete and default status.
OOP20 says a concrete inherited class method takes precedence over an interface default. An abstract class declaration can instead leave an implementation obligation for a concrete subclass. A compatible public implementation may satisfy the interface contract, but incompatible signatures/return types may be impossible. Without declaration details, these conditional rules are the answer rather than one unconditional outcome.
Evidence in the complete study note
A concrete inherited class method takes precedence over an interface default. An inherited abstract class declaration can require a concrete subclass to implement the operation rather than silently adopting a default.OOP20
Unrelated interfaces providing conflicting defaults require an explicit resolution; interfaces do not remove every diamond ambiguity. If two compatible interfaces merely declare the same abstract signature, one public implementation can satisfy both. If return types or other contracts conflict, additional declarations may still be impossible. The answer to “same method in abstract class and interface” depends on whether each is abstract or implemented and whether their signatures are compatible.OOP20
Question 266
Can you instantiate an interface? If not, how do you use it?
Hint / Module Reference (Where to Read)
Identify the interface contract, effective modifiers and permitted implementation forms.
Answer: Not directly. Use an interface reference holding an implementing object, anonymous implementation or suitable lambda.
OOP19 prohibits direct interface instantiation while allowing a reference of interface type to hold an implementing object. Calls then use the interface contract with the object’s implementation. Anonymous class syntax still creates an implementing class instance, and a compatible functional-interface lambda supplies an implementation; neither means constructing a bare interface with no implementation.
Evidence in the complete study note
Implementations must satisfy all inherited abstract contracts; they may inherit suitable public implementations. Interfaces cannot be instantiated directly, but references may hold implementing objects, anonymous implementations or suitable functional-interface lambdas.OOP19
Question 267
What is the difference between throw and throws in Java?
Hint / Module Reference (Where to Read)
Check the thrown type and catch order before tracing propagation or handler output.
Answer: throw actively raises an exception value; throws declares a method’s possible checked-exception obligation.
OOP30 contrasts throw new IOException("message") with throws IOException in a method signature. The first performs an action in control flow, skipping the remaining try body; the second declares an obligation that callers must handle or propagate. A throws clause does not itself throw anything, and throwing a checked exception still requires handling or declaration.
Evidence in the complete study note
throw new IOException("message") actively throws a value; throws IOException in a signature declares a possible checked exception. A caller must handle or propagate checked obligations. try encloses guarded operations; a matching catch handles the thrown type or a subtype. Execution skips the remainder of the try when a throw occurs.OOP30
Question 268
What happens if an exception occurs in a try block and there is no matching catch block?
Hint / Module Reference (Where to Read)
Check the thrown type and catch order before tracing propagation or handler output.
Answer: It propagates outward to a matching enclosing handler; if uncaught, its thread terminates.
Without a matching local catch, the exception is not ignored and execution does not resume with the next ordinary statement in the try. OOP30 sends it outward through enclosing calls/handlers. Relevant finally blocks normally execute during that exit under OOP31’s limits. If no handler catches it, the uncaught exception terminates its thread, not necessarily every JVM thread.
Evidence in the complete study note
Execution skips the remainder of the try when a throw occurs.OOP30
If no catch matches, the exception propagates outward and an uncaught exception terminates its thread.OOP30
finally normally executes after try and any selected catch, including when leaving by return or propagating an exception. It is not guaranteed if the process/JVM exits or crashes, or control never leaves the try.OOP31
Question 269
Is it mandatory to handle an ArithmeticException?
Hint / Module Reference (Where to Read)
Separate source errors from runtime exceptions and determine the hierarchy and checked obligation.
Answer: No catch-or-declare obligation applies: ArithmeticException is unchecked.
OOP29 lists ArithmeticException among unchecked exceptions, so Java does not require a surrounding catch or throws declaration merely because it may occur. A program can still catch it when that provides useful recovery. Unchecked means no mandatory compile-time handling obligation, not harmless behavior: an uncaught occurrence propagates and may terminate its thread.
Evidence in the complete study note
RuntimeException and Error subclasses are unchecked; other throwable classes are checked. IOException, FileNotFoundException and SQLException are standard checked examples. ArithmeticException, NullPointerException, ClassCastException and array bounds exceptions are unchecked.OOP29
Checked does not mean the exception occurs at compile time: the compiler checks an obligation to catch or declare it, while an actual throw occurs at runtime.OOP29
If no catch matches, the exception propagates outward and an uncaught exception terminates its thread.OOP30
Question 270
What is the order of execution in: try { ... } catch(E e) { ... } finally { ... }?
Hint / Module Reference (Where to Read)
Check the thrown type and catch order before tracing propagation or handler output.
Answer: Run try, then a matching catch if thrown, then normally finally.
If try completes normally, no catch executes and finally follows. If an exception is thrown, the remaining try body is skipped, a matching catch runs if available, and finally normally executes before continuation or outward propagation. finally also normally runs on return. Process/JVM exit, a crash or control never leaving try prevents an unconditional always claim.
Evidence in the complete study note
Execution skips the remainder of the try when a throw occurs.OOP30
finally normally executes after try and any selected catch, including when leaving by return or propagating an exception. It is not guaranteed if the process/JVM exits or crashes, or control never leaves the try.OOP31
Question 271
You catch a general Exception before a specific IOException. What is the result?
Hint / Module Reference (Where to Read)
Check the thrown type and catch order before tracing propagation or handler output.
Answer: Compilation fails because the IOException catch after Exception is unreachable.
Exception already catches IOException values because IOException is a subtype. The later subtype handler can never be selected, and OOP30 says this ordering prevents compilation rather than merely causing the general handler to win at runtime. Place the specific IOException catch before Exception if both handlers are needed.
Evidence in the complete study note
Catch blocks are considered in source order. Place FileNotFoundException before IOException and IOException before Exception; a general catch before a subtype catch makes that later handler unreachable and prevents compilation.OOP30
Question 272
What does e.printStackTrace() actually print?
Hint / Module Reference (Where to Read)
Track pending returns or exceptions and distinguish normal cleanup from process termination.
Answer: Exception information plus recorded call-stack frames for diagnosis.
OOP31 distinguishes getMessage, toString and printStackTrace. The stack trace reports exception information together with recorded call frames, helping locate the call path associated with the failure. It is more diagnostic context than the message alone and does not repair or handle the error by itself. Exact text depends on the exception and recorded frames.
Evidence in the complete study note
getMessage returns the message, toString normally includes type and message, and printStackTrace shows exception information and recorded call frames for diagnosis. Tests should cover expected success, caught failures and propagation. Exception handling does not replace validation or correct an algorithm’s logic automatically.OOP31
Question 273
Can a finally block change the return value of a try block?
Hint / Module Reference (Where to Read)
Track pending returns or exceptions and distinguish normal cleanup from process termination.
Answer: Yes. A return from finally overrides the pending try/catch return; avoid it.
A try return expression is evaluated before finally runs. A return statement inside finally can replace that pending return and can even suppress an exception, which OOP31 warns against. Merely changing a local after a primitive return expression was evaluated does not automatically recompute that earlier result. The explicit finally return is the clear override mechanism.
Evidence in the complete study note
A return expression is evaluated before finally; a finally return overrides the pending return and can suppress an exception, so avoid that pattern.OOP31
Question 274
What is the difference between Error and Exception in Java?
Hint / Module Reference (Where to Read)
Separate source errors from runtime exceptions and determine the hierarchy and checked obligation.
Answer: They are Throwable branches: Error usually denotes serious conditions; Exception contains checked and unchecked application exceptions.
OOP29 places Error and Exception below Throwable. Error normally signals serious conditions for which routine recovery is inappropriate and its subclasses are unchecked. Exception includes unchecked RuntimeException subclasses and other checked exceptions requiring catch-or-declare handling. It is technically possible to catch Error, so the distinction must not be stated as errors can never be caught.
Evidence in the complete study note
Throwable is the root of throwable values, with Exception and Error branches. RuntimeException and Error subclasses are unchecked; other throwable classes are checked.OOP29
Checked does not mean the exception occurs at compile time: the compiler checks an obligation to catch or declare it, while an actual throw occurs at runtime. A custom exception can extend Exception or RuntimeException. Error normally signals serious conditions for which routine recovery is inappropriate; it is not technically impossible to catch an Error.OOP29
Question 275
FileNotFoundException is a subclass of IOException. Which catch block executes: catch(IOException e) or catch(FileNotFoundException e)?
Hint / Module Reference (Where to Read)
Check the thrown type and catch order before tracing propagation or handler output.
Answer: For FileNotFoundException, the first applicable catch wins; put it before IOException.
Both handler types can match a FileNotFoundException, so catch order matters. If FileNotFoundException is first, that specific block executes. If IOException is placed first with FileNotFoundException afterward, the latter is unreachable and compilation fails. If only IOException is present, it can handle the subclass. The prompt omits order, so these cases must be distinguished.
Evidence in the complete study note
Execution skips the remainder of the try when a throw occurs.OOP30
Catch blocks are considered in source order. Place FileNotFoundException before IOException and IOException before Exception; a general catch before a subtype catch makes that later handler unreachable and prevents compilation. If no catch matches, the exception propagates outward and an uncaught exception terminates its thread.OOP30
Question 276
What does ClassCastException indicate?
Hint / Module Reference (Where to Read)
Separate compile-time cast compatibility from the object’s actual runtime type.
Answer: An attempted reference cast is incompatible with the actual object type.
A cast can be syntactically and type-checkably permitted between related reference types while still fail at runtime. OOP21’s plain Car cannot become a Ferrari merely by casting, so ClassCastException occurs before subsequent method calls. The exception reports an incompatible dynamic type, not object transformation, allocation or a numeric conversion failure.
Evidence in the complete study note
Upcasting a subclass reference to a superclass is implicit and does not change the object. A downcast may pass compile-time type checks yet fail at runtime. Car a=new Car(); Ferrari f=(Ferrari)a; throws ClassCastException before subsequent drive() or brake() calls. It does not turn a plain Car into a Ferrari.OOP21
For Object obj="Hello", (String)obj succeeds and (Integer)obj throws ClassCastException.OOP21
Question 277
Can you use multiple catch blocks for one try block? Can one catch block catch multiple exceptions?
Hint / Module Reference (Where to Read)
Check the thrown type and catch order before tracing propagation or handler output.
Answer: Yes to both: use ordered catches or a multi-catch such as catch(IOException | SQLException e).
One try can have several catch blocks; source order and specific-before-general reachability still apply. A single multi-catch can also handle alternative exception types. OOP30 prohibits alternatives related by subclassing, so IOException and FileNotFoundException cannot be paired in one union catch. Their hierarchy instead calls for an appropriate common catch or ordered handlers.
Evidence in the complete study note
Catch blocks are considered in source order. Place FileNotFoundException before IOException and IOException before Exception; a general catch before a subtype catch makes that later handler unreachable and prevents compilation. If no catch matches, the exception propagates outward and an uncaught exception terminates its thread. Multiple catch blocks are allowed; catch(IOException | SQLException e) handles alternatives, which must not be related by subclassing.OOP30
Question 278
What is the output? int x = 5; int y = ++x * x--; System.out.println(x + ' ' + y);
Hint / Module Reference (Where to Read)
Track the old and updated values separately and distinguish a character operand from a string.
Answer: 73. The expression leaves x=5 and y=36, then adds the space character’s value 32.
Java evaluates ++x first, changing 5 to 6 and supplying 6. x-- then supplies 6 and restores x to 5, so y=36. In x + ' ' + y the space is char, not String, and numeric promotion gives 5+32+36=73. Replacing it with a double-quoted space would instead concatenate separated values.
Evidence in the complete study note
Starting x=5, printing x++ then ++x gives 5 then 7. For int y=++x*x--, Java uses 6*6=36 and leaves x=5. System.out.println(x + ' ' + y) then adds char space’s numeric value 32, so it prints 73. To print separated values, use x + " " + y instead.OOP24
Arithmetic promotes char, byte and short to int in many expressions.OOP06
Question 279
Circle and Sphere are separately declared top-level Java classes. Circle declares private double radius; and Sphere extends Circle. What happens if an instance method of Sphere attempts this.radius = 5.0;?
Hint / Module Reference (Where to Read)
Separate parameters from arguments and operations that read state from operations that change it.
Answer: Compilation fails for an ordinary separately declared Sphere: the inherited radius field is private.
The direct field access fails compilation. Circle’s private field is not accessible from a separately declared top-level subclass, and this only identifies the current object; it does not relax visibility. Sphere must use an accessible operation supplied by Circle if it needs to request a radius change. Declaring the classes separately removes the shared-nest exception from the scenario.
Evidence in the complete study note
A private field cannot normally be accessed directly by a separately declared subclass, even with this.field; use a permitted parent operation.OOP11
For ordinary members: private restricts access to the declaring class/nest; no modifier grants package access; protected grants same-package access plus qualified subclass access; public is widest, provided the declaring type itself is accessible.OOP08
Java this denotes the current object; this.name=name distinguishes a field from a parameter.OOP16
Question 280
What is the difference between a concrete class and an abstract class?
Hint / Module Reference (Where to Read)
Check whether a class is concrete and whether every inherited abstract contract has an implementation.
Answer: A concrete class can be instantiated and must satisfy abstract obligations; an abstract class cannot be directly instantiated.
An abstract class can hold state, constructors, concrete methods and abstract methods, and need not contain an abstract method. A concrete subclass must provide or inherit implementations of every required abstract operation before it can serve as an instantiable class. Abstract is therefore a class-level instantiation/contract restriction, not a prohibition on implemented behavior.
Evidence in the complete study note
An abstract class cannot be directly instantiated but can define fields, constructors, abstract methods and concrete methods. It need not contain an abstract method.OOP18
A concrete subclass must provide or inherit implementations of all required abstract methods; otherwise it must itself be abstract.OOP18
Question 281
String is declared as a final class. What does this mean for developers?
Hint / Module Reference (Where to Read)
Decide whether a member belongs to a class or an object, then check initialization and final restrictions.
Answer: Developers cannot subclass String; final prohibits extension.
Applying final to String prevents any class from extending String. It does not prevent constructing or referencing String instances, nor does the class modifier alone explain immutability of arbitrary objects. OOP22 treats String’s immutable content as a distinct property. Developers should use existing String operations rather than attempting a String subclass.
Evidence in the complete study note
final prevents reassignment of a variable, overriding of a method or extension of a class. A final reference may still refer to a mutable object.OOP07
Java String objects are immutable. text += " World" assigns a reference to a new concatenated result and can print Hello World without mutating the original String object. final class String prevents subclassing; final alone does not make arbitrary objects immutable.OOP22
Question 282
What is method hiding in Java and how does it differ from overriding?
Hint / Module Reference (Where to Read)
Distinguish the current instance, parent context, hidden fields and static dispatch.
Answer: A subclass static method hides a same-signature parent static method; overriding is runtime instance dispatch.
For static hiding, the selected declaration follows the compile-time type used to qualify the call. For eligible overridden instance methods, the object’s runtime class determines the implementation. OOP16’s Animal a=new Dog() static call therefore resolves to Animal, unlike a virtual instance sound call that could invoke Dog. Class qualification makes static selection clearer.
Evidence in the complete study note
Fields are hidden rather than dynamically overridden, and same-signature static methods hide rather than override. With Animal a=new Dog(), a.staticMethod() resolves using Animal’s compile-time type. Prefer Animal.staticMethod() for clarity.OOP16
For Animal a=new Dog(), Animal is the declared type and Dog the actual type. The declared type determines which member operations compile. If fetch() exists only in Dog, a.fetch() fails compilation. For an eligible overridden sound(), a.sound() invokes Dog.sound() at runtime.OOP15
Question 283
Given: interface A { void m1(); } interface B { void m2(); } class C implements A, B {} — What must C define?
Hint / Module Reference (Where to Read)
Identify the interface contract, effective modifiers and permitted implementation forms.
Answer: C must provide public void m1() and public void m2(), or inherit suitable implementations.
Both unmodified interface declarations are implicitly public abstract. A concrete C implementing A and B must satisfy both signatures, not merely one. In the shown class with no suitable superclass implementation, define public void m1() and public void m2(). Package-private implementations would narrow the public contract; otherwise C must be declared abstract instead of concrete.
Evidence in the complete study note
A method declaration without private, default or static is implicitly public abstract. Modern interfaces may also have default/static method bodies, and Java 9+ private helper methods. Not every interface method must lack a body in modern Java. Implementations must satisfy all inherited abstract contracts; they may inherit suitable public implementations.OOP19
A concrete subclass must provide or inherit implementations of all required abstract methods; otherwise it must itself be abstract.OOP18
Visibility cannot become more restrictive, and checked exceptions cannot be broadened incompatibly.OOP14
Question 284
What is the significance of the java.lang.Throwable class?
Hint / Module Reference (Where to Read)
Separate source errors from runtime exceptions and determine the hierarchy and checked obligation.
Answer: Throwable is the common root of Java’s throwable Error and Exception hierarchy.
OOP29 places both Error and Exception under Throwable, establishing the common type for Java throwable values. The distinction between checked and unchecked branches controls catch-or-declare obligations, not whether an exception happens during compilation. Throwable therefore unifies the hierarchy without implying that every subclass is an ordinary recoverable application exception.
Evidence in the complete study note
Throwable is the root of throwable values, with Exception and Error branches. RuntimeException and Error subclasses are unchecked; other throwable classes are checked.OOP29
Checked does not mean the exception occurs at compile time: the compiler checks an obligation to catch or declare it, while an actual throw occurs at runtime. A custom exception can extend Exception or RuntimeException. Error normally signals serious conditions for which routine recovery is inappropriate; it is not technically impossible to catch an Error.OOP29
Question 285
A method throws a checked exception but neither catches it nor declares throws. What happens?
Hint / Module Reference (Where to Read)
Check the thrown type and catch order before tracing propagation or handler output.
Answer: Compilation fails because the checked exception is neither handled nor declared.
OOP30 requires callers and methods to handle or propagate checked obligations. A method that may throw a checked exception but neither catches it nor declares it in throws violates that compile-time requirement. The failure is not that checked exceptions occur during compilation: the compiler is checking a possible future runtime throw.
Evidence in the complete study note
throw new IOException("message") actively throws a value; throws IOException in a signature declares a possible checked exception. A caller must handle or propagate checked obligations. try encloses guarded operations; a matching catch handles the thrown type or a subtype.OOP30
Checked does not mean the exception occurs at compile time: the compiler checks an obligation to catch or declare it, while an actual throw occurs at runtime.OOP29
Question 286
What does 'extensibility' mean in the context of polymorphism?
Hint / Module Reference (Where to Read)
Check what compiles from the declared type, then select behavior from the actual runtime class.
Answer: New subtypes can supply behavior while existing common-type client code remains reusable.
OOP15 describes a common Animal array loop invoking speak on Dog and Cat objects. Adding another conforming Animal subtype can supply its own override without rewriting that generic loop. That ability is extensibility through polymorphism: clients depend on the shared contract, while runtime dispatch supplies subtype behavior. The new subtype must still satisfy that contract.
Evidence in the complete study note
To solve dispatch questions: check the declaration and visibility, determine the compile-time signature, then identify the object’s runtime class and its most specific override. An array Animal[]{new Dog(),new Cat()} can call speak() on each using one loop. New subclasses can supply behavior without rewriting this generic loop, which is the practical meaning of extensibility.OOP15
Question 287
You have: Object obj = 'Hello'; String s = (String) obj; Is this valid? What about Integer i = (Integer) obj;?
Hint / Module Reference (Where to Read)
Separate compile-time cast compatibility from the object’s actual runtime type.
Answer: Literal single-quoted Hello is invalid. With "Hello", the String cast succeeds and the Integer cast throws ClassCastException.
A Java character literal cannot contain the multi-character text 'Hello', so the printed declaration fails before either cast executes. OOP21 explicitly separates that defect from the intended double-quoted version. After changing it to a String literal, obj refers to a String: narrowing back to String succeeds, but narrowing it to Integer fails at runtime.
Evidence in the complete study note
For Object obj="Hello", (String)obj succeeds and (Integer)obj throws ClassCastException. A literal 'Hello' is invalid Java syntax; use double quotes for a string literal before tracing the program.OOP21
A double-quoted string literal denotes a String object. new String(existingString) creates a String with the same text; new String(charArray) copies the array’s characters into an immutable String. A single-quoted literal denotes one char, so several characters enclosed together in single quotes cannot supply a String.OOP-S04
Question 288
If a subclass constructor doesn't explicitly call super(), what does Java do?
Hint / Module Reference (Where to Read)
Trace constructor delegation and initialization in the specified Java version.
Answer: If no explicit this(...) or super(...) delegation exists, Java inserts super(); this(...) instead delegates within the class.
Omitting explicit super() alone is insufficient to determine what happens. A constructor may explicitly call this(...), delegating to another same-class constructor that eventually reaches superclass construction. Only when there is no explicit constructor delegation does OOP10 insert super(), requiring an accessible matching parent no-argument constructor. Otherwise the program fails to compile.
Evidence in the complete study note
Under Java 17 rules, an explicit this(args) or super(args) invocation must be the first constructor statement. this invokes another constructor in the same class; super invokes the immediate superclass constructor. A constructor cannot explicitly invoke both. If there is no explicit delegation, an implicit super() is inserted; a matching accessible no-argument parent constructor must exist.OOP10
Question 289
What is the difference between a class and an object? Use a concrete example.
Hint / Module Reference (Where to Read)
Distinguish an object’s stored state, operations, identity and class definition.
Answer: A class defines common structure/behavior; an object is one instance, such as a particular Rectangle with width and height.
Rectangle can define width, height, getArea and getPerimeter for every rectangle. A particular rectangle object stores its own width and height values and responds to those operations. OOP01 distinguishes that instance from the type description: two objects can have equal field values and still have distinct identities. The class is shared structure, not one particular rectangle.
Evidence in the complete study note
An object has identity, state and behavior. State is stored in fields; behavior is provided by methods. A Rectangle object may hold width and height and answer getArea() or getPerimeter(). Two objects can have equal fields and still be distinct objects. A class defines their common structure and behavior; an object is a particular instance.OOP01
Question 290
Why is encapsulation important? How is it achieved?
Hint / Module Reference (Where to Read)
Identify whether the emphasis is grouping state, hiding implementation, exposing essentials or varying behavior.
Answer: Encapsulation protects invariants and stable interfaces by grouping state with validated operations and controlling access.
OOP02 groups state and operations with controlled access, keeping representation decisions behind stable interfaces. A private account balance exposed through deposit(amount) can reject invalid negative changes rather than permitting unrestricted assignment. This localizes responsibility and lets clients use meaningful operations without depending on internal representation. OOP11 cautions that automatically exposing setters for every field is not required.
Evidence in the complete study note
Encapsulation groups related state and operations and controls access. Information hiding keeps implementation decisions behind a stable interface. Abstraction presents the essential operations while omitting details irrelevant to the caller. These ideas overlap: a private balance plus deposit(amount) can demonstrate all three, depending on what the question emphasizes.OOP02
An accessor/getter returns information; a mutator/setter changes state. Encapsulation does not require blindly generating setters for every field: validate changes and expose only useful operations. For a bank account, deposit must reject negative amounts.OOP11
Question 291
What is the difference between method overloading and method overriding? Provide examples.
Hint / Module Reference (Where to Read)
Compare names and parameter signatures before considering return types or access modifiers.
Answer: Overloading changes parameter signatures; overriding replaces eligible inherited instance behavior with the same signature.
For overloading, f(int), f(double) and f(int,int) share a name but have distinct signatures selected using declared arguments at compile time. For overriding, Dog extends Animal and supplies void sound() matching Animal’s eligible void sound(); a superclass reference can then dispatch to Dog at runtime. Changing only the return type cannot create an overload, and override return compatibility still matters.
Evidence in the complete study note
Overloaded methods share a name but have different parameter types, counts or type order. Return type alone is insufficient in Java and C++. Overloads can also arise through inherited methods; “same class only” is a teaching simplification. f(int), f(double) and f(int,int) are distinct, but changing a parameter name does not create an overload.OOP12
The compiler selects the applicable signature from the declared argument types and conversions.OOP12
A subclass overrides an eligible inherited instance method with the same signature and a compatible return type; a covariant reference return may be a subtype. Visibility cannot become more restrictive, and checked exceptions cannot be broadened incompatibly.OOP14
For an eligible overridden sound(), a.sound() invokes Dog.sound() at runtime.OOP15
Question 292
Why can't Java classes inherit from multiple parent classes? How is this limitation overcome?
Hint / Module Reference (Where to Read)
Identify the subtype or ownership relationship and distinguish class inheritance from interface contracts.
Answer: Java permits one direct superclass. Use multiple interfaces for type contracts and composition for cooperating implementation/state.
The immediate reason the declaration is rejected is Java’s one-direct-superclass rule in OOP13. Multiple interfaces supply multiple type contracts, while contained collaborators model has-a reuse without multiple class inheritance. This does not eliminate every diamond problem: OOP20 requires explicit resolution of conflicting unrelated interface defaults. The note supplies these mechanisms, rather than a historical language-design rationale.
Evidence in the complete study note
class Dog extends Animal declares a subclass/derived/child of a superclass/base/parent. A class extends one direct class and can implement multiple interfaces. Single, multilevel and hierarchical inheritance mean one parent, a chain, and several children of one parent. Java does not permit class Dog extends Animal,Mammal.OOP13
Composition represents has-a, such as Car containing Engine. Reuse alone does not justify an invalid is-a relationship.OOP13
Unrelated interfaces providing conflicting defaults require an explicit resolution; interfaces do not remove every diamond ambiguity.OOP20
Question 293
What is polymorphism? Explain with a code example.
Hint / Module Reference (Where to Read)
Check what compiles from the declared type, then select behavior from the actual runtime class.
Answer: Polymorphism lets a common-type reference invoke behavior appropriate to the actual subtype.
Example: class Animal { void sound() { System.out.println("Animal"); } } class Dog extends Animal { void sound() { System.out.println("Bark"); } } Then Animal a=new Dog(); a.sound(); prints Bark. The declared Animal type makes sound available; the actual Dog object supplies its eligible override at runtime. A new Animal subtype can participate through the same common operation.
Evidence in the complete study note
For Animal a=new Dog(), Animal is the declared type and Dog the actual type. The declared type determines which member operations compile. If fetch() exists only in Dog, a.fetch() fails compilation. For an eligible overridden sound(), a.sound() invokes Dog.sound() at runtime.OOP15
To solve dispatch questions: check the declaration and visibility, determine the compile-time signature, then identify the object’s runtime class and its most specific override. An array Animal[]{new Dog(),new Cat()} can call speak() on each using one loop. New subclasses can supply behavior without rewriting this generic loop, which is the practical meaning of extensibility.OOP15
Question 294
When would you use an abstract class versus an interface?
Hint / Module Reference (Where to Read)
Check the kind of inherited method and whether competing contracts require an explicit resolution.
Answer: Use an abstract class for shared state/construction/implementation; use an interface for capabilities across unrelated classes and multiple type contracts.
An abstract class can centralize common fields, constructor initialization and concrete operations while leaving selected operations abstract. An interface specifies a capability that otherwise unrelated classes can implement, and a class may implement several interfaces. Modern interface defaults do not supply per-instance fields or constructors, so shared object state/construction remains a reason to choose an abstract class.
Evidence in the complete study note
Use an abstract class for shared state, construction and common implementation; use an interface for a capability across unrelated classes and multiple type inheritance.OOP20
No interface instance fields or constructors exist; fields are implicitly public static final.OOP19
An abstract class cannot be directly instantiated but can define fields, constructors, abstract methods and concrete methods.OOP18