0% found this document useful (0 votes)
7 views34 pages

OOP Sample Exam

The document outlines an advanced Java programming exam focused on object-oriented programming concepts, covering multiple choice questions related to Java syntax, operators, exception handling, recursion, and OOP principles. It includes questions about identifiers, method functionality, class structures, and polymorphism, with correct answers provided for each question. The exam assesses knowledge of Java features and best practices in programming.

Uploaded by

samiragamal07
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views34 pages

OOP Sample Exam

The document outlines an advanced Java programming exam focused on object-oriented programming concepts, covering multiple choice questions related to Java syntax, operators, exception handling, recursion, and OOP principles. It includes questions about identifiers, method functionality, class structures, and polymorphism, with correct answers provided for each question. The exam assesses knowledge of Java features and best practices in programming.

Uploaded by

samiragamal07
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java Programming Exam (Advanced Concepts)

Course: Object-Oriented Programming

Lectures Covered: Chapter 1 (Lectures 1-5), Chapter 2 (Lectures 6-7)

Instructions: Answer all questions.

Section 1: Multiple Choice Questions (40 Questions)

1. Which of the following is NOT a valid identifier in Java?

a) _myVariable

b) $

c) 1stVariable

d) my_variable

Answer: c) 1stVariable (Identifiers cannot start with a digit (number).)


2. What is the result of the following Java expression?

int a = 10;

int b = 3;

double result = (double) a / b;

[Link](result);

a) 3

b) 3.0

c) 3.3333333333333335

d) 3.3

Answer: c) 3.3333333333333335 (Casting a to double before division ensures


floating-point division.

3. Consider the following code snippet:

int x = 5;

[Link](x++ + ++x);

What is the output?

a) 10

b) 11

c) 12

d) 13

Answer: c) 12 (x++ uses 5, then x becomes 6; ++x increments x to 7, then uses 7.


So, 5 + 7 = 12.)
4. Which of these operators has the highest precedence?

a) +

b) *

c) &&

d) ==

Answer: b) * (Multiplication has higher precedence than addition, logical AND, or


equality.)

5. What will be the output of the following Java code?

boolean p = true;

boolean q = false;

[Link](p || q && !p);

a) true

b) false

c) Compilation Error

d) Runtime Error

Answer: a) true (Operator precedence: ! (NOT) > && (AND) > || (OR). So, !p is
false, q && !p is false && false which is false. Finally, p || (false) is true || false
which is true.)
6. Which of the following statements about if-else if-else ladders is TRUE?

a) Only the if and else blocks are mandatory.

b) Once a condition is met, the subsequent else if and else blocks are skipped.

c) All conditions are always evaluated.

d) The else block must always be present.

Answer: b) Once a condition is met, the subsequent else if and else blocks are
skipped.

7. What happens if you use break inside a nested for loop?

a) It breaks out of all loops.

b) It breaks out of the innermost loop only.

c) It skips the current iteration of the innermost loop.

d) It causes a compilation error.

Answer: b) It breaks out of the innermost loop only.

8. Which of the following is the correct way to iterate over an ArrayList named
list containing String elements using a for-each loop?

a) for (int i = 0; i < [Link](); i++) { [Link]([Link](i)); }

b) for (String s : list) { [Link](s); }

c) for ([Link](s) { [Link](s); })

d) [Link]([Link]::println); (While valid in Java 8+, b is the direct for-each


equivalent.)

Answer: b) for (String s : list) { [Link](s); }


9. What is the key difference between a primitive type array and an ArrayList
in terms of memory management?

a) Arrays store values directly, while ArrayList stores references to objects.

b) Arrays can change size, while ArrayLists have a fixed size.

c) ArrayLists are stored on the stack, while arrays are stored on the heap.

d) Arrays are always dynamically allocated, while ArrayLists are statically allocated.

Answer: a) Arrays store values directly, while ArrayList stores references to


objects. (Also, ArrayLists handle resizing automatically, unlike arrays.)

10. What is the main benefit of using methods in Java?

a) To make variables globally accessible.

b) To improve code readability and reusability.

c) To avoid the need for classes.

