Exam 1 Study Guide Flashcards

1
Q

What is a constructor?

A

A special method in Java that is used to initialize objects when they are created. It is automatically called when an object is instantiated using the ‘new’ keyword.

Example:

class Car {
Car() { // Constructor has the same name as the class
System.out.println(“Car object created!”);
}
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is a Parameterized Constructor?

A

A constructor that accepts arguments.

Example:

class Car{
private String name;

public Car(String name);
this.name = name;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Copy Constructor

A

A constructor that takes another object as the argument. Basically it copies.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is a Singleton?

A

A creational design pattern that ensures that only one instance of its kind exists. It provides a single point of access to it.

  • Restricts Multiple Instances
  • Global Access Point
  • Lazy or Eager Initialization
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

When is a Singleton useful?

A

-Database connections
-Logging systems
-Configuration settings
-Thread pools

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Downsides of Singleton

A
  • Tight Coupling
  • Hidden Dependencies
  • Difficult to debug
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Benefits of Singleton

A
  • Control Over Instance Creation
  • Memory Efficiency
  • Thread Safety
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What are access modifiers in Java?

A

Access modifiers control the visibility and accessibility of classes, methods, and variables. They define which other classes can interact with a given field or method.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Scope of ‘public’ access modifier

A

Everywhere. Inside and outside the package

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Scope of ‘Protected’ access modifier

A

Same package + subclasses

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Scope of ‘private’ access modifier

A

Only within the same class

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Scope of the default access modifier (no access modifier)

A

Only within the same package.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is the purpose of the ‘final’ modifier?

A

The ‘final’ modifier restricts modifications to variables, methods, and classes

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Example of ‘final’ modifier in variables

A

class Example {
public static void main(String[] args) {
final int number = 10;
number = 20; // ❌ ERROR: Cannot reassign a final variable
}
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

‘final’ modifier with methods

A

class Parent {
final void show() {
System.out.println(“This is a final method.”);
}
}

class Child extends Parent {
void show() { // ❌ ERROR: Cannot override a final method
System.out.println(“Overriding attempt!”);
}
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

‘final’ modifier with classes

A

final class Animal {
void makeSound() {
System.out.println(“Animal makes sound”);
}
}

class Dog extends Animal { // ❌ ERROR: Cannot extend a final class
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What is the purpose of the ‘static’ modifier

A

‘static’ keyword is used to define class-level members, meaning they belong to the class itself rather than an instance. A static variable is shared across all instances of the class.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

‘static’ with variables

A

‘static’ varibales are shared across all instances of the class:

class Example {
static int count = 0; // Shared among all instances

Example() {
    count++; // Increments for each new object
}

public static void main(String[] args) {
    Example obj1 = new Example();
    Example obj2 = new Example();
    System.out.println(Example.count); // Output: 2
} }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

‘static’ with Methods

A

‘static’ method belongs to the class and can be called without creating an object.

class Utility {
static void greet() {
System.out.println(“Hello, World!”);
}
}

public class Test {
public static void main(String[] args) {
Utility.greet(); // ✅ No need to create an object
}
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What is the strategy design pattern?

A

A behavioral design pattern that allows you to define a family of algorithms and select them at run time without modifying the client code.

21
Q

Benefits of the strategy design pattern?

A

Helps achieve loose coupling and follows the open-closed principle (modify behavior without modifying existing code)

Also avoids many if-else or switch statements.

You want to switch algorithms at runtime.

22
Q

Scenario when the Strategy design pattern would be useful?

A

An e-commerce application where users can pay using Credit Card, Paypal, or Bitcoin. The Strategy design pattern allows us to switch between these payment methods dynamically.

23
Q

How does the Strategy Pattern Improve Code Flexibility and Maintainability?

A

*Encapsulation of Behavior - Logic is in separate strategy classes, making it easier to manage.

*Supports Open-Closed Principle (OCP) - New methods can be added without modifying existing code.

*Eliminates Complex Conditionals - No need for multiple if-else or switch statements

*Increases Reusability - Each strategy can be reused independently

*Enhances Testability - Individual strategies can be tested separately without affecting the main method

24
Q

What job would the Strategy Pattern be good for?

A

When you need to perform the same job but with different approaches (or inputs). Instead of hardcoding multiple behaviors into a single class, you encapsulate them into separate strategy classes, making it easier to switch, extend and maintain different implementations dynamically.

25
Sorting method used by Comparable?
compareTo(T o) -Compare this to other -Compares in a fixed order (natural order which is smallest to largest)
26
When would you use Comparable vs Comparator?
-Use Comparable when the object has a natural sorting order (Sorting by age) -Use Comparator when you need multiple ways of sorting (Sorting by age and then by name)
27
What is exception handling?
Exception handling is a way to manage errors in a Java program without crashing the application.
28
What happens during exception handling?
When an error occurs, Java creates an exception object that contains details about the error. We use exception handling to catch, handle, and respond to these errors gracefully.
29
Exception Example: Division by Zero
Code: int result = 10 / 0; // ❌ ERROR: Division by zero! Java will throw an exception (ArithmeticException) and stops execution
30
What is the try-catch concept?
The 'try' block contains code that might cause an exception (error). The 'catch' block handles the error if an exception occurs. try-catch structure: try { // Code that may cause an exception } catch (ExceptionType e) { // Code that handles the exception }
31
try-catch example: Handling Division by Zero
public class TryCatchExample { public static void main(String[] args) { try { int result = 10 / 0; // ❌ Error: Division by zero } catch (ArithmeticException e) { System.out.println("Cannot divide by zero!"); } System.out.println("Program continues..."); } }
32
What happens if there is no 'try-catch'?
If you don't handle exceptions, Java stops execution immediately: public class NoTryCatch { public static void main(String[] args) { int result = 10 / 0; // ❌ Program crashes here System.out.println("This won't print!"); } }
33
What does the 'try' block contain?
Contains code that might cause an exception.
34
What does the 'catch' block handle?
Handles exceptions that occur in try.
35
What does the 'throw' keyword do?
Manually throws an exception.
36
What does the 'throws' keyword do?
Declares that a method might throw an exception. This forces the calling code to handle or propagate the exception, making the program more robust and modular.
37
What does the 'finally' block do?
It always runs, even if an exception occurs or not. Used for cleanup (closing files)
38
What is the Factory design pattern?
A creational design pattern that provides a centralized method for creating objects without exposing the instantiation logic. Instead of using 'new' to create objects directly, a factory method decides which object to return based on input parameters.
39
Benefits of the Factory design pattern.
- Encapsulates object creation (hides 'new' keyword usage) -Simplifies code maintenance by centralizing object creation in one place. -Provides flexibility by allowing new object types without modifying existing code.
40
Downsides of the Factory pattern
- Instead of simply using 'new' to create objects, you now have a separate factory class. - More code and extra abstraction can make simple programs harder to read.
41
What is the Simple Factory design pattern variation?
1. Simple Factory - Contains a static method that creates and returns objects based on inputs. Downsides: -Violates the Open-Closed Principle - Every new object type requires modifying the factory
42
What is the Polymorphic Factory Variation?
Each subclass provides its own implementation of the factory method. Instead of a single factory class, the subclasses decide which object to create.
43
What is the Abstract Factory variation?
Creates factories that produce related objects (families of objects). Instead of directly creating objects, it creates other factories, each dedicated toa family of related objects.
44
What is Polymorphism in Object-Oriented Programming?
Allows one interface to be used for multiple data types. It lets objects take many forms, meaning a single method, class, or interface can behave differently depending on the object calling it.
45
What is method overloading?
Multiple methods with the same name but different parameters.
46
When does method overloading occur?
Compile-time
47
When does method overriding occur?
Runtime
48
When to use an Interface? (implements)
- When you need multiple inheritance - You want to enforce a contract - Different classes need the same behavior, but they are not related. - You want loose coupling
49
When to use Inheritance (extends)
- One class is a specialized version of another (e.g., a Dog is an Animal) - You want to reuse common behavior without redefining it. - Subclasses should inherit common fields and methods - The child class should override (or extend) only some behavior of the parent class.