d) To make the program run faster without compilation.

Answer: b) To improve code readability and reusability.


11. Which of the following accurately describes public static void main(String[]
args)?

a) public makes it accessible from the JVM, static allows calling without an object,
void means it returns nothing, main is the entry point, String[] args for command-
line arguments.

b) public makes it accessible from other classes, static means it belongs to an


object, void means it can return any type, main is a standard method, String[] args
is optional.

c) public is a non-access modifier, static means it's a constant, void means it can
return a boolean, main is a user-defined method, String[] args is for GUI input.

d) public defines its scope within a package, static means it can be inherited, void
implies a default return value, main is a reserved keyword, String[] args is for file
input.

Answer: a) public makes it accessible from the JVM, static allows calling without
an object, void means it returns nothing, main is the entry point, String[] args for
command-line arguments.

12. When would you use a try-catch-finally block for file operations?

a) To skip file operations if an error occurs.

b) To ensure that file resources are always closed, even if exceptions occur during
read/write operations.

c) To only handle IOException and ignore other exceptions.

d) To make file operations faster.

Answer: b) To ensure that file resources are always closed, even if exceptions
occur during read/write operations.
13. What is a "checked exception" in Java?

a) An exception that occurs due to a programming error (e.g.,


NullPointerException).

b) An exception that the compiler forces you to handle (e.g., IOException).

c) An exception that extends RuntimeException.

d) An exception that can only be caught by the JVM.

Answer: b) An exception that the compiler forces you to handle (e.g.,


IOException).

14. What is the fundamental principle of recursion?

a) Using a loop to perform repeated operations.

b) A function calling another function from a different class.

c) A function calling itself until a base condition is met.

d) Iterating over an array using an index.

Answer: c) A function calling itself until a base condition is met.

15. In a recursive function, what is the role of the "base case"?

a) It's the first statement in the function definition.

b) It's the condition that triggers an infinite loop.

c) It's the condition that stops the recursion and provides a direct solution without
further recursive calls.

d) It's the recursive call itself.

Answer: c) It's the condition that stops the recursion and provides a direct
solution without further recursive calls.
16. What does the throws keyword indicate in a method signature?

a) The method will always throw an exception.

b) The method handles an exception internally.

c) The method might throw a specified exception, and the caller is responsible for
handling it.

d) The method is designed to be error-prone.

Answer: c) The method might throw a specified exception, and the caller is
responsible for handling it.

17. Which of the following is NOT a core principle of Object-Oriented


Programming (OOP)?

a) Encapsulation

b) Inheritance

c) Polymorphism

d)1 Global Variables

Answer: d) Global Variables (OOP emphasizes data hiding and localized scope, not
global variables.)

18. What is the primary purpose of a class in OOP?

a) To store a single piece of data.

b) To serve as a blueprint for creating objects, defining their state and behavior.

c) To execute the main program logic.

d) To manage system resources.

Answer: b) To serve as a blueprint for creating objects, defining their state and
behavior.
19. Consider the following class:

class Box {

int width;

public Box(int w) { width = w; }

public Box() { this(1); } // Line A

If new Box(); is called, which constructor will Line A invoke?

a) It will cause a compilation error.

b) It will call the Box(int w) constructor.

c) It will call the default constructor implicitly generated by Java.

d) It will call Box() recursively.

Answer: b) It will call the Box(int w) constructor. (This demonstrates constructor


chaining using this().)

20. What is the difference between new MyClass() and MyClass obj;?

a) Both create an object, but new MyClass() also calls the constructor.

b) new MyClass() allocates memory and calls the constructor, while MyClass obj;
only declares a reference variable.

c) MyClass obj; creates an object, while new MyClass() just assigns a value.

d) new MyClass() is for static objects, MyClass obj; is for dynamic objects.

Answer: b) new MyClass() allocates memory and calls the constructor, while
MyClass obj; only declares a reference variable.
21. If a class member is declared private, how can it be accessed from outside
the class?

a) Directly, using the dot operator.

b) Only through public getter and setter methods.

c) Only if the accessing class is in the same package.

d) It cannot be accessed at all.

Answer: b) Only through public getter and setter methods.

22. What is the main advantage of Encapsulation?

a) It allows direct modification of an object's internal state.

b) It ensures data integrity and provides better control over data access.

c) It enables multiple inheritance.

d) It eliminates the need for constructors.

Answer: b) It ensures data integrity and provides better control over data access.

23. Which of the following is a key characteristic of static methods?

a) They can access both static and non-static members of the class.

b) They can be overridden by subclasses.

c) They belong to the class, not to a specific object, and can be called using the
class name.

d) They must always return a value.

Answer: c) They belong to the class, not to a specific object, and can be called
using the class name.
24. If a class is declared final, what does it imply?

a) All its methods are implicitly final.

b) It cannot be inherited by any other class.

c) It cannot have any instance variables.

d) Its objects cannot be modified after creation.

Answer: b) It cannot be inherited by any other class.

25. What is constructor chaining in Java?

a) The process of calling a constructor from a regular method.

b) The automatic execution of constructors by the JVM in a specific order.

c) Calling one constructor from another constructor using this() or super().

d) Creating multiple objects in a single line of code.

Answer: c) Calling one constructor from another constructor using this() or


super().

26. Which of the following is true about this() and super() calls in constructors?

a) Both this() and super() can appear anywhere in a constructor body.

b) Only this() can be used, super() is deprecated.

c) If used, both this() and super() must be the first statement in the constructor
body.

d) A constructor can contain both this() and super().

Answer: c) If used, both this() and super() must be the first statement in the
constructor body. (A constructor cannot contain both, as only one can be the first
statement.)
27. What is polymorphism demonstrated by the following code snippet?

Animal myAnimal = new Dog(); // Dog is a subclass of Animal

[Link](); // Invokes Dog's makeSound()

a) Compile-time polymorphism (Method Overloading)

b) Runtime polymorphism (Method Overriding)

c) Encapsulation

d) Inheritance

Answer: b) Runtime polymorphism (Method Overriding)

28. Which keyword is used by a class to inherit from another class?

a) implements

b) uses

c) extends

d) inherits

Answer: c) extends

29. If a method in a subclass has the same name and parameters as a method
in its superclass, what is this an example of?

a) Method Overloading

b) Method Hiding

c) Method Overriding

d) Constructor Chaining

Answer: c) Method Overriding


30. Which of the following is TRUE about abstract methods?

a) They must provide a complete implementation.

b) They can only be declared in regular (non-abstract) classes.

c) They are declared without an implementation and must be implemented by


concrete subclasses.

d) They can be static.

Answer: c) They are declared without an implementation and must be


implemented by concrete subclasses.

31. If a class contains at least one abstract method, what must be true about
that class?

a) It must implement an interface.

b) It must be declared as final.

c) It must be declared as abstract.

d) It cannot have any constructors.

Answer: c) It must be declared as abstract.


32. What is a key difference between an abstract class and an interface?

a) An abstract class can be instantiated, an interface cannot.

b) An abstract class can have concrete methods, an interface (traditionally) only


has abstract methods.

c) An interface can have instance variables, an abstract class cannot.

d) A class can extend multiple abstract classes, but can only implement one
interface.

Answer: b) An abstract class can have concrete methods, an interface


(traditionally) only has abstract methods. (Interfaces in Java 8+ can have default
and static methods, but still no instance variables.)

33. A class A has a non-static inner class B. Which of the following is true?

a) An object of B can be created without creating an object of A.

b) An object of B can only access static members of A.

c) An object of B needs an object of A to be created first, and can access all


members of A.

d) Class B cannot have its own constructor.

Answer: c) An object of B needs an object of A to be created first, and can access


all members of A.
34. How does Java achieve "multiple inheritance" of behavior?

a) By allowing a class to extend multiple classes.

b) By allowing a class to implement multiple interfaces.

c) By using constructor chaining.

d) By declaring all methods as static.

Answer: b) By allowing a class to implement multiple interfaces.

35. Consider the following code:

interface Flyable { void fly(); }

class Bird implements Flyable {

public void fly() { [Link]("Bird flying"); }

class Plane implements Flyable {

public void fly() { [Link]("Plane flying"); }

public class Test {

public static void main(String[] args) {

Flyable f1 = new Bird();

Flyable f2 = new Plane();

[Link]();

[Link]();

}
What OOP concept is primarily demonstrated here?

a) Encapsulation

b) Inheritance

c) Polymorphism

d) Abstraction

Answer: c) Polymorphism (Specifically, runtime polymorphism via interfaces).

36. Which of the following is the most suitable for defining a contract that
multiple unrelated classes must adhere to?

a) A concrete class

b) An abstract class

c) An interface

d) A static class

Answer: c) An interface

37. If a constructor calls this(args) for constructor chaining, where does the
super() call (implicit or explicit) occur?

a) super() is automatically invoked before the this(args) call within the chained
constructor.

b) super() is automatically invoked after the this(args) call within the chained
constructor.

c) super() is handled by the constructor that this(args) eventually calls, making it


the first statement in that constructor.

d) super() is not called at all if this() is used.

Answer: c) super() is handled by the constructor that this(args) eventually calls,


making it the first statement in that constructor.
38. What is the output of the following code snippet?

class A {

A() { [Link]("A"); }

class B extends A {

B() { [Link]("B"); }

class C extends B {

C() { [Link]("C"); }

public static void main(String[] args) {

new C();

a) ABC

b) CBA

c) AC

d) BC

Answer: a) ABC (Constructor calls always chain upwards to the superclass first
before executing the current class's constructor body.)
39. You have an abstract class Vehicle and a concrete class Car that extends
Vehicle. If Vehicle has a non-abstract method start(), what is true about
start() in Car?

a) Car must override start().

b) Car cannot access start().

c) Car inherits start() and can use it directly or override it optionally.

d) start() in Vehicle must be private.

Answer: c) Car inherits start() and can use it directly or override it optionally.

40. Which of the following is the most restrictive access modifier?

a) public

b) protected

c) default (no keyword)

d) private

Answer: d) private

Part A: Java Basics (2 Questions)

1. Factorial Calculator (with User Input) Write a Java program that calculates
the factorial of a non-negative integer entered by the user.

o Prompt the user to enter a number.

o Read the integer.

o If the number is negative, print an error message.

o Otherwise, calculate its factorial using a for loop.

o Print the result.


Example Output:

Enter a non-negative number: 5

Factorial of 5 is: 120

Enter a non-negative number: -3

Error: Factorial is not defined for negative numbers.

Solution:

import [Link];

public class FactorialCalculator {

public static void main(String[] args) {

Scanner scanner = new Scanner([Link]);

[Link]("Enter a non-negative number: ");

int num = [Link]();

if (num < 0) {

[Link]("Error: Factorial is not defined for negative numbers.");

} else {

long factorial = 1; // Use long to handle larger factorials

for (int i = 1; i <= num; i++) {

factorial *= i;

[Link]("Factorial of " + num + " is: " + factorial);


}

[Link]();

2. Array and ArrayList Operations Write a Java program that demonstrates the
difference between a fixed-size array and a dynamic ArrayList.

o Part 1: Fixed-Size Array

▪ Declare an integer array named staticNumbers of size 3.

▪ Initialize it with values 10, 20, 30.

▪ Try to add a fourth element (e.g., 40) to staticNumbers at index


3. What happens? (Describe the error in a comment in your
code).

▪ Print all elements of staticNumbers using a for-each loop.

o Part 2: ArrayList

▪ Declare an ArrayList of String named dynamicNames.

▪ Add "Alice", "Bob", "Charlie" to dynamicNames.

▪ Add "David" to dynamicNames.

▪ Print the dynamicNames ArrayList.

▪ Remove "Bob" from dynamicNames.

▪ Print the dynamicNames ArrayList again.

▪ Insert "Eve" at the beginning of dynamicNames.

▪ Print the dynamicNames ArrayList one last time.

Solution:
import [Link];

import [Link]; // For printing array directly

public class ArrayVsArrayList {

public static void main(String[] args) {

[Link]("--- Part 1: Fixed-Size Array ---");

int[] staticNumbers = new int[3]; // Declares an array of size 3

staticNumbers[0] = 10;

staticNumbers[1] = 20;

staticNumbers[2] = 30;

// Try to add a fourth element (e.g., 40) at index 3

// staticNumbers[3] = 40; // This would cause an


ArrayIndexOutOfBoundsException at runtime

[Link]("Elements of staticNumbers:");

for (int num : staticNumbers) {

[Link](num + " ");

[Link]("\n(Attempting to add element at index 3 would result in


ArrayIndexOutOfBoundsException because arrays have a fixed size after
creation.)");
[Link]("\n--- Part 2: ArrayList ---");

ArrayList<String> dynamicNames = new ArrayList<>(); // Diamond operator <>


for type inference

[Link]("Adding Alice, Bob, Charlie:");

[Link]("Alice");

[Link]("Bob");

[Link]("Charlie");

[Link]("Current list: " + dynamicNames); // [Alice, Bob, Charlie]

[Link]("Adding David:");

[Link]("David");

[Link]("Current list: " + dynamicNames); // [Alice, Bob, Charlie,


David]

[Link]("Removing Bob:");

[Link]("Bob"); // Removes by object value

// [Link](1); // Would remove by index if using int

[Link]("Current list: " + dynamicNames); // [Alice, Charlie, David]

[Link]("Inserting Eve at the beginning (index 0):");

[Link](0, "Eve"); // Insert at specific index


[Link]("Current list: " + dynamicNames); // [Eve, Alice, Charlie,
David]

Part B: Object-Oriented Programming (2 Questions)

1. Bank Account Management with Advanced Encapsulation and


Polymorphism

Design a banking system with a base Account class and two subclasses:
SavingsAccount and CheckingAccount.

o Account Class (Abstract):

▪ Private attributes: String accountNumber, double balance.

▪ Constructor to initialize accountNumber and balance.

▪ Public getAccountNumber() and getBalance() methods.

▪ Abstract methods: deposit(double amount) and


withdraw(double amount).

▪ A concrete method displayAccountInfo() that prints account


number and balance.

o SavingsAccount Class (Concrete):

▪ Extends Account.

▪ Private attribute: double interestRate.

▪ Constructor: Takes accountNumber, balance, interestRate. Calls


super constructor.

▪ Overrides deposit(): Adds the amount to the balance.


▪ Overrides withdraw():

▪ If amount is positive and balance - amount >= 0, deducts


amount.

▪ Otherwise, prints "Insufficient funds or invalid


withdrawal amount."

▪ A method applyInterest() that calculates interest and adds it to


the balance.

o CheckingAccount Class (Concrete):

▪ Extends Account.

▪ Private attribute: double transactionFee.

▪ Constructor: Takes accountNumber, balance, transactionFee.


Calls super constructor.

▪ Overrides deposit(): Adds the amount to the balance.

▪ Overrides withdraw():

▪ If amount is positive and balance - amount -


transactionFee >= 0, deducts amount and
transactionFee.

▪ Otherwise, prints "Insufficient funds (including fee) or


invalid withdrawal amount."

o Main Class:

▪ Create objects of SavingsAccount and CheckingAccount.

▪ Use Account type references to store these objects


(demonstrate polymorphism).

▪ Perform a series of deposits and withdrawals on both account


types.
▪ Call applyInterest() on the SavingsAccount.

▪ Call displayAccountInfo() for both accounts at different stages.

Example Flow (Illustrative, your output should reflect actual transactions):

Section 3: Answer Key

Part A: Coding Questions (Sample Solutions)

Part B: Object-Oriented Programming (2 Questions)

1. Student Management with Encapsulation Create a Java class named


Student with the following private attributes:

o String name

o int id

o int age

Implement the following:

o A constructor that takes name, id, and age as parameters and


initializes the attributes.

o Public getter and setter methods for all attributes.

▪ For the age setter, add a validation: if age is less than or equal
to 0, print an error message and do not update the age.

o A method displayStudentInfo() that prints the student's name, ID,


and age.

In a Main class, demonstrate the usage:

o Create a Student object.


o Use the setter methods to try setting a valid age and an invalid age.

o Use the getter methods to retrieve and print the student's name
and ID.

o Call displayStudentInfo().

Example Output:

Student created: Alice (ID: 101, Age: 20)

Age cannot be negative or zero.

Student Name: Alice

Student ID: 101

Student Information:

Name: Alice

ID: 101

Age: 25

Solution:

[Link]

public class Student {

private String name;

private int id;

private int age;

// Constructor

public Student(String name, int id, int age) {


[Link] = name;

[Link] = id;

setAge(age); // Use setter for initial age to apply validation

[Link]("Student created: " + [Link] + " (ID: " + [Link] + ",


Age: " + [Link] + ")");

// Getter for name

public String getName() {

return name;

// Setter for name

public void setName(String name) {

[Link] = name;

// Getter for id

public int getId() {

return id;

}
// Setter for id

public void setId(int id) {

[Link] = id;

// Getter for age

public int getAge() {

return age;

// Setter for age with validation

public void setAge(int age) {

if (age > 0) {

[Link] = age;

} else {

[Link]("Age cannot be negative or zero.");

// Method to display student information

public void displayStudentInfo() {

[Link]("Student Information:");
[Link]("Name: " + name);

[Link]("ID: " + id);

[Link]("Age: " + age);

public class Main {

public static void main(String[] args) {

// Create a Student object

Student student1 = new Student("Alice", 101, 20);

// Use setter methods

[Link](25); // Set a valid age

[Link](-5); // Try setting an invalid age (should print error)

// Use getter methods

[Link]("Student Name: " + [Link]());

[Link]("Student ID: " + [Link]());

// Call displayStudentInfo()

[Link]();

}
2. Shape Hierarchy with Polymorphism and Abstract Class Create an abstract
class Shape with:

o An abstract method calculateArea() that returns a double.

o An abstract method calculatePerimeter() that returns a double.

o A concrete method displayMessage() that prints "This is a shape.".

Create two concrete subclasses that extends Shape:

o Circle:

▪ Private attribute double radius.

▪ Constructor to initialize radius.

▪ Implement calculateArea() (π * radius * radius).

▪ Implement calculatePerimeter() (2 * π * radius).

o Rectangle:

▪ Private attributes double length, double width.

▪ Constructor to initialize length and width.

▪ Implement calculateArea() (length * width).

▪ Implement calculatePerimeter() (2 * (length + width)).

In a Main class:

o Create objects of Circle and Rectangle.

o Use Shape references to hold these objects (demonstrating


polymorphism).

o Call displayMessage(), calculateArea(), and calculatePerimeter() for


both objects.

Example Output:
--- Circle ---

This is a shape.

Area: 78.5398...

Perimeter: 31.4159...

--- Rectangle ---

This is a shape.

Area: 50.0

Perimeter: 30.0

Solution:

abstract class Shape {

// Abstract methods (must be implemented by concrete subclasses)

public abstract double calculateArea();

public abstract double calculatePerimeter();

// Concrete method

public void displayMessage() {

[Link]("This is a shape.");

class Circle extends Shape {

private double radius;


public Circle(double radius) {

[Link] = radius;

@Override

public double calculateArea() {

return [Link] * radius * radius;

@Override

public double calculatePerimeter() {

return 2 * [Link] * radius;

[Link]

Java

class Rectangle extends Shape {

private double length;

private double width;

public Rectangle(double length, double width) {


[Link] = length;

[Link] = width;

@Override

public double calculateArea() {

return length * width;

@Override

public double calculatePerimeter() {

return 2 * (length + width);

public class Main {

public static void main(String[] args) {

// Create objects of Circle and Rectangle using Shape references


(Polymorphism)

Shape myCircle = new Circle(5.0);

Shape myRectangle = new Rectangle(10.0, 5.0);

[Link]("--- Circle ---");


[Link]();

[Link]("Area: " + [Link]());

[Link]("Perimeter: " + [Link]());

[Link]("\n--- Rectangle ---");

[Link]();

[Link]("Area: " + [Link]());

[Link]("Perimeter: " + [Link]());

You might also like