0% found this document useful (0 votes)
1 views

Chapter 2 4 Java

Uploaded by

dawit kassa
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Chapter 2 4 Java

Uploaded by

dawit kassa
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 173

Q&A on Wrapper Classes in Java

Q1: What is a Wrapper Class in Java?


A: A wrapper class in Java is a class that encapsulates a primitive
data type into an object. This allows primitives to be treated as
objects, enabling them to be used in situations where objects are
required, such as in collections.
Q2: What are the main wrapper classes in Java?
A: The main wrapper classes corresponding to primitive types are:
 Integer for int
 Double for double
 Character for char
 Boolean for boolean
 Byte for byte
 Short for short
 Long for long
 Float for float
Q3: Why use Wrapper Classes?
A: Wrapper classes are used for:
 Object manipulation: Collections (like ArrayList) can store only
objects.
 Null values: They can hold a null value, unlike primitives.
 Utility methods: Wrapper classes provide useful methods for
converting and manipulating data.
Q4: How to create a Wrapper Class?
A: You can create a wrapper object by using the constructor or
autoboxing.
Example of Autoboxing:
java
Copy
int num = 10;
Integer wrappedNum = num; // Autoboxing
Q5: How to retrieve the primitive value from a Wrapper
Class?
A: You can retrieve the primitive value using unboxing.
Example of Unboxing:
java
Copy
Integer wrappedNum = 10; // Autoboxing
int num = wrappedNum; // Unboxing
Example Code
Here's a simple example demonstrating the use of wrapper classes:
java

Java (OOP) 1
Copy
import java.util.ArrayList;

public class WrapperClassExample {


public static void main(String[] args) {
// Autoboxing: converting a primitive to an Integer object
Integer intObj = 42;
Double doubleObj = 3.14;

// Unboxing: converting an Integer object back to a primitive


int primitiveInt = intObj;

// Using wrapper classes in a collection


ArrayList<Integer> intList = new ArrayList<>();
intList.add(intObj); // Adds the Integer object
intList.add(100); // Autoboxing of primitive int to Integer

// Displaying the values


System.out.println("Integer object: " + intObj);
System.out.println("Primitive int: " + primitiveInt);
System.out.println("ArrayList of Integers: " + intList);
}
}
Explanation of the Example
1. Autoboxing: The primitive int is automatically converted to
an Integer object when assigned.
2. Unboxing: The Integer object is automatically converted back
to the primitive int.
3. ArrayList: An ArrayList is created to store Integer objects,
demonstrating how wrapper classes can be used in collections.

Q&A on Wrapper Class: Autoboxing vs. Unboxing in Java


Q1: What is Autoboxing in Java?
A: Autoboxing is the automatic conversion of a primitive data type
into its corresponding wrapper class object. This happens when a
primitive is assigned to a variable of a wrapper type.
Q2: What is Unboxing in Java?
A: Unboxing is the automatic conversion of a wrapper class object
back to its corresponding primitive type. This occurs when an object
of a wrapper class is assigned to a variable of a primitive type.
Q3: Why are Autoboxing and Unboxing useful?
A: They allow for seamless integration of primitive types with
collection classes (like ArrayList), which can only store objects. This
makes it easier to work with numerical and character data in a more
flexible way.
Java (OOP) 2
Example Code
Here's a simple example demonstrating both autoboxing and
unboxing:
java
Copy
import java.util.ArrayList;

public class AutoboxingUnboxingExample {


public static void main(String[] args) {
// Autoboxing: converting primitive types to wrapper class objects
int primitiveInt = 42;
Integer wrappedInt = primitiveInt; // Autoboxing

double primitiveDouble = 3.14;


Double wrappedDouble = primitiveDouble; // Autoboxing

// Displaying the results of autoboxing


System.out.println("Autoboxing:");
System.out.println("Primitive int: " + primitiveInt);
System.out.println("Wrapped Integer: " + wrappedInt);
System.out.println("Primitive double: " + primitiveDouble);
System.out.println("Wrapped Double: " + wrappedDouble);

// Using wrapper objects in a collection


ArrayList<Integer> intList = new ArrayList<>();
intList.add(wrappedInt); // Adding wrapped Integer
intList.add(100); // Autoboxing of primitive int to Integer

// Unboxing: converting wrapper class objects back to primitive types


Integer anotherWrappedInt = intList.get(0); // Getting Integer object
int unwrappedInt = anotherWrappedInt; // Unboxing

// Displaying the results of unboxing


System.out.println("\nUnboxing:");
System.out.println("Wrapped Integer from ArrayList: " +
anotherWrappedInt);
System.out.println("Unwrapped int: " + unwrappedInt);
}
}
Explanation of the Example
1. Autoboxing:
 The primitive int and double are automatically converted
into their respective wrapper objects (Integer and Double).
2. Displaying Results: The values of both primitive and
wrapped types are printed to the console.
3. Using Collections: An ArrayList is used to store Integer objects,
demonstrating how autoboxing allows primitives to be added
directly.
4. Unboxing:

Java (OOP) 3
 The Integer object is retrieved from the ArrayList and
automatically converted back to a primitive int.
Summary
 Autoboxing: Automatic conversion from primitive to wrapper
object.
 Unboxing: Automatic conversion from wrapper object to
primitive.
These features make Java more flexible when dealing with primitive
types and objects, particularly in collections. If you have more
questions or need further clarification, feel free to ask!

Q&A on Wrapper Class: Autoboxing vs. Unboxing in Java


Q1: What is a Wrapper Class in Java?
A: A wrapper class in Java is a class that encapsulates a primitive
data type into an object. This allows primitives to be treated as
objects, which is useful for collections and utility methods.

Q2: What is Autoboxing?


A: Autoboxing is the process of automatically converting a primitive
type into its corresponding wrapper class. This occurs when a
primitive is assigned to a wrapper class reference.
Illustration:
 Primitive int → Wrapper Integer
 Primitive double → Wrapper Double
Example:
java
Copy
int num = 10;
Integer wrappedNum = num; // Autoboxing

Q3: What is Unboxing?


A: Unboxing is the reverse process of autoboxing, where a wrapper
class object is automatically converted back to its corresponding
primitive type.
Illustration:
 Wrapper Integer → Primitive int
 Wrapper Double → Primitive double
Example:
java
Copy
Java (OOP) 4
Integer wrappedNum = 10; // Autoboxing
int num = wrappedNum; // Unboxing

Q4: Why are Autoboxing and Unboxing useful?


A: They enable seamless integration of primitive types with
collections (like ArrayList), which can only store objects. This allows
developers to work with primitive data types in a flexible and
convenient manner.

Example Code with Detailed Illustrations


Here's a more comprehensive example to illustrate both autoboxing
and unboxing:
java
Copy
import java.util.ArrayList;

public class AutoboxingUnboxingExample {


public static void main(String[] args) {
// Autoboxing: converting primitive types to wrapper class objects
int primitiveInt = 42; // Primitive int
Integer wrappedInt = primitiveInt; // Autoboxing
System.out.println("Autoboxing:");
System.out.println("Primitive int: " + primitiveInt); // 42
System.out.println("Wrapped Integer: " + wrappedInt); // 42

// Adding wrapped Integer into an ArrayList


ArrayList<Integer> intList = new ArrayList<>();
intList.add(wrappedInt); // Adding wrapped Integer
intList.add(100); // Autoboxing of primitive int to Integer

System.out.println("\nArrayList contents after autoboxing:");


System.out.println(intList); // [42, 100]

// Unboxing: converting wrapper class objects back to primitive types


Integer anotherWrappedInt = intList.get(0); // Getting Integer object
int unwrappedInt = anotherWrappedInt; // Unboxing
System.out.println("\nUnboxing:");
System.out.println("Wrapped Integer from ArrayList: " +
anotherWrappedInt); // 42
System.out.println("Unwrapped int: " + unwrappedInt); // 42

// Further illustration with Double


double primitiveDouble = 3.14;
Double wrappedDouble = primitiveDouble; // Autoboxing
System.out.println("\nAutoboxing Double:");
System.out.println("Primitive double: " + primitiveDouble); // 3.14
System.out.println("Wrapped Double: " + wrappedDouble); // 3.14

// Unboxing Double
Double anotherWrappedDouble = 5.67; // Autoboxing
double unwrappedDouble = anotherWrappedDouble; // Unboxing

Java (OOP) 5
System.out.println("\nUnboxing Double:");
System.out.println("Wrapped Double: " + anotherWrappedDouble); //
5.67
System.out.println("Unwrapped double: " + unwrappedDouble); // 5.67
}
}
Explanation of the Example
1. Autoboxing:
 The primitive int (42) is automatically converted to
an Integer object.
 The ArrayList can only store objects,
so intList.add(100) demonstrates that a primitive int can be
directly added due to autoboxing.
2. Displaying Results:
 The contents of the ArrayList are printed to show the result
of autoboxing.
3. Unboxing:
 The Integer object is retrieved from the ArrayList and
converted back to a primitive int.
 Similarly, a Double object is demonstrated with autoboxing
and unboxing.
Summary
 Autoboxing: Automatic conversion from primitive to wrapper
object.
 Unboxing: Automatic conversion from wrapper object to
primitive.

Q&A on Variables in Java


Q1: What is a Variable in Java?
A: A variable in Java is a container that holds data that can be
changed during program execution. Each variable has a type, which
defines the kind of data it can store.

Q2: What are the Types of Variables in Java?


A: Java has three main types of variables:
1. Local Variables: Defined within a method or block and
accessible only within that method/block.

Java (OOP) 6
2. Instance Variables: Defined inside a class but outside any
method. Each object of the class has its own instance
variables.
3. Static Variables: Defined with the static keyword. These
variables are shared among all instances of a class.

Q3: How to Declare a Variable in Java?


A: To declare a variable, specify the type followed by the variable
name. Optionally, you can initialize it with a value.
Example:
java
Copy
int age; // Declaration
age = 25; // Initialization
You can also combine both steps:
java
Copy
int age = 25; // Declaration and initialization

Example Code
Here's a simple example demonstrating different types of variables:
java
Copy
public class VariableExample {
// Instance variable
String name;

// Static variable
static int objectCount = 0;

// Constructor
public VariableExample(String name) {
this.name = name; // Initializing instance variable
objectCount++; // Incrementing static variable
}

// Method to display information


public void displayInfo() {
// Local variable
String greeting = "Hello"; // Declaration and initialization
System.out.println(greeting + ", " + name + "!");
}

public static void main(String[] args) {


VariableExample obj1 = new VariableExample("Alice");
obj1.displayInfo(); // Output: Hello, Alice!

VariableExample obj2 = new VariableExample("Bob");


obj2.displayInfo(); // Output: Hello, Bob!

Java (OOP) 7
System.out.println("Total objects created: " +
VariableExample.objectCount); // Output: 2
}
}
Explanation of the Example
1. Instance Variable:
 String name: This variable belongs to each instance
of VariableExample. Each object can have a different name.
2. Static Variable:
 static int objectCount: This variable is shared across all
instances of the class. It counts how many objects have
been created.
3. Local Variable:
 String greeting: This variable is declared within
the displayInfo method and can only be accessed there. It
is initialized each time the method is called.
4. Constructors and Methods:
 The constructor initializes the name and increments
the objectCount each time a new object is created.
 The displayInfo method uses the local variable to print a
greeting.
Summary
 Local Variables: Accessible only within their method/block.
 Instance Variables: Unique to each object of a class.
 Static Variables: Shared among all instances of a class.
Variables are essential in Java for storing and manipulating data,
enabling dynamic programming.

Q&A on Operators in Java


Q1: What is an Operator in Java?
A: An operator in Java is a special symbol that performs operations
on one, two, or three operands and produces a result. Operators are
essential for manipulating data and variables.

Q2: What are the Types of Operators in Java?


A: Java operators can be categorized into several types:
1. Arithmetic Operators: Used for mathematical calculations.
2. Relational Operators: Used to compare two values.
3. Logical Operators: Used to perform logical operations.

Java (OOP) 8
4. Bitwise Operators: Operate on bits and perform bit-by-bit
operations.
5. Assignment Operators: Used to assign values to variables.
6. Unary Operators: Operate on a single operand.
7. Ternary Operator: A shorthand form of the if-else statement.

Example Code
Here’s a comprehensive example illustrating different types of
operators:
java
Copy
public class OperatorsExample {
public static void main(String[] args) {
// Arithmetic Operators
int a = 10, b = 5;
System.out.println("Arithmetic Operators:");
System.out.println("Addition: " + (a + b)); // 15
System.out.println("Subtraction: " + (a - b)); // 5
System.out.println("Multiplication: " + (a * b)); // 50
System.out.println("Division: " + (a / b)); // 2
System.out.println("Modulus: " + (a % b)); // 0

// Relational Operators
System.out.println("\nRelational Operators:");
System.out.println("a is greater than b: " + (a > b)); // true
System.out.println("a is less than or equal to b: " + (a <= b)); //
false

// Logical Operators
boolean x = true, y = false;
System.out.println("\nLogical Operators:");
System.out.println("x AND y: " + (x && y)); // false
System.out.println("x OR y: " + (x || y)); // true
System.out.println("NOT x: " + !x); // false

// Bitwise Operators
int m = 5; // 0101 in binary
int n = 3; // 0011 in binary
System.out.println("\nBitwise Operators:");
System.out.println("m & n: " + (m & n)); // 1 (0001)
System.out.println("m | n: " + (m | n)); // 7 (0111)
System.out.println("m ^ n: " + (m ^ n)); // 6 (0110)

// Assignment Operators
int num = 10;
System.out.println("\nAssignment Operators:");
num += 5; // Equivalent to num = num + 5
System.out.println("After num += 5: " + num); // 15

// Unary Operators
System.out.println("\nUnary Operators:");

Java (OOP) 9
int increment = 5;
System.out.println("Increment: " + (++increment)); // 6 (pre-
increment)
System.out.println("Decrement: " + (--increment)); // 5 (pre-
decrement)

// Ternary Operator
int result = (a > b) ? a : b; // If a > b, result = a; else result =
b
System.out.println("\nTernary Operator:");
System.out.println("Max of a and b: " + result); // 10
}
}
Explanation of the Example
1. Arithmetic Operators:
 Perform basic mathematical operations: addition,
subtraction, multiplication, division, and modulus.
2. Relational Operators:
 Compare two values, returning a boolean result
(true or false). For example, a > b checks if a is greater
than b.
3. Logical Operators:
 Combine boolean expressions. The && operator
returns true only if both operands are true.
4. Bitwise Operators:
 Operate on the binary representations of numbers. For
example, m & n performs a bitwise AND operation.
5. Assignment Operators:
 Assign values to variables. The += operator adds the right
operand to the left operand and assigns the result to the
left operand.
6. Unary Operators:
 Operate on a single operand. The increment operator +
+ increases the value by 1, while the decrement
operator -- decreases it by 1.
7. Ternary Operator:
 A shorthand for an if-else statement. It evaluates a
boolean expression and assigns one of two values based
on the result.
Summary
Operators in Java are powerful tools for performing various
operations on data. Understanding how to use different types of
operators effectively is crucial for writing efficient and functional
code.

Java (OOP) 10
Here’s a detailed overview of the various operator categories in
Java, along with the corresponding symbols (signs) and illustrations
for each type.
1. Arithmetic Operators
These operators perform basic mathematical operations.
Symb Examp
Operator Description
ol le

Addition + Adds two operands a + b

Subtracts the second operand


Subtraction - a - b
from the first

Multiplicati * Multiplies two operands a * b


on

Divides the numerator by the


Division / a / b
denominator

Modulus % Returns the remainder of division a % b

Illustration:
java
Copy
int a = 10, b = 3;
System.out.println("Addition: " + (a + b)); // 13
System.out.println("Subtraction: " + (a - b)); // 7
System.out.println("Multiplication: " + (a * b)); // 30
System.out.println("Division: " + (a / b)); // 3
System.out.println("Modulus: " + (a % b)); // 1

2. Relational Operators
These operators compare two values and return a boolean result.
Symb Examp
Operator Description
ol le

Checks if left operand is


Greater Than > a > b
greater than right

Less Than < Checks if left operand is less a < b

Java (OOP) 11
Symb Examp
Operator Description
ol le

than right

Greater Than or >=


Checks if left operand is a >= b
Equal To greater than or equal to right

Less Than or <=


Checks if left operand is less a <= b
Equal To than or equal to right

Checks if two operands are


Equal To == a == b
equal

Checks if two operands are


Not Equal To != a != b
not equal
Illustration:
java
Copy
int a = 10, b = 5;
System.out.println("a > b: " + (a > b)); // true
System.out.println("a < b: " + (a < b)); // false
System.out.println("a >= b: " + (a >= b)); // true
System.out.println("a <= b: " + (a <= b)); // false
System.out.println("a == b: " + (a == b)); // false
System.out.println("a != b: " + (a != b)); // true

3. Logical Operators
These operators are used to combine boolean expressions.
Operat Symb Examp
Description
or ol le

Returns true if both operands are


AND && x && y
true

OR ` `

Reverses the logical state of its


NOT ! !x
operand
Illustration:
java
Copy
boolean x = true, y = false;

Java (OOP) 12
System.out.println("x && y: " + (x && y)); // false
System.out.println("x || y: " + (x || y)); // true
System.out.println("!x: " + !x); // false

4. Bitwise Operators
These operators perform operations on the binary representations of
integers.
Symb
Operator Description Example
ol

Bitwise AND & Performs AND operation m & n

Performs OR
Bitwise OR ` `
operation

Bitwise XOR ^ Performs XOR operation m ^ n

Bitwise ~ Inverts all bits ~m


Complement

Left Shift << Shifts bits to the left m << 2

Right Shift >> Shifts bits to the right m >> 2

Zero-fill Right >>>


Shifts bits to the right, m >>> 2
Shift filling with zeros
Illustration:
java
Copy
int m = 5; // 0101 in binary
int n = 3; // 0011 in binary
System.out.println("m & n: " + (m & n)); // 1 (0001)
System.out.println("m | n: " + (m | n)); // 7 (0111)
System.out.println("m ^ n: " + (m ^ n)); // 6 (0110)
System.out.println("~m: " + (~m)); // -6 (inverts bits)

5. Assignment Operators
These operators are used to assign values to variables.
Symb Examp
Operator Description
ol le

Assigns the right-hand operand


Assign = a = b
to the left

Java (OOP) 13
Symb Examp
Operator Description
ol le

Add and +=
Adds right operand to left a += b
Assign operand and assigns

Subtract and -=
Subtracts right operand from a -= b
Assign left operand and assigns

Multiply and *=
Multiplies left operand by right a *= b
Assign operand and assigns

Divide and /=
Divides left operand by right a /= b
Assign operand and assigns

Modulus and %=
Takes modulus using two a %= b
Assign operands and assigns
Illustration:
java
Copy
int num = 10;
num += 5; // Equivalent to num = num + 5
System.out.println("After num += 5: " + num); // 15

6. Unary Operators
These operators operate on a single operand.
Symb Examp
Operator Description
ol le

Indicates a positive
Unary Plus + +a
value

Unary - Negates the value -a


Minus

Increases the value ++a or a+


Increment ++
by 1 +

Decremen --
Decreases the value --a or a-
t by 1 -

Illustration:
java
Java (OOP) 14
Copy
int increment = 5;
System.out.println("Increment: " + (++increment)); // 6 (pre-increment)
System.out.println("Decrement: " + (--increment)); // 5 (pre-decrement)

7. Ternary Operator
This is a shorthand for an if-else statement.
Operat Symb
Description Example
or ol

Evaluates a boolean expression condition ?


Ternary ? :
and returns one of two values expr1 : expr2

Illustration:
java
Copy
int a = 10, b = 20;
int max = (a > b) ? a : b; // If a > b, max = a; else max = b
System.out.println("Max of a and b: " + max); // 20

Summary
 Arithmetic Operators: Used for mathematical calculations.
 Relational Operators: Compare two values.
 Logical Operators: Combine boolean expressions.
 Bitwise Operators: Operate on binary representations.
 Assignment Operators: Assign values to variables.
 Unary Operators: Operate on a single operand.
 Ternary Operator: A shorthand for if-else statements.
Understanding these operators is essential for effective
programming in Java.

1. Arithmetic Expressions
Description: Arithmetic expressions use arithmetic operators to
perform calculations.
Illustration:
java
Copy
public class ArithmeticExpressions {
public static void main(String[] args) {
int a = 15;
int b = 4;

// Basic Arithmetic Operations

Java (OOP) 15
int sum = a + b; // Addition
int difference = a - b; // Subtraction
int product = a * b; // Multiplication
int quotient = a / b; // Division
int remainder = a % b; // Modulus

System.out.println("Arithmetic Expressions:");
System.out.println("Sum: " + sum); // 19
System.out.println("Difference: " + difference); // 11
System.out.println("Product: " + product); // 60
System.out.println("Quotient: " + quotient); // 3
System.out.println("Remainder: " + remainder); // 3
}
}
2. Relational Expressions
Description: Relational expressions compare two values and return
a boolean result.
Illustration:
java
Copy
public class RelationalExpressions {
public static void main(String[] args) {
int a = 10;
int b = 20;

// Relational Comparisons
boolean isGreater = a > b; // false
boolean isLess = a < b; // true
boolean isEqual = (a == b); // false
boolean isNotEqual = (a != b); // true
boolean isGreaterOrEqual = (a >= b); // false
boolean isLessOrEqual = (a <= b); // true

System.out.println("Relational Expressions:");
System.out.println("Is a > b? " + isGreater); // false
System.out.println("Is a < b? " + isLess); // true
System.out.println("Is a == b? " + isEqual); // false
System.out.println("Is a != b? " + isNotEqual); // true
System.out.println("Is a >= b? " + isGreaterOrEqual); // false
System.out.println("Is a <= b? " + isLessOrEqual); // true
}
}
3. Logical Expressions
Description: Logical expressions combine boolean values using
logical operators.
Illustration:
java
Copy
public class LogicalExpressions {
public static void main(String[] args) {
boolean x = true;

Java (OOP) 16
boolean y = false;

// Logical Operations
boolean logicalAnd = x && y; // false
boolean logicalOr = x || y; // true
boolean logicalNotX = !x; // false
boolean logicalNotY = !y; // true

System.out.println("Logical Expressions:");
System.out.println("x AND y: " + logicalAnd); // false
System.out.println("x OR y: " + logicalOr); // true
System.out.println("NOT x: " + logicalNotX); // false
System.out.println("NOT y: " + logicalNotY); // true
}
}
4. Bitwise Expressions
Description: Bitwise expressions perform operations on the binary
representations of integers.
Illustration:
java
Copy
public class BitwiseExpressions {
public static void main(String[] args) {
int m = 6; // 0110 in binary
int n = 3; // 0011 in binary

// Bitwise Operations
int bitwiseAnd = m & n; // 2 (0010)
int bitwiseOr = m | n; // 7 (0111)
int bitwiseXor = m ^ n; // 5 (0101)
int bitwiseNotM = ~m; // -7 (inverts bits)
int leftShift = m << 1; // 12 (1100)
int rightShift = m >> 1; // 3 (0011)

System.out.println("Bitwise Expressions:");
System.out.println("m & n: " + bitwiseAnd); // 2
System.out.println("m | n: " + bitwiseOr); // 7
System.out.println("m ^ n: " + bitwiseXor); // 5
System.out.println("~m: " + bitwiseNotM); // -7
System.out.println("m << 1: " + leftShift); // 12
System.out.println("m >> 1: " + rightShift); // 3
}
}
5. Conditional Expressions (Ternary Operator)
Description: The ternary operator evaluates a condition and
returns one of two values based on the result.
Illustration:
java
Copy
public class ConditionalExpressions {
public static void main(String[] args) {

Java (OOP) 17
int a = 10;
int b = 20;

// Conditional (Ternary) Operator


int max = (a > b) ? a : b; // If a > b, max = a; else max = b

System.out.println("Conditional Expression:");
System.out.println("Max of a and b: " + max); // 20
}
}
6. Combined Expressions
Description: You can combine different types of expressions to
create more complex evaluations.
Illustration:
java
Copy
public class CombinedExpressions {
public static void main(String[] args) {
int a = 5;
int b = 10;
int c = 15;

// Combined Expression
boolean result = (a < b) && (b < c) || (c > 10);
int sum = (a + b) * c; // Arithmetic combined with logical

System.out.println("Combined Expressions:");
System.out.println("Result of logical expression: " + result); //
true
System.out.println("Result of arithmetic expression: " + sum); // 225
}
}
Summary
 Expressions: Combinations of variables, operators, and values
that evaluate to a single value.
 Types: Arithmetic, relational, logical, bitwise, conditional, and
combined expressions.
These examples illustrate how to use various types of expressions in
Java, showcasing their syntax and functionalities.

Q&A on Control Statements in Java


Q1: What are Control Statements in Java?
A: Control statements in Java are used to determine the flow of
execution of the program. They help in making decisions, repeating
actions, and controlling the flow based on certain conditions.

Java (OOP) 18
Q2: What are the Types of Control Statements in Java?
A: Control statements can be categorized into three main types:
1. Conditional Statements: Execute a block of code based on a
condition.
 if
 if-else
 else if
 switch
2. Looping Statements: Execute a block of code repeatedly as
long as a condition is true.
 for
 while
 do-while
3. Jump Statements: Control the flow by transferring control to
another part of the program.
 break
 continue
 return

Example Code
1. Conditional Statements
Illustration of if, if-else, and switch:
java
Copy
public class ConditionalStatements {
public static void main(String[] args) {
int number = 20;

// if statement
if (number > 0) {
System.out.println("The number is positive.");
}

// if-else statement
if (number % 2 == 0) {
System.out.println("The number is even.");
} else {
System.out.println("The number is odd.");
}

// switch statement
switch (number) {
case 10:
System.out.println("Number is 10.");

Java (OOP) 19
break;
case 20:
System.out.println("Number is 20.");
break;
default:
System.out.println("Number is not 10 or 20.");
}
}
}
Output:
Copy
The number is positive.
The number is even.
Number is 20.

2. Looping Statements
Illustration of for, while, and do-while:
java
Copy
public class LoopingStatements {
public static void main(String[] args) {
// For loop
System.out.println("For Loop:");
for (int i = 1; i <= 5; i++) {
System.out.println("Iteration: " + i);
}

// While loop
System.out.println("\nWhile Loop:");
int j = 1;
while (j <= 5) {
System.out.println("Iteration: " + j);
j++;
}

// Do-while loop
System.out.println("\nDo-While Loop:");
int k = 1;
do {
System.out.println("Iteration: " + k);
k++;
} while (k <= 5);
}
}
Output:
vbnet
Copy

Java (OOP) 20
For Loop:
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Iteration: 5

While Loop:
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Iteration: 5

Do-While Loop:
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Iteration: 5

3. Jump Statements
Illustration of break and continue:
java
Copy
public class JumpStatements {
public static void main(String[] args) {
// Break statement
System.out.println("Break Statement:");
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // Exit the loop when i equals 5
}
System.out.println("Iteration: " + i);
}

// Continue statement
System.out.println("\nContinue Statement:");
for (int i = 1; i <= 10; i++) {
if (i == 5) {
continue; // Skip the iteration when i equals 5
}
System.out.println("Iteration: " + i);
}
}
}
Output:
ebnf
Copy

Java (OOP) 21
Break Statement:
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4

Continue Statement:
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Iteration: 6
Iteration: 7
Iteration: 8
Iteration: 9
Iteration: 10

Summary
1. Conditional Statements: Used to perform different actions
based on different conditions (if, if-else, switch).
2. Looping Statements: Used to execute a block of code
repeatedly (for, while, do-while).
3. Jump Statements: Used to alter the flow of control
(break, continue, return).
These control statements are essential for creating dynamic and
responsive Java applications.

Here are more detailed illustrations of control statements in Java,


complete with example code for each type.
1. Conditional Statements
1.1 if and if-else
Description: The if statement executes a block of code if the
specified condition is true. The if-else statement provides an
alternative block that executes if the condition is false.
Illustration:
java
Copy
public class IfElseExample {
public static void main(String[] args) {
int score = 75;

// if statement
if (score >= 60) {

Java (OOP) 22
System.out.println("You passed the exam.");
} else {
System.out.println("You failed the exam.");
}

// Additional check with else-if


if (score >= 90) {
System.out.println("Grade: A");
} else if (score >= 80) {
System.out.println("Grade: B");
} else if (score >= 70) {
System.out.println("Grade: C");
} else {
System.out.println("Grade: D");
}
}
}
Output:
Copy
You passed the exam.
Grade: C

1.2 switch
Description: The switch statement allows for multi-way branching
based on the value of a variable.
Illustration:
java
Copy
public class SwitchExample {
public static void main(String[] args) {
int day = 3;

switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:

Java (OOP) 23
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
default:
System.out.println("Invalid day");
}
}
}
Output:
Copy
Wednesday

2. Looping Statements
2.1 for Loop
Description: The for loop is used for iterating a part of the program
multiple times.
Illustration:
java
Copy
public class ForLoopExample {
public static void main(String[] args) {
System.out.println("Even numbers from 1 to 10:");
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
System.out.println(i); // Print only even numbers
}
}
}
}
Output:
Copy
Even numbers from 1 to 10:
2
4
6
8
10

2.2 while Loop


Description: The while loop continues to execute a block of code as
long as a specified condition is true.
Illustration:

Java (OOP) 24
java
Copy
public class WhileLoopExample {
public static void main(String[] args) {
int count = 1;

System.out.println("Counting to 5:");
while (count <= 5) {
System.out.println(count);
count++; // Increment count
}
}
}
Output:
Copy
Counting to 5:
1
2
3
4
5

2.3 do-while Loop


Description: The do-while loop is similar to the while loop, but it
guarantees that the block of code will be executed at least once.
Illustration:
java
Copy
public class DoWhileLoopExample {
public static void main(String[] args) {
int num = 1;

System.out.println("Do-While Loop Example:");


do {
System.out.println("Number: " + num);
num++;
} while (num <= 5);
}
}
Output:
Copy
Do-While Loop Example:
Number: 1
Number: 2
Number: 3

Java (OOP) 25
Number: 4
Number: 5

3. Jump Statements
3.1 break
Description: The break statement exits the nearest enclosing loop
or switch statement.
Illustration:
java
Copy
public class BreakExample {
public static void main(String[] args) {
System.out.println("Break Statement Example:");
for (int i = 1; i <= 10; i++) {
if (i == 6) {
break; // Exit the loop when i is 6
}
System.out.println(i);
}
}
}
Output:
Copy
Break Statement Example:
1
2
3
4
5

3.2 continue
Description: The continue statement skips the current iteration of a
loop and proceeds to the next iteration.
Illustration:
java
Copy
public class ContinueExample {
public static void main(String[] args) {
System.out.println("Continue Statement Example:");
for (int i = 1; i <= 10; i++) {
if (i == 5) {
continue; // Skip the iteration when i is 5
}
System.out.println(i);

Java (OOP) 26
}
}
}
Output:
Copy
Continue Statement Example:
1
2
3
4
6
7
8
9
10

4. Labeled Statements
Description: Labeled statements can be useful when you have
nested loops. They allow you to break or continue from the outer
loop.
Illustration:
java
Copy
public class LabeledBreakExample {
public static void main(String[] args) {
outerLoop:
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (i == 2 && j == 2) {
break outerLoop; // Exit both loops
}
System.out.println("i: " + i + ", j: " + j);
}
}
}
}
Output:
Copy
i: 1, j: 1
i: 1, j: 2
i: 1, j: 3
i: 2, j: 1

Summary

Java (OOP) 27
1. Conditional Statements: Control flow based on conditions
(if, if-else, switch).
2. Looping Statements: Repeat a block of code (for, while, do-
while).
3. Jump Statements: Control the flow with break and continue.
4. Labeled Statements: Use labels for nested loops to control
flow.
These examples illustrate the use of various control statements in
Java, providing a deeper understanding of how to manage the flow
of a program.

Q&A on Arrays in Java


Q1: What is an Array in Java?
A: An array in Java is a data structure that can hold a fixed number
of values of a single type. It is a collection of elements identified by
an index or key.

Q2: How do you declare and initialize an Array in Java?


A: You can declare an array by specifying the type, followed by
square brackets. Arrays can be initialized at the time of declaration
or later.
Example:
java
Copy
int[] numbers = new int[5]; // Declaration with size
int[] moreNumbers = {1, 2, 3, 4, 5}; // Declaration with initialization

Q3: How do you access Array Elements?


A: Array elements are accessed using their index, which starts from
0. For example, numbers[0] accesses the first element.
Example:
java
Copy
int firstNumber = moreNumbers[0]; // Accessing the first element

Example Code

Java (OOP) 28
1. Declaring and Initializing Arrays
Illustration:
java
Copy
public class ArrayDeclaration {
public static void main(String[] args) {
// Declaration and Initialization
int[] numbers = new int[5]; // Array of size 5
for (int i = 0; i < numbers.length; i++) {
numbers[i] = (i + 1) * 10; // Assigning values
}

// Displaying the Array


System.out.println("Array Elements:");
for (int num : numbers) {
System.out.println(num);
}
}
}
Output:
Copy
Array Elements:
10
20
30
40
50

2. Accessing Array Elements


Illustration:
java
Copy
public class ArrayAccess {
public static void main(String[] args) {
int[] scores = {95, 85, 75, 65, 55};

// Accessing and Displaying Specific Elements


System.out.println("First Score: " + scores[0]); // 95
System.out.println("Second Score: " + scores[1]); // 85
System.out.println("Last Score: " + scores[scores.length - 1]); // 55
}
}
Output:
Copy
First Score: 95

Java (OOP) 29
Second Score: 85
Last Score: 55

3. Multidimensional Arrays
Description: Java supports multidimensional arrays (arrays of
arrays), commonly used for matrices.
Illustration:
java
Copy
public class MultiDimensionalArray {
public static void main(String[] args) {
// Declaration and Initialization of a 2D Array
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

// Accessing and Displaying Elements


System.out.println("2D Array Elements:");
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}
Output:
basic
Copy
2D Array Elements:
1 2 3
4 5 6
7 8 9

4. Array Length and Iteration


Description: You can find the length of an array using
the length property and iterate through it using loops.
Illustration:
java
Copy
public class ArrayLengthAndIteration {

Java (OOP) 30
public static void main(String[] args) {
String[] fruits = {"Apple", "Banana", "Cherry"};

// Displaying Array Length


System.out.println("Number of Fruits: " + fruits.length); // 3

// Iterating through the Array


System.out.println("Fruits List:");
for (int i = 0; i < fruits.length; i++) {
System.out.println(fruits[i]);
}
}
}
Output:
Copy
Number of Fruits: 3
Fruits List:
Apple
Banana
Cherry

5. Copying Arrays
Description: You can copy arrays using methods
like System.arraycopy() or using Arrays.copyOf().
Illustration:
java
Copy
import java.util.Arrays;

public class ArrayCopy {


public static void main(String[] args) {
int[] original = {1, 2, 3, 4, 5};
int[] copy = Arrays.copyOf(original, original.length); // Copying the
array

// Modifying the copy


copy[0] = 10;

// Displaying both Arrays


System.out.println("Original Array: " + Arrays.toString(original));
System.out.println("Copied Array: " + Arrays.toString(copy));
}
}
Output:
json
Copy

Java (OOP) 31
Original Array: [1, 2, 3, 4, 5]
Copied Array: [10, 2, 3, 4, 5]

Summary
1. Arrays: Fixed-size data structures holding elements of the
same type.
2. Declaration and Initialization: Use new keyword or curly
braces for initialization.
3. Accessing Elements: Use indices starting from 0.
4. Multidimensional Arrays: Arrays of arrays, useful for
matrices.
5. Array Length and Iteration: Use length property to get size,
and loops to iterate.
6. Copying Arrays: Use methods like Arrays.copyOf().
These examples give a comprehensive overview of arrays in Java,
demonstrating how to declare, initialize, access, and manipulate
them.

Here are additional illustrations and concepts related to arrays in


Java, complete with example code for each type.
1. Array of Objects
Description: You can create an array to hold objects of a class
type.
Illustration:
java
Copy
class Student {
String name;
int age;

Student(String name, int age) {


this.name = name;
this.age = age;
}
}

public class ArrayOfObjects {


public static void main(String[] args) {
// Array of Student objects
Student[] students = new Student[3];
students[0] = new Student("Alice", 20);
students[1] = new Student("Bob", 22);
students[2] = new Student("Charlie", 21);

Java (OOP) 32
// Displaying Student information
System.out.println("Student Details:");
for (Student student : students) {
System.out.println("Name: " + student.name + ", Age: " +
student.age);
}
}
}
Output:
Copy
Student Details:
Name: Alice, Age: 20
Name: Bob, Age: 22
Name: Charlie, Age: 21

2. Array Manipulation: Inserting and Deleting Elements


Description: You can manipulate arrays by inserting or deleting
elements, but since arrays have a fixed size, you may need to shift
elements.
Illustration:
java
Copy
import java.util.Arrays;

public class ArrayManipulation {


public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
int insertIndex = 2; // Position to insert
int newValue = 99;

// Inserting a value
arr = insertElement(arr, insertIndex, newValue);
System.out.println("Array after insertion: " + Arrays.toString(arr));

// Deleting a value
arr = deleteElement(arr, 3); // Delete element at index 3
System.out.println("Array after deletion: " + Arrays.toString(arr));
}

public static int[] insertElement(int[] array, int index, int value) {


int[] newArray = new int[array.length + 1];
for (int i = 0, j = 0; i < newArray.length; i++) {
if (i == index) {
newArray[i] = value;
} else {
newArray[i] = array[j++];
}
}
return newArray;
}

public static int[] deleteElement(int[] array, int index) {

Java (OOP) 33
if (index < 0 || index >= array.length) {
return array; // Return original if index is out of bounds
}
int[] newArray = new int[array.length - 1];
for (int i = 0, j = 0; i < array.length; i++) {
if (i != index) {
newArray[j++] = array[i];
}
}
return newArray;
}
}
Output:
json
Copy
Array after insertion: [1, 2, 99, 3, 4, 5]
Array after deletion: [1, 2, 99, 4, 5]

3. Sorting an Array
Description: You can sort arrays using built-in methods from
the Arrays class.
Illustration:
java
Copy
import java.util.Arrays;

public class ArraySorting {


public static void main(String[] args) {
int[] numbers = {5, 3, 8, 1, 2};

// Sorting the array


Arrays.sort(numbers);
System.out.println("Sorted Array: " + Arrays.toString(numbers));
}
}
Output:
Copy
Sorted Array: [1, 2, 3, 5, 8]

4. Using Arrays.fill()
Description: The Arrays.fill() method can fill an array with a
specific value.
Illustration:
java
Copy
import java.util.Arrays;

public class ArrayFill {


public static void main(String[] args) {

Java (OOP) 34
int[] numbers = new int[5];

// Filling the array with the value 7


Arrays.fill(numbers, 7);
System.out.println("Filled Array: " + Arrays.toString(numbers));
}
}
Output:
Copy
Filled Array: [7, 7, 7, 7, 7]

5. Finding the Maximum and Minimum Values


Description: You can find the maximum and minimum values in an
array by iterating through it.
Illustration:
java
Copy
public class MaxMinInArray {
public static void main(String[] args) {
int[] numbers = {45, 12, 78, 34, 23};

int max = numbers[0];


int min = numbers[0];

for (int num : numbers) {


if (num > max) {
max = num; // Update max
}
if (num < min) {
min = num; // Update min
}
}

System.out.println("Maximum Value: " + max);


System.out.println("Minimum Value: " + min);
}
}
Output:
Copy
Maximum Value: 78
Minimum Value: 12

6. Passing Arrays to Methods


Description: You can pass arrays as arguments to methods.
Illustration:
java
Copy
public class PassArrayToMethod {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};

Java (OOP) 35
printArray(numbers); // Passing the array to the method
}

public static void printArray(int[] array) {


System.out.println("Array Elements:");
for (int num : array) {
System.out.println(num);
}
}
}
Output:
Copy
Array Elements:
10
20
30
40
50

Summary
1. Array of Objects: Arrays can hold objects of any class.
2. Array Manipulation: Inserting and deleting elements requires
shifting.
3. Sorting an Array: Use Arrays.sort() for sorting.
4. Using Arrays.fill(): Fill an array with a specific value easily.
5. Finding Max/Min Values: Iterate through the array to find
extremes.
6. Passing Arrays to Methods: Arrays can be passed to
methods for processing.

Here’s a comprehensive overview of arrays in Java, covering


declaration and initialization, accessing elements, iterating,
multidimensional arrays, and various methods.
1. Declaration and Initialization
Description: You can declare an array by specifying the type
followed by square brackets. Initialization can occur at the time of
declaration or later.
Illustration:
java
Copy
public class ArrayDeclaration {
public static void main(String[] args) {
// Declaration with size
int[] numbers = new int[5];

Java (OOP) 36
// Initialization at declaration
int[] moreNumbers = {1, 2, 3, 4, 5};

// Assigning values to the first array


for (int i = 0; i < numbers.length; i++) {
numbers[i] = (i + 1) * 10; // Assigning values
}

// Displaying both arrays


System.out.println("Numbers: " + java.util.Arrays.toString(numbers));
System.out.println("More Numbers: " +
java.util.Arrays.toString(moreNumbers));
}
}
Output:
json
Copy
Numbers: [10, 20, 30, 40, 50]
More Numbers: [1, 2, 3, 4, 5]

2. Accessing Elements
Description: Array elements are accessed using their index, which
starts at 0.
Illustration:
java
Copy
public class ArrayAccess {
public static void main(String[] args) {
int[] scores = {90, 80, 70, 60, 50};

// Accessing elements
System.out.println("First Score: " + scores[0]); // 90
System.out.println("Third Score: " + scores[2]); // 70
System.out.println("Last Score: " + scores[scores.length - 1]); // 50
}
}
Output:
Copy
First Score: 90
Third Score: 70
Last Score: 50

3. Iterating Through Arrays


Description: You can use loops to iterate through the elements of
an array.
Illustration:
java
Copy

Java (OOP) 37
public class ArrayIteration {
public static void main(String[] args) {
String[] fruits = {"Apple", "Banana", "Cherry"};

// Using a for loop


System.out.println("Using for loop:");
for (int i = 0; i < fruits.length; i++) {
System.out.println(fruits[i]);
}

// Using an enhanced for loop


System.out.println("\nUsing enhanced for loop:");
for (String fruit : fruits) {
System.out.println(fruit);
}
}
}
Output:
Copy
Using for loop:
Apple
Banana
Cherry

Using enhanced for loop:


Apple
Banana
Cherry

4. Multidimensional Arrays
Description: Multidimensional arrays are arrays of arrays,
commonly used for matrices.
Illustration:
java
Copy
public class MultiDimensionalArray {
public static void main(String[] args) {
// Declaration and initialization of a 2D array
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

// Accessing and displaying elements


System.out.println("2D Array Elements:");
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}

Java (OOP) 38
}
}
Output:
basic
Copy
2D Array Elements:
1 2 3
4 5 6
7 8 9

5. Common Array Methods


Description: Java provides several useful methods in
the Arrays class for array manipulation.
 Copying Arrays:
java
Copy
import java.util.Arrays;

public class ArrayCopy {


public static void main(String[] args) {
int[] original = {1, 2, 3, 4, 5};
int[] copy = Arrays.copyOf(original, original.length); // Copying the
array

// Displaying both arrays


System.out.println("Original Array: " + Arrays.toString(original));
System.out.println("Copied Array: " + Arrays.toString(copy));
}
}
Output:
json
Copy
Original Array: [1, 2, 3, 4, 5]
Copied Array: [1, 2, 3, 4, 5]
 Sorting Arrays:
java
Copy
import java.util.Arrays;

public class ArraySorting {


public static void main(String[] args) {
int[] numbers = {3, 5, 1, 4, 2};

// Sorting the array


Arrays.sort(numbers);
System.out.println("Sorted Array: " + Arrays.toString(numbers));
}
}
Output:

Java (OOP) 39
Copy
Sorted Array: [1, 2, 3, 4, 5]
 Filling Arrays:
java
Copy
import java.util.Arrays;

public class ArrayFill {


public static void main(String[] args) {
int[] numbers = new int[5];

// Filling the array with the value 7


Arrays.fill(numbers, 7);
System.out.println("Filled Array: " + Arrays.toString(numbers));
}
}
Output:
Copy
Filled Array: [7, 7, 7, 7, 7]
 Finding Array Length:
java
Copy
public class ArrayLength {
public static void main(String[] args) {
String[] colors = {"Red", "Green", "Blue"};
System.out.println("Number of colors: " + colors.length);
}
}
Output:
Copy
Number of colors: 3

Summary
1. Declaration and Initialization: Arrays can be declared with a
size or initialized directly with values.
2. Accessing Elements: Use indices to access specific elements
in the array.
3. Iterating: Use for or enhanced for loops to iterate through
array elements.
4. Multidimensional Arrays: Arrays can be multidimensional,
enabling matrix-like structures.
5. Common Methods: Use Arrays class methods for copying,
sorting, filling, and finding array lengths.
These examples illustrate the fundamental aspects of working with
arrays in Java.

Java (OOP) 40
Q&A on Strings in Java
Q1: What is a String in Java?
A: A String in Java is a sequence of characters used to represent
text. Strings are immutable, meaning once created, they cannot be
changed.

Q2: How do you declare and initialize Strings in Java?


A: Strings can be declared using double quotes or the String class
constructor.
Example:
java
Copy
String str1 = "Hello, World!"; // Using double quotes
String str2 = new String("Hello, Java!"); // Using the String constructor

Example Code
1. Basic String Operations
Illustration:
java
Copy
public class BasicStringOperations {
public static void main(String[] args) {
String greeting = "Hello, World!";

// Length of the string


System.out.println("Length: " + greeting.length()); // 13

// Accessing characters
char firstChar = greeting.charAt(0);
System.out.println("First Character: " + firstChar); // H

// Substring
String subStr = greeting.substring(7, 12); // from index 7 to 11
System.out.println("Substring: " + subStr); // World
}
}
Output:
Copy
Length: 13
First Character: H
Substring: World

Java (OOP) 41
2. String Concatenation
Description: You can concatenate strings using the + operator or
the concat() method.
Illustration:
java
Copy
public class StringConcatenation {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "Java";

// Using + operator
String result1 = str1 + " " + str2;
System.out.println("Concatenation using +: " + result1); // Hello
Java

// Using concat() method


String result2 = str1.concat(" ").concat(str2);
System.out.println("Concatenation using concat(): " + result2); //
Hello Java
}
}
Output:
Copy
Concatenation using +: Hello Java
Concatenation using concat(): Hello Java

3. String Comparison
Description: Strings can be compared using == for reference
equality and equals() for value equality.
Illustration:
java
Copy
public class StringComparison {
public static void main(String[] args) {
String str1 = "Java";
String str2 = new String("Java");

// Reference comparison
System.out.println("str1 == str2: " + (str1 == str2)); // false

// Value comparison
System.out.println("str1.equals(str2): " + str1.equals(str2)); //
true
}

Java (OOP) 42
}
Output:
Copy
str1 == str2: false
str1.equals(str2): true

4. Converting Strings to Other Data Types


Description: You can convert strings to integers and vice versa
using Integer.parseInt() and String.valueOf().
Illustration:
java
Copy
public class StringConversion {
public static void main(String[] args) {
String numberStr = "1234";

// Converting String to int


int number = Integer.parseInt(numberStr);
System.out.println("String to int: " + number); // 1234

// Converting int to String


String strNumber = String.valueOf(number);
System.out.println("int to String: " + strNumber); // "1234"
}
}
Output:
Copy
String to int: 1234
int to String: 1234

5. String Methods
Description: Java provides many useful methods for string
manipulation.
Illustration:
java
Copy
public class StringMethods {
public static void main(String[] args) {
String text = " Hello, Java! ";

// Trimming whitespace
String trimmed = text.trim();
System.out.println("Trimmed: '" + trimmed + "'"); // 'Hello, Java!'

Java (OOP) 43
// Changing case
System.out.println("Uppercase: " + trimmed.toUpperCase()); // HELLO,
JAVA!
System.out.println("Lowercase: " + trimmed.toLowerCase()); // hello,
java!

// Replacing characters
String replaced = trimmed.replace("Java", "World");
System.out.println("Replaced: " + replaced); // Hello, World!
}
}
Output:
Copy
Trimmed: 'Hello, Java!'
Uppercase: HELLO, JAVA!
Lowercase: hello, java!
Replaced: Hello, World!

6. String Formatting
Description: You can format strings
using String.format() or System.out.printf().
Illustration:
java
Copy
public class StringFormatting {
public static void main(String[] args) {
String name = "Alice";
int age = 30;

// Using String.format()
String formatted = String.format("Name: %s, Age: %d", name, age);
System.out.println(formatted); // Name: Alice, Age: 30

// Using printf
System.out.printf("Name: %s, Age: %d\n", name, age); // Name: Alice,
Age: 30
}
}
Output:
Copy
Name: Alice, Age: 30
Name: Alice, Age: 30

Summary
1. Strings: A sequence of characters, immutable once created.
Java (OOP) 44
2. Declaration and Initialization: Strings can be created using
double quotes or with the String constructor.
3. Basic Operations: Length, character access, and substring
extraction.
4. Concatenation: Combine strings using + or concat().
5. Comparison: Use == for reference comparison and equals() for
value comparison.
6. Conversions: Convert between strings and other data types.
7. String Methods: Various built-in methods for manipulation
and formatting.
These examples provide a solid foundation for understanding how to
work with strings in Java.

Here’s a comprehensive overview of classes and objects in Java,


including definitions, concepts, and illustrative code examples.
Understanding Classes and Objects in Java
1. Definition
 Class: A class is a blueprint or template for creating objects. It
defines attributes (fields) and methods (functions) that the
objects created from the class can use.
 Object: An object is an instance of a class. It represents a
specific entity with state and behavior defined by the class.

2. Key Concepts
2.1 Attributes and Methods
 Attributes: Variables that hold the state of an object.
 Methods: Functions that define the behavior of an object.
They can manipulate the object's attributes or perform actions.

Java (OOP) 45
2.2 Constructor
A constructor is a special method that is called when an object is
instantiated. It initializes the object's attributes.
Example:
java
Copy
class Car {
String color;
String model;

// Constructor
Car(String color, String model) {
this.color = color;
this.model = model;
}

// Method to display car details


void displayDetails() {
System.out.println("Car Model: " + model + ", Color: " + color);
}
}

3. Creating and Using Objects


Illustration:
java
Copy
public class Main {
public static void main(String[] args) {
// Creating an object of the Car class
Car myCar = new Car("Red", "Toyota");

// Accessing attributes and methods


myCar.displayDetails(); // Output: Car Model: Toyota, Color: Red
}
}
Output:
Copy
Car Model: Toyota, Color: Red

4. Access Modifiers
Access modifiers control the visibility of class attributes and
methods. The main access modifiers are:
 public: Accessible from any other class.

Java (OOP) 46
private: Accessible only within the same class.
 protected: Accessible within the same package and
subclasses.
Example:
java
Copy
class Person {
private String name; // Private attribute

// Constructor
public Person(String name) {
this.name = name;
}

// Method to access private attribute


public String getName() {
return name;
}
}

5. Inheritance
Inheritance allows one class to inherit the attributes and methods of
another class, promoting code reuse.
Illustration:
java
Copy
// Base class
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}

// Derived class
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");
}
}

public class Main {


public static void main(String[] args) {
Dog myDog = new Dog();
myDog.sound(); // Output: Dog barks
}
}

Java (OOP) 47
Output:
Copy
Dog barks

6. Polymorphism
Polymorphism allows methods to do different things based on the
object that it is acting upon. The two types are:
 Compile-time (Method Overloading): Same method name
with different parameters.
 Runtime (Method Overriding): A subclass provides a
specific implementation of a method already defined in its
superclass.
Example of Method Overloading:
java
Copy
class MathOperations {
// Method to add two integers
int add(int a, int b) {
return a + b;
}

// Method to add three integers


int add(int a, int b, int c) {
return a + b + c;
}
}

7. Encapsulation
Encapsulation is the practice of keeping the data (attributes) and
the code (methods) that manipulates the data in a single unit
(class). It restricts direct access to some of the object's components.
Illustration:
java
Copy
class BankAccount {
private double balance; // Private attribute

// Constructor
public BankAccount(double initialBalance) {
balance = initialBalance;
}

Java (OOP) 48
// Method to deposit money
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}

// Method to get balance


public double getBalance() {
return balance;
}
}

8. Example: Putting It All Together


Here's a comprehensive example that demonstrates the concepts of
classes, objects, encapsulation, inheritance, and polymorphism:
java
Copy
// Base class
class Vehicle {
protected String brand;

Vehicle(String brand) {
this.brand = brand;
}

void honk() {
System.out.println("Vehicle honks");
}
}

// Subclass
class Bike extends Vehicle {
Bike(String brand) {
super(brand);
}

@Override
void honk() {
System.out.println(brand + " bike honks");
}
}

// Subclass
class Car extends Vehicle {
Car(String brand) {
super(brand);
}

@Override
void honk() {

Java (OOP) 49
System.out.println(brand + " car honks");
}
}

public class Main {


public static void main(String[] args) {
Vehicle myBike = new Bike("Yamaha");
Vehicle myCar = new Car("Toyota");

myBike.honk(); // Output: Yamaha bike honks


myCar.honk(); // Output: Toyota car honks
}
}
Output:
Copy
Yamaha bike honks
Toyota car honks

Summary
1. Classes and Objects: Classes are blueprints; objects are
instances of classes.
2. Attributes and Methods: Attributes define state; methods
define behavior.
3. Constructors: Special methods for initializing objects.
4. Access Modifiers: Control the visibility of class members.
5. Inheritance: Enables code reuse and hierarchical
relationships.
6. Polymorphism: Allows methods to operate differently based
on the object.
7. Encapsulation: Bundles data and methods while restricting
access.
These concepts form the foundation of object-oriented programming
in Java.

Here are additional illustrations and examples of classes and objects


in Java, covering various scenarios and concepts.
1. Class with Multiple Attributes and Methods
Illustration:
java
Copy
Java (OOP) 50
class Book {
private String title;
private String author;
private double price;

// Constructor
public Book(String title, String author, double price) {
this.title = title;
this.author = author;
this.price = price;
}

// Method to display book details


public void displayInfo() {
System.out.println("Title: " + title);
System.out.println("Author: " + author);
System.out.println("Price: $" + price);
}

// Method to apply discount


public void applyDiscount(double percentage) {
price -= price * (percentage / 100);
}
}

public class Library {


public static void main(String[] args) {
Book book1 = new Book("1984", "George Orwell", 15.99);
book1.displayInfo(); // Display original info

book1.applyDiscount(10); // Apply a 10% discount


System.out.println("After discount:");
book1.displayInfo(); // Display updated info
}
}
Output:
Copy
Title: 1984
Author: George Orwell
Price: $15.99
After discount:
Title: 1984
Author: George Orwell
Price: $14.391

2. Inheritance with Method Overriding


Illustration:
java
Copy
class Shape {

Java (OOP) 51
void draw() {
System.out.println("Drawing a shape");
}
}

class Circle extends Shape {


@Override
void draw() {
System.out.println("Drawing a circle");
}
}

class Square extends Shape {


@Override
void draw() {
System.out.println("Drawing a square");
}
}

public class ShapeTest {


public static void main(String[] args) {
Shape myShape = new Shape();
Shape myCircle = new Circle();
Shape mySquare = new Square();

myShape.draw(); // Output: Drawing a shape


myCircle.draw(); // Output: Drawing a circle
mySquare.draw(); // Output: Drawing a square
}
}
Output:
Copy
Drawing a shape
Drawing a circle
Drawing a square

3. Polymorphism with Method Overloading


Illustration:
java
Copy
class Printer {
void print(int number) {
System.out.println("Printing number: " + number);
}

void print(String text) {


System.out.println("Printing text: " + text);
}

void print(double decimal) {

Java (OOP) 52
System.out.println("Printing decimal: " + decimal);
}
}

public class PrinterTest {


public static void main(String[] args) {
Printer printer = new Printer();

printer.print(10); // Calls print(int)


printer.print("Hello, World!"); // Calls print(String)
printer.print(3.14); // Calls print(double)
}
}
Output:
Copy
Printing number: 10
Printing text: Hello, World!
Printing decimal: 3.14

4. Encapsulation with Getters and Setters


Illustration:
java
Copy
class Student {
private String name;
private int age;

// Getter for name


public String getName() {
return name;
}

// Setter for name


public void setName(String name) {
this.name = name;
}

// Getter for age


public int getAge() {
return age;
}

// Setter for age


public void setAge(int age) {
if (age > 0) { // Simple validation
this.age = age;
} else {
System.out.println("Invalid age");
}
}

Java (OOP) 53
}

public class StudentTest {


public static void main(String[] args) {
Student student = new Student();
student.setName("Alice");
student.setAge(20);

System.out.println("Name: " + student.getName());


System.out.println("Age: " + student.getAge());
}
}
Output:
Copy
Name: Alice
Age: 20

5. Abstract Classes and Methods


Description: Abstract classes cannot be instantiated and can have
abstract methods that must be implemented by subclasses.
Illustration:
java
Copy
abstract class Animal {
abstract void sound(); // Abstract method

void sleep() {
System.out.println("The animal is sleeping");
}
}

class Cat extends Animal {


@Override
void sound() {
System.out.println("Meow");
}
}

class Dog extends Animal {


@Override
void sound() {
System.out.println("Bark");
}
}

public class AnimalTest {


public static void main(String[] args) {
Animal myCat = new Cat();
Animal myDog = new Dog();

Java (OOP) 54
myCat.sound(); // Output: Meow
myDog.sound(); // Output: Bark
myCat.sleep(); // Output: The animal is sleeping
}
}
Output:
Copy
Meow
Bark
The animal is sleeping

6. Interfaces
Description: An interface defines a contract that classes can
implement. A class can implement multiple interfaces.
Illustration:
java
Copy
interface Drawable {
void draw(); // Abstract method
}

class Rectangle implements Drawable {


@Override
public void draw() {
System.out.println("Drawing a rectangle");
}
}

class Circle implements Drawable {


@Override
public void draw() {
System.out.println("Drawing a circle");
}
}

public class InterfaceTest {


public static void main(String[] args) {
Drawable rectangle = new Rectangle();
Drawable circle = new Circle();

rectangle.draw(); // Output: Drawing a rectangle


circle.draw(); // Output: Drawing a circle
}
}
Output:
Copy
Drawing a rectangle

Java (OOP) 55
Drawing a circle

7. Composition
Description: Composition is a design principle where a class
contains references to other classes as part of its state.
Illustration:
java
Copy
class Engine {
void start() {
System.out.println("Engine starting");
}
}

class Car {
private Engine engine; // Car has an Engine

Car() {
engine = new Engine(); // Creating an Engine instance
}

void startCar() {
engine.start(); // Delegating the start action to the engine
System.out.println("Car is ready to go!");
}
}

public class CompositionTest {


public static void main(String[] args) {
Car myCar = new Car();
myCar.startCar(); // Output: Engine starting
// Car is ready to go!
}
}
Output:
Copy
Engine starting
Car is ready to go!

Summary
 Classes and Objects: Fundamental to object-oriented
programming, defining blueprints and instances.
 Attributes and Methods: Define state and behavior of
objects.
 Inheritance: Allows code reuse and creation of hierarchical
relationships.
Java (OOP) 56
 Polymorphism: Enables methods to operate differently based
on the object.
 Encapsulation: Protects data through access modifiers and
getter/setter methods.
 Abstract Classes and Interfaces: Define contracts for
subclasses to implement.
 Composition: A design principle where objects are composed
of other objects.
These examples illustrate various aspects of classes and objects in
Java, highlighting their flexibility and power in modeling real-world
scenarios.

Here's a brief explanation of encapsulation and information hiding in


Java, along with their differences.
Encapsulation
Definition:
Encapsulation is an object-oriented programming principle that
bundles the data (attributes) and methods (functions) that operate
on the data into a single unit, typically a class. It restricts direct
access to some of an object's components, which can help prevent
unintended interference and misuse of the methods and data.
Key Points:
 Access Modifiers: Encapsulation uses access modifiers
(like private, public, and protected) to define the visibility of class
members.
 Getters and Setters: It commonly employs getter and setter
methods to access and modify private attributes, allowing
controlled access.
Example:
java
Copy
class BankAccount {
private double balance; // Private attribute

public BankAccount(double initialBalance) {


balance = initialBalance;
}

Java (OOP) 57
public double getBalance() {
return balance; // Getter
}

public void deposit(double amount) {


if (amount > 0) {
balance += amount; // Method to modify balance
}
}
}
Information Hiding
Definition:
Information hiding is a broader concept that refers to the practice of
restricting access to certain details of a module (like a class) to
reduce complexity and increase robustness. It focuses on exposing
only what is necessary and hiding the implementation details.
Key Points:
 Focus on Implementation: Information hiding emphasizes
hiding the internal workings of a class while exposing only the
necessary interfaces.
 Promotes Maintenance: By hiding implementation details, it
makes it easier to maintain and modify code without affecting
other parts of the program.
Differences Between Encapsulation and Information Hiding
Aspect Encapsulation Information Hiding

Bundles data and Hides implementation


Purpose methods into a single details to reduce
unit. complexity.

Achieved using access Achieved by exposing


Implementat
modifiers (private, only necessary
ion
public). interfaces.

Protects data integrity Reduces coupling and


Focus through controlled promotes
access. maintainability.

Example Using getters and Hiding the details of how


setters for private a method is

Java (OOP) 58
Aspect Encapsulation Information Hiding

attributes. implemented.

Conclusion
Both encapsulation and information hiding are essential concepts in
object-oriented programming that promote modularity and
maintainability in Java. While encapsulation focuses on bundling
data and methods and controlling access, information hiding
emphasizes reducing complexity by concealing implementation
details.

In Java, relationships between classes are essential for modeling


real-world scenarios. The main types of relationships
include Association, Aggregation, and Composition. Here’s a
brief explanation of each, along with code examples.
1. Association
Definition:
Association is a general relationship between two classes where one
class uses or interacts with another. It can be one-to-one, one-to-
many, or many-to-many. Neither class owns the other.
Example:
In a university scenario, a Student can enroll in multiple Courses, and
a Course can have multiple Students.
java
Copy
import java.util.ArrayList;
import java.util.List;

class Student {
String name;

Student(String name) {
this.name = name;
}

void enroll(Course course) {


course.addStudent(this);
}
}

class Course {

Java (OOP) 59
String title;
List<Student> students = new ArrayList<>();

Course(String title) {
this.title = title;
}

void addStudent(Student student) {


students.add(student);
}

void showStudents() {
System.out.println("Students in " + title + ":");
for (Student student : students) {
System.out.println(student.name);
}
}
}

public class AssociationExample {


public static void main(String[] args) {
Student student1 = new Student("Alice");
Student student2 = new Student("Bob");
Course course = new Course("Java Programming");

student1.enroll(course);
student2.enroll(course);
course.showStudents();
}
}
Output:
Copy
Students in Java Programming:
Alice
Bob

2. Aggregation
Definition:
Aggregation is a specialized form of association that represents a
"whole-part" relationship. In aggregation, the part can exist
independently of the whole. For example, a Library contains Books, but
a Book can exist without a Library.
Example:
java
Copy
import java.util.ArrayList;
import java.util.List;

class Book {
String title;

Java (OOP) 60
Book(String title) {
this.title = title;
}
}

class Library {
List<Book> books = new ArrayList<>();

void addBook(Book book) {


books.add(book);
}

void showBooks() {
System.out.println("Books in the library:");
for (Book book : books) {
System.out.println(book.title);
}
}
}

public class AggregationExample {


public static void main(String[] args) {
Book book1 = new Book("1984");
Book book2 = new Book("To Kill a Mockingbird");
Library library = new Library();

library.addBook(book1);
library.addBook(book2);
library.showBooks();
}
}
Output:
Copy
Books in the library:
1984
To Kill a Mockingbird

3. Composition
Definition:
Composition is a stronger form of aggregation where the part
cannot exist independently of the whole. If the whole is destroyed,
the parts are also destroyed. For example, a House has Rooms, and if
the House is destroyed, the Rooms are also gone.
Example:
java
Copy
class Room {
String name;

Room(String name) {
this.name = name;

Java (OOP) 61
}
}

class House {
private List<Room> rooms = new ArrayList<>();

House() {
// Creating rooms as part of the house
rooms.add(new Room("Living Room"));
rooms.add(new Room("Bedroom"));
rooms.add(new Room("Kitchen"));
}

void showRooms() {
System.out.println("Rooms in the house:");
for (Room room : rooms) {
System.out.println(room.name);
}
}
}

public class CompositionExample {


public static void main(String[] args) {
House house = new House();
house.showRooms();
}
}
Output:
Copy
Rooms in the house:
Living Room
Bedroom
Kitchen

Summary of Relationships
Relationship
Definition Example
Type

A general relationship where one Student and


Association
class uses another. Course

A "whole-part" relationship where Library and


Aggregation
parts can exist independently. Books

A strong "whole-part" relationship


House and
Composition where parts cannot exist
Rooms
independently.
These relationships help in designing a clear structure in your Java
applications, making it easier to understand and maintain the code.
Java (OOP) 62
Let's dive deeper into the relationships between classes in Java—
Association, Aggregation, and Composition—exploring their
characteristics, differences, and practical implications in software
design.
1. Association
Definition:
Association represents a relationship between two classes where
one class (the client) uses or interacts with another class (the
supplier). This relationship can be bidirectional or unidirectional.
Characteristics:
 Independence: The classes involved in an association can
exist independently. If one class is destroyed, the other can
still function.
 Multiplicity: Association can have different multiplicities, such
as one-to-one, one-to-many, or many-to-many.
Example:
In the example of Student and Course, a Student can enroll in
multiple Courses, and a Course can have multiple Students. This
relationship does not imply ownership; both entities can exist
independently.
Code Explanation:
java
Copy
class Student {
String name;

Student(String name) {
this.name = name;
}

void enroll(Course course) {


course.addStudent(this); // Linking student to course
}
}

class Course {
String title;
List<Student> students = new ArrayList<>();

Course(String title) {
this.title = title;
}

Java (OOP) 63
void addStudent(Student student) {
students.add(student); // Adding student to course
}

void showStudents() {
System.out.println("Students in " + title + ":");
for (Student student : students) {
System.out.println(student.name);
}
}
}
2. Aggregation
Definition:
Aggregation is a specialized type of association that represents a
"whole-part" relationship. In this case, the part can exist
independently of the whole.
Characteristics:
 Ownership: The whole (container) can contain parts
(components), but the parts do not depend on the whole for
their existence.
 Weak Relationship: If the whole is destroyed, the parts can
still exist. For example, a Library can exist without its Books,
and Books can exist independently.
Example:
In the Library and Book relationship, a Library can hold multiple Books,
but if the Library is closed, the Books can still be available elsewhere.
Code Explanation:
java
Copy
class Book {
String title;

Book(String title) {
this.title = title;
}
}

class Library {
List<Book> books = new ArrayList<>();

void addBook(Book book) {


books.add(book); // Adding book to library
}

void showBooks() {
System.out.println("Books in the library:");

Java (OOP) 64
for (Book book : books) {
System.out.println(book.title);
}
}
}
3. Composition
Definition:
Composition is a stronger form of aggregation where the part
cannot exist independently of the whole. If the whole is destroyed,
the parts are also destroyed.
Characteristics:
 Strong Ownership: The whole (composite) has a strong
ownership over its parts (components).
 Lifecycle Dependency: The lifecycle of the parts is tied to
the lifecycle of the whole. For instance, if a House is demolished,
the Rooms within it cease to exist.
Example:
In the House and Room relationship, a House contains Rooms. If the House is
destroyed, the Rooms no longer exist.
Code Explanation:
java
Copy
class Room {
String name;

Room(String name) {
this.name = name;
}
}

class House {
private List<Room> rooms = new ArrayList<>();

House() {
// Rooms are created as part of the house
rooms.add(new Room("Living Room"));
rooms.add(new Room("Bedroom"));
rooms.add(new Room("Kitchen"));
}

void showRooms() {
System.out.println("Rooms in the house:");
for (Room room : rooms) {
System.out.println(room.name);
}
}
}

Java (OOP) 65
Key Differences Between Relationships
Aspect Association Aggregation Composition

A whole-part A strong whole-


A general
relationship part relationship
Definitio relationship
where parts can where parts
n where one class
exist cannot exist
uses another.
independently. independently.

The whole owns


No ownership; The whole can
the parts; parts
Ownersh both entities contain parts,
cannot exist
ip can exist but parts can
without the
independently. exist elsewhere.
whole.

Parts can live Parts depend on


Lifecycles are
Lifecycle without the the lifecycle of
independent.
whole. the whole.

Student and Library and


Example House and Rooms
Course Books

Practical Implications
 Design Clarity: Understanding these relationships helps
clarify the design of your system, making it easier to model
real-world scenarios.
 Maintainability: Clear relationships between classes enhance
maintainability. For instance, when using composition, you
know that destroying the composite class will automatically
clean up its components.
 Flexibility: Aggregation allows for more flexible designs, as
parts can be reused across different wholes. For example,
a Book can belong to multiple Libraries.
Conclusion
By understanding association, aggregation, and composition, you
can create more organized, maintainable, and flexible Java
applications. Each relationship serves a unique purpose in modeling

Java (OOP) 66
the interactions between classes, reflecting the complexity and
nuances of real-world scenarios.

Chapter 4

Q1: What is code reusability in Java?


A: Code reusability refers to the practice of using existing code for
new functions or programs instead of writing new code from scratch.
This is achieved through mechanisms like classes, interfaces, and
inheritance in Java.
Q2: How does inheritance contribute to code reusability?
A: Inheritance allows a new class (subclass) to inherit properties and
methods from an existing class (superclass). This enables
developers to reuse existing code and extend functionality without
modifying the original code.

Example 1: Basic Inheritance

// Superclass
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}

// Subclass
class Dog extends Animal {
void bark() {
System.out.println("The dog barks.");
}
}

Java (OOP) 67
// Usage
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.eat(); // Inherited method
dog.bark(); // Dog's own method
}
}
Example 2: Method Overriding

// Superclass
class Vehicle {
void start() {
System.out.println("Vehicle is starting.");
}
}

// Subclass
class Car extends Vehicle {
@Override
void start() {
System.out.println("Car is starting.");
}
}

// Usage
public class Main {
public static void main(String[] args) {
Vehicle myCar = new Car();
myCar.start(); // Calls the overridden method in Car
}
}

Example 3: Multiple Levels of Inheritance

// Superclass
class Shape {
void display() {
System.out.println("This is a shape.");

Java (OOP) 68
}
}

// Intermediate subclass
class Circle extends Shape {
void draw() {
System.out.println("Drawing a circle.");
}
}

// Leaf subclass
class ColoredCircle extends Circle {
void fillColor() {
System.out.println("Filling the circle with color.");
}
}

// Usage
public class Main {
public static void main(String[] args) {
ColoredCircle coloredCircle = new ColoredCircle();
coloredCircle.display(); // Inherited from Shape
coloredCircle.draw(); // From Circle
coloredCircle.fillColor(); // From ColoredCircle
}
}

Example 4: Using Constructors in Inheritance


// Superclass
class Person {
String name;

Person(String name) {
this.name = name;
}
}

// Subclass
class Student extends Person {
int studentId;

Java (OOP) 69
Student(String name, int studentId) {
super(name); // Call superclass constructor
this.studentId = studentId;
}

void display() {
System.out.println("Name: " + name + ", Student ID: " +
studentId);
}
}

// Usage
public class Main {
public static void main(String[] args) {
Student student = new Student("Alice", 101);
student.display(); // Output: Name: Alice, Student ID: 101
}
}

Example 5: Abstract Classes and Inheritance

// Abstract superclass
abstract class Animal {
abstract void sound(); // Abstract method
}

// Subclass
class Cat extends Animal {
@Override
void sound() {
System.out.println("The cat meows.");
}
}

// Usage
public class Main {
public static void main(String[] args) {
Animal myCat = new Cat();
myCat.sound(); // Output: The cat meows.
}
}

Java (OOP) 70
Example 6: Interface Implementation with Inheritance
// Interface
interface Playable {
void play();
}

// Superclass
class Game {
void start() {
System.out.println("Game is starting.");
}
}

// Subclass implementing the interface


class Soccer extends Game implements Playable {
@Override
public void play() {
System.out.println("Playing soccer.");
}
}

// Usage
public class Main {
public static void main(String[] args) {
Soccer soccer = new Soccer();
soccer.start(); // From Game
soccer.play(); // From Playable
}
}

Q3: What are interfaces, and how do they promote code


reusability?
A: Interfaces define a contract that classes can implement. They
allow different classes to be treated in the same way, promoting
code reusability by enabling polymorphism. This means you can use
the same method names across different classes.

Example 1: Basic Interface Implementation

Java (OOP) 71
// Define an interface
interface Animal {
void sound();
}

// Implement the interface in different classes


class Dog implements Animal {
@Override
public void sound() {
System.out.println("Dog barks.");
}
}

class Cat implements Animal {


@Override
public void sound() {
System.out.println("Cat meows.");
}
}

// Usage
public class Main {
public static void main(String[] args) {
Animal myDog = new Dog();
Animal myCat = new Cat();

myDog.sound(); // Output: Dog barks.


myCat.sound(); // Output: Cat meows.
}
}

Example 2: Polymorphism with Interfaces

// Define the interface


interface Shape {
double area();
}

// Implement the interface in different classes


class Rectangle implements Shape {
private double width;

Java (OOP) 72
private double height;

Rectangle(double width, double height) {


this.width = width;
this.height = height;
}

@Override
public double area() {
return width * height;
}
}

class Circle implements Shape {


private double radius;

Circle(double radius) {
this.radius = radius;
}

@Override
public double area() {
return Math.PI * radius * radius;
}
}

// Usage
public class Main {
public static void main(String[] args) {
Shape[] shapes = { new Rectangle(4, 5), new Circle(3) };

for (Shape shape : shapes) {


System.out.println("Area: " + shape.area());
}
// Output:
// Area: 20.0
// Area: 28.274333882308138
}
}

Example 3: Multiple Interfaces

Java (OOP) 73
// Define the first interface
interface Playable {
void play();
}

// Define the second interface


interface Eatable {
void eat();
}

// Implement both interfaces in a single class


class Dog implements Playable, Eatable {
@Override
public void play() {
System.out.println("Dog is playing.");
}

@Override
public void eat() {
System.out.println("Dog is eating.");
}
}

// Usage
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.play(); // Output: Dog is playing.
dog.eat(); // Output: Dog is eating.
}
}

Example 4: Default Methods in Interfaces


// Define the interface with a default method
interface Vehicle {
void start();

default void honk() {


System.out.println("Vehicle is honking.");
}

Java (OOP) 74
}

// Implement the interface in a class


class Car implements Vehicle {
@Override
public void start() {
System.out.println("Car is starting.");
}
}

// Usage
public class Main {
public static void main(String[] args) {
Car car = new Car();
car.start(); // Output: Car is starting.
car.honk(); // Output: Vehicle is honking.
}
}

Example 5: Interface as a Parameter

// Define the interface


interface Greeting {
void greet(String name);
}

// Implement the interface in different classes


class EnglishGreeting implements Greeting {
@Override
public void greet(String name) {
System.out.println("Hello, " + name + "!");
}
}

class SpanishGreeting implements Greeting {


@Override
public void greet(String name) {
System.out.println("¡Hola, " + name + "!");
}
}

Java (OOP) 75
// Method that uses the interface
public class Main {
public static void displayGreeting(Greeting greeting, String name)
{
greeting.greet(name);
}

public static void main(String[] args) {


Greeting english = new EnglishGreeting();
Greeting spanish = new SpanishGreeting();

displayGreeting(english, "Alice"); // Output: Hello, Alice!


displayGreeting(spanish, "Carlos"); // Output: ¡Hola, Carlos!
}
}

Example 6: Marker Interface


// Define a marker interface
interface Serializable {}

// A class implementing the marker interface


class Data implements Serializable {
// Class implementation
}

// Usage of the marker interface


public class Main {
public static void main(String[] args) {
Data data = new Data();
if (data instanceof Serializable) {
System.out.println("Data is serializable.");
} else {
System.out.println("Data is not serializable.");
}
// Output: Data is serializable.
}
}

Q4: Can you explain the concept of composition and how it


supports code reusability?

Java (OOP) 76
A: Composition involves building classes using references to other
classes, rather than inheriting from them. This allows for greater
flexibility and reusability, as you can combine different components
to create new functionality without the constraints of a class
hierarchy.
Example 1: Basic Composition
// Class representing an Engine
class Engine {
void start() {
System.out.println("Engine starting...");
}
}

// Class representing a Car that uses composition


class Car {
private Engine engine; // Reference to Engine

Car() {
this.engine = new Engine(); // Composition
}

void startCar() {
engine.start(); // Delegating the start action to the engine
System.out.println("Car is ready to go!");
}
}

// Usage
public class Main {
public static void main(String[] args) {
Car car = new Car();
car.startCar();
// Output:
// Engine starting...
// Car is ready to go!
}
}

Example 2: Composition with Multiple Components


// Class representing a Wheel
class Wheel {

Java (OOP) 77
void roll() {
System.out.println("Wheel is rolling.");
}
}

// Class representing a Car that uses multiple components


class Car {
private Engine engine; // Engine component
private Wheel[] wheels; // Array of Wheel components

Car() {
this.engine = new Engine();
this.wheels = new Wheel[4]; // A car typically has 4 wheels
for (int i = 0; i < wheels.length; i++) {
wheels[i] = new Wheel();
}
}

void startCar() {
engine.start();
for (Wheel wheel : wheels) {
wheel.roll();
}
System.out.println("Car is ready to go!");
}
}

// Usage
public class Main {
public static void main(String[] args) {
Car car = new Car();
car.startCar();
// Output:
// Engine starting...
// Wheel is rolling.
// Wheel is rolling.
// Wheel is rolling.
// Wheel is rolling.
// Car is ready to go!
}
}

Java (OOP) 78
Example 3: Using Interfaces for Composition
// Interface for Flyable
interface Flyable {
void fly();
}

// Class representing a Bird


class Bird implements Flyable {
@Override
public void fly() {
System.out.println("Bird is flying.");
}
}

// Class representing a Plane


class Plane implements Flyable {
@Override
public void fly() {
System.out.println("Plane is flying.");
}
}

// Class that uses composition with Flyable components


class FlyingMachine {
private Flyable flyable; // Composition

FlyingMachine(Flyable flyable) {
this.flyable = flyable;
}

void performFlight() {
flyable.fly(); // Delegating the flight action
}
}

// Usage
public class Main {
public static void main(String[] args) {
FlyingMachine birdMachine = new FlyingMachine(new Bird());

Java (OOP) 79
FlyingMachine planeMachine = new FlyingMachine(new
Plane());

birdMachine.performFlight(); // Output: Bird is flying.


planeMachine.performFlight(); // Output: Plane is flying.
}
}

Example 4: Composition with Configuration


// Class representing a configuration
class Configuration {
private String setting;

Configuration(String setting) {
this.setting = setting;
}

String getSetting() {
return setting;
}
}

// Class that uses composition to apply a configuration


class Application {
private Configuration config; // Composition

Application(Configuration config) {
this.config = config;
}

void run() {
System.out.println("Application running with setting: " +
config.getSetting());
}
}

// Usage
public class Main {
public static void main(String[] args) {
Configuration config = new Configuration("High Performance");
Application app = new Application(config);

Java (OOP) 80
app.run(); // Output: Application running with setting: High
Performance
}
}

Example 5: Dynamic Composition

// Class representing a Printer


class Printer {
void print(String message) {
System.out.println("Printing: " + message);
}
}

// Class representing a Document that uses composition


class Document {
private Printer printer; // Composition

Document(Printer printer) {
this.printer = printer; // Dependency injection
}

void printDocument(String content) {


printer.print(content); // Delegating print action
}
}

// Usage
public class Main {
public static void main(String[] args) {
Printer printer = new Printer();
Document doc = new Document(printer);
doc.printDocument("Hello, World!"); // Output: Printing: Hello,
World!
}
}

Example 6: Composition Over Inheritance


// Class representing a Sound System
class SoundSystem {
void playMusic() {

Java (OOP) 81
System.out.println("Playing music...");
}
}

// Class representing a Home Theater that uses composition


class HomeTheater {
private SoundSystem soundSystem; // Composition

HomeTheater() {
this.soundSystem = new SoundSystem(); // Composition
}

void watchMovie() {
System.out.println("Setting up the home theater...");
soundSystem.playMusic(); // Using the composed object
System.out.println("Enjoy the movie!");
}
}

// Usage
public class Main {
public static void main(String[] args) {
HomeTheater homeTheater = new HomeTheater();
homeTheater.watchMovie();
// Output:
// Setting up the home theater...
// Playing music...
// Enjoy the movie!
}
}

Q5: What is the DRY principle, and how does it relate to code
reusability?
A: The DRY (Don't Repeat Yourself) principle emphasizes reducing
code duplication. By reusing code through methods, classes, or
libraries, developers can adhere to this principle, making their
codebase cleaner and easier to maintain.
Q6: How can libraries and frameworks aid in code
reusability?
A: Libraries and frameworks provide pre-written code for common
tasks, allowing developers to leverage existing solutions rather than

Java (OOP) 82
creating new ones. This accelerates development and ensures
consistency across applications.
Q7: What role do design patterns play in code reusability?
A: Design patterns are established solutions to common problems in
software design. By following these patterns, developers can create
reusable code structures that facilitate easier maintenance and
scalability.
Q8: How can generic programming enhance code reusability
in Java?
A: Generic programming allows developers to define classes,
interfaces, and methods with type parameters. This enables the
creation of flexible and reusable code that can work with any data
type, reducing redundancy.
Q9: What is the significance of modular programming in
terms of code reusability?
A: Modular programming involves breaking down a program into
smaller, manageable, and reusable modules. This makes it easier to
test, maintain, and reuse code across different projects.
Q10: Can you provide an example of how to achieve code
reusability with methods in Java?
A: Yes! Here’s a simple example:
java
Copy
public class MathUtils {
// Method to add two numbers
public static int add(int a, int b) {
return a + b;
}

// Method to multiply two numbers


public static int multiply(int a, int b) {
return a * b;
}
}

// Usage in another class


public class Main {
public static void main(String[] args) {
int sum = MathUtils.add(5, 10);
int product = MathUtils.multiply(5, 10);

System.out.println("Sum: " + sum); // Output: Sum: 15


System.out.println("Product: " + product); // Output: Product: 50
}
}

Java (OOP) 83
This example demonstrates how to create reusable methods in a
utility class, which can be called from other parts of the program.

Q11: What are static methods, and how do they promote


code reusability?
A: Static methods belong to the class rather than any instance of
the class. They can be called without creating an object, making
them ideal for utility or helper methods that can be reused
throughout the application.

Example 1: Basic Static Method


class MathUtils {
// Static method to add two numbers
static int add(int a, int b) {
return a + b;
}
}

// Usage
public class Main {
public static void main(String[] args) {
int sum = MathUtils.add(5, 10);
System.out.println("Sum: " + sum); // Output: Sum: 15
}
}

Example 2: Static Methods for Utility Functions


class StringUtils {
// Static method to reverse a string
static String reverse(String str) {
return new StringBuilder(str).reverse().toString();
}
}

// Usage
public class Main {

Java (OOP) 84
public static void main(String[] args) {
String original = "Hello";
String reversed = StringUtils.reverse(original);
System.out.println("Reversed: " + reversed); // Output:
Reversed: olleH
}
}

Example 3: Static Methods with Parameters


class Converter {
// Static method to convert Celsius to Fahrenheit
static double celsiusToFahrenheit(double celsius) {
return (celsius * 9/5) + 32;
}
}

// Usage
public class Main {
public static void main(String[] args) {
double celsius = 25;
double fahrenheit = Converter.celsiusToFahrenheit(celsius);
System.out.println(celsius + " °C = " + fahrenheit + " °F"); //
Output: 25.0 °C = 77.0 °F
}
}

Example 4: Static Block Initialization


class Config {
static String CONFIG;

// Static block to initialize static variables


static {
CONFIG = "Application Configuration Loaded";
}

// Static method to display configuration


static void displayConfig() {
System.out.println(CONFIG);
}
}

Java (OOP) 85
// Usage
public class Main {
public static void main(String[] args) {
Config.displayConfig(); // Output: Application Configuration
Loaded
}
}

Example 5: Static Methods in a Singleton Patter


class Singleton {
private static Singleton instance;

// Private constructor to prevent instantiation


private Singleton() {}

// Static method to provide access to the instance


public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}

void showMessage() {
System.out.println("Hello from Singleton!");
}
}

// Usage
public class Main {
public static void main(String[] args) {
Singleton singleton = Singleton.getInstance();
singleton.showMessage(); // Output: Hello from Singleton!
}
}

Example 6: Static Methods with Overloading


class Display {
// Static method to display an integer
static void show(int number) {
System.out.println("Integer: " + number);

Java (OOP) 86
}

// Overloaded static method to display a string


static void show(String message) {
System.out.println("Message: " + message);
}
}

// Usage
public class Main {
public static void main(String[] args) {
Display.show(100); // Output: Integer: 100
Display.show("Hello!"); // Output: Message: Hello!
}
}

Example 7: Static Methods in a Math Library


class MathLibrary {
// Static method to compute the factorial of a number
static long factorial(int n) {
if (n == 0) return 1;
long result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
}

// Usage
public class Main {
public static void main(String[] args) {
int number = 5;
long fact = MathLibrary.factorial(number);
System.out.println("Factorial of " + number + " is " + fact); //
Output: Factorial of 5 is 120
}
}

Java (OOP) 87
Q12: How does the use of packages enhance code reusability
in Java?
A: Packages group related classes and interfaces, making it easier
to organize code. By using packages, developers can import and
reuse classes across different projects, promoting modular design
and reducing redundancy.

Example 1: Creating and Using a Package


MathUtils Class in Package

src/
└── com/
└── example/
└── utils/
└── MathUtils.java

// File: src/com/example/utils/MathUtils.java
package com.example.utils;

public class MathUtils {


public static int add(int a, int b) {
return a + b;
}

public static int subtract(int a, int b) {


return a - b;
}
}

Using the Package in Another Class

Create another class to use the MathUtils class:

// File: src/Main.java

import com.example.utils.MathUtils;

Java (OOP) 88
public class Main {

public static void main(String[] args) {

int sum = MathUtils.add(10, 5);

int difference = MathUtils.subtract(10, 5);

System.out.println("Sum: " + sum); // Output: Sum: 15

System.out.println("Difference: " + difference); // Output:


Difference: 5

Example 2: Creating a Package with Multiple Classes


src/

└── com/

└── example/

└── shapes/

├── Circle.java

└── Rectangle.java

Circle Class

// File: src/com/example/shapes/Circle.java

package com.example.shapes;

public class Circle {

private double radius;

Java (OOP) 89
public Circle(double radius) {

this.radius = radius;

public double area() {

return Math.PI * radius * radius;

Rectangle Class

// File: src/com/example/shapes/Rectangle.java

package com.example.shapes;

public class Rectangle {

private double width;

private double height;

public Rectangle(double width, double height) {

this.width = width;

this.height = height;

Java (OOP) 90
public double area() {

return width * height;

Using the Package

// File: src/Main.java

import com.example.shapes.Circle;

import com.example.shapes.Rectangle;

public class Main {

public static void main(String[] args) {

Circle circle = new Circle(5);

Rectangle rectangle = new Rectangle(4, 6);

System.out.println("Circle Area: " + circle.area()); // Output:


Circle Area: 78.53981633974483

System.out.println("Rectangle Area: " + rectangle.area()); //


Output: Rectangle Area: 24.0

Example 3: Using import Statements

Java (OOP) 91
1. Creating a New Package

src/

└── com/

└── example/

└── animals/

├── Dog.java

└── Cat.java

Dog Class

// File: src/com/example/animals/Dog.java

package com.example.animals;

public class Dog {

public void bark() {

System.out.println("Dog barks!");

Cat Class

// File: src/com/example/animals/Cat.java

package com.example.animals;

public class Cat {

public void meow() {

Java (OOP) 92
System.out.println("Cat meows!");

Using Import Statements

// File: src/Main.java

import com.example.animals.Dog;

import com.example.animals.Cat;

public class Main {

public static void main(String[] args) {

Dog dog = new Dog();

Cat cat = new Cat();

dog.bark(); // Output: Dog barks!

cat.meow(); // Output: Cat meows!

Example 4: Subpackages
1. Creating a Subpackage

src/

└── com/

└── example/

Java (OOP) 93
├── animals/

│ ├── Dog.java

│ └── Cat.java

└── services/

└── AnimalService.java

AnimalService Class

// File: src/com/example/services/AnimalService.java

package com.example.services;

import com.example.animals.Dog;

import com.example.animals.Cat;

public class AnimalService {

public void makeSound() {

Dog dog = new Dog();

Cat cat = new Cat();

dog.bark();

cat.meow();

Using the Subpackage

Java (OOP) 94
// File: src/Main.java

import com.example.services.AnimalService;

public class Main {

public static void main(String[] args) {

AnimalService animalService = new AnimalService();

animalService.makeSound();

// Output:

// Dog barks!

// Cat meows!

Example 5: Package Access Modifiers


1. Creating a Class with Default Access Modifier

// File: src/com/example/animals/Cat.java

package com.example.animals;

class Cat { // Default access modifier

public void meow() {

System.out.println("Cat meows!");

Java (OOP) 95
Accessing the Class from the Same Package

// File: src/com/example/animals/Dog.java

package com.example.animals;

public class Dog {

public void bark() {

Cat cat = new Cat(); // Accessible because it's in the same


package

cat.meow();

System.out.println("Dog barks!");

Using the Classes

// File: src/Main.java
import com.example.animals.Dog;

public class Main {


public static void main(String[] args) {
Dog dog = new Dog();
dog.bark();
// Output:
// Cat meows!
// Dog barks!
}
}

Java (OOP) 96
Q13: What is the importance of Java libraries in promoting
code reusability?
A: Java libraries, such as the Java Standard Library, provide pre-
written code for various functionalities (e.g., data structures,
networking). Developers can reuse these libraries to save time and
effort, ensuring reliability and efficiency.

Example 1: Using the Java Collections Framework


The Java Collections Framework provides classes for storing and
manipulating groups of data.

import java.util.ArrayList;
import java.util.Collections;

public class Main {


public static void main(String[] args) {
// Create a list using ArrayList
ArrayList<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");

// Sort the list


Collections.sort(names);

// Print the sorted list


System.out.println("Sorted names: " + names);
// Output: Sorted names: [Alice, Bob, Charlie]
}
}

Example 2: Using the Java Stream API


The Stream API allows for functional-style operations on streams of
elements.

import java.util.Arrays;
import java.util.List;

public class Main {


public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

Java (OOP) 97
// Use Stream API to filter and sum
int sum = numbers.stream()
.filter(n -> n % 2 == 0) // Only even numbers
.mapToInt(Integer::intValue)
.sum();

System.out.println("Sum of even numbers: " + sum); // Output:


Sum of even numbers: 6
}
}
Example 3: Using the java.time Package for Date and Time
The java.time package provides a modern date and time API.

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class Main {


public static void main(String[] args) {
// Get the current date
LocalDate today = LocalDate.now();
System.out.println("Today's date: " + today);

// Format the date


DateTimeFormatter formatter =
DateTimeFormatter.ofPattern("dd-MM-yyyy");
String formattedDate = today.format(formatter);
System.out.println("Formatted date: " + formattedDate);
// Output: Today's date: 2024-09-24 (example output)
// Output: Formatted date: 24-09-2024
}
}

Q14: How does the concept of "loose coupling" relate to


code reusability?
A: Loose coupling refers to designing components that are
independent of each other. This allows for easier code reuse, as
changes to one component do not affect others. It simplifies
maintenance and enhances flexibility in code design.
Q15: Can you explain how annotations can be used to
support code reusability?

Java (OOP) 98
A: Annotations provide metadata about code elements, allowing
frameworks to process them in reusable ways. For example, Java's
Spring framework uses annotations for dependency injection,
enabling reusable and configurable components.
Q16: What is the role of abstract classes in code reusability?
A: Abstract classes provide a base for other classes, allowing shared
code implementation while enforcing a contract for subclasses. This
promotes code reusability by allowing subclasses to inherit common
behaviors while defining specific implementations.

Example 1: Basic Abstract Class

// Abstract class
abstract class Animal {
// Abstract method (does not have a body)
abstract void sound();

// Concrete method
void sleep() {
System.out.println("Sleeping...");
}
}

// Subclass that extends the abstract class


class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks!");
}
}

// Usage
public class Main {
public static void main(String[] args) {
Animal myDog = new Dog();
myDog.sound(); // Output: Dog barks!
myDog.sleep(); // Output: Sleeping...
}
}

Example 2: Abstract Class with Constructor

Java (OOP) 99
// Abstract class
abstract class Vehicle {
private String brand;

// Constructor
Vehicle(String brand) {
this.brand = brand;
}

// Abstract method
abstract void start();

// Concrete method
String getBrand() {
return brand;
}
}

// Subclass that extends the abstract class


class Car extends Vehicle {
Car(String brand) {
super(brand); // Call the constructor of Vehicle
}

@Override
void start() {
System.out.println(getBrand() + " car is starting.");
}
}

// Usage
public class Main {
public static void main(String[] args) {
Vehicle myCar = new Car("Toyota");
myCar.start(); // Output: Toyota car is starting.
}
}

Example 3: Multiple Subclasses

// Abstract class

Java (OOP) 100


abstract class Shape {
abstract double area(); // Abstract method
}

// Subclass for Circle


class Circle extends Shape {
private double radius;

Circle(double radius) {
this.radius = radius;
}

@Override
double area() {
return Math.PI * radius * radius;
}
}

// Subclass for Rectangle


class Rectangle extends Shape {
private double width;
private double height;

Rectangle(double width, double height) {


this.width = width;
this.height = height;
}

@Override
double area() {
return width * height;
}
}

// Usage
public class Main {
public static void main(String[] args) {
Shape circle = new Circle(5);
Shape rectangle = new Rectangle(4, 6);

Java (OOP) 101


System.out.println("Circle Area: " + circle.area()); // Output:
Circle Area: 78.53981633974483
System.out.println("Rectangle Area: " + rectangle.area()); //
Output: Rectangle Area: 24.0
}
}

Example 4: Abstract Class with Method Implementation

// Abstract class
abstract class Employee {
String name;

Employee(String name) {
this.name = name;
}

// Abstract method
abstract double calculateSalary();

// Concrete method
void display() {
System.out.println("Employee Name: " + name);
}
}

// Subclass for FullTimeEmployee


class FullTimeEmployee extends Employee {
private double monthlySalary;

FullTimeEmployee(String name, double monthlySalary) {


super(name);
this.monthlySalary = monthlySalary;
}

@Override
double calculateSalary() {
return monthlySalary * 12; // Annual salary
}
}

Java (OOP) 102


// Subclass for PartTimeEmployee
class PartTimeEmployee extends Employee {
private double hourlyWage;
private int hoursWorked;

PartTimeEmployee(String name, double hourlyWage, int


hoursWorked) {
super(name);
this.hourlyWage = hourlyWage;
this.hoursWorked = hoursWorked;
}

@Override
double calculateSalary() {
return hourlyWage * hoursWorked; // Total earnings
}
}

// Usage
public class Main {
public static void main(String[] args) {
Employee fullTime = new FullTimeEmployee("Alice", 3000);
Employee partTime = new PartTimeEmployee("Bob", 20, 80);

fullTime.display();
System.out.println("Annual Salary: " +
fullTime.calculateSalary()); // Output: Annual Salary: 36000.0

partTime.display();
System.out.println("Total Earnings: " +
partTime.calculateSalary()); // Output: Total Earnings: 1600.0
}
}

Example 5: Abstract Class with Final Method

// Abstract class
abstract class Animal {
abstract void sound(); // Abstract method

// Final method

Java (OOP) 103


final void info() {
System.out.println("Animals are living beings.");
}
}

// Subclass
class Cat extends Animal {
@Override
void sound() {
System.out.println("Cat meows!");
}
}

// Usage
public class Main {
public static void main(String[] args) {
Animal myCat = new Cat();
myCat.sound(); // Output: Cat meows!
myCat.info(); // Output: Animals are living beings.
}
}

Q17: How can exception handling contribute to code


reusability?
A: By defining custom exceptions, developers can create reusable
error-handling mechanisms across applications. This encapsulates
error logic and allows consistent handling of specific scenarios,
making code more maintainable.
Q18: What are lambda expressions, and how do they
enhance code reusability?
A: Lambda expressions allow for the creation of anonymous
functions. They enable developers to pass behavior as parameters,
leading to more reusable and concise code, especially in functional
programming paradigms.
Q19: How can unit testing frameworks promote code
reusability?
A: Unit testing frameworks like JUnit allow developers to write
reusable test cases for their code. Once written, these tests can be
run against different versions of the code, ensuring functionality
remains consistent across changes.

Java (OOP) 104


Q20: What is the significance of version control in
maintaining reusable code?
A: Version control systems (e.g., Git) help track changes in code
over time. This allows developers to reuse stable versions of code,
collaborate effectively, and maintain a history of changes,
facilitating better management of reusable components.
Q21: How do functional interfaces support code reusability?
A: Functional interfaces (interfaces with a single abstract method)
allow for the use of lambda expressions and method references.
This encourages reusable code patterns, especially in APIs that
require callbacks or event handling.
Q22: Can you provide an example of using interfaces for
code reusability?
A: Here’s an example illustrating the use of interfaces:
Java

// Define a reusable interface


interface Shape {
double area();
}

// Implement the interface in different classes


class Circle implements Shape {
private double radius;

public Circle(double radius) {


this.radius = radius;
}

@Override
public double area() {
return Math.PI * radius * radius;
}
}

class Rectangle implements Shape {


private double width;
private double height;

public Rectangle(double width, double height) {


this.width = width;
this.height = height;
}

@Override
public double area() {
return width * height;
}
}

Java (OOP) 105


// Usage in another class
public class Main {
public static void main(String[] args) {
Shape circle = new Circle(5);
Shape rectangle = new Rectangle(4, 6);

System.out.println("Circle Area: " + circle.area()); //


Output: Circle Area: 78.53981633974483
System.out.println("Rectangle Area: " + rectangle.area()); //
Output: Rectangle Area: 24.0
}
}
This example shows how different shapes can implement a common
interface, promoting code reusability and flexibility in handling
different shape types through a unified method.

What is the output of the following code?

class Parent {

void display() {

System.out.println("Parent");

class Child extends Parent {

void display() {

System.out.println("Child");

public class Main {

Java (OOP) 106


public static void main(String[] args) {

Parent obj = new Child();

obj.display();

A) Parent
B) Child
C) Compilation Error
D) Runtime Error
Answer: B) Child

Which of the following is an example of polymorphism in


Java?
A) Method Overloading
B) Method Overriding
C) Both A and B
D) None of the above
Answer: C) Both A and B

Question 6: Composition vs Aggregation


Which of the following best describes composition?
A) A relationship where one class can contain references to another
class.
B) A relationship where one class can exist independently of the
other.
C) A "has-a" relationship that implies ownership.
D) Both A and C.
Answer: D) Both A and C.

Question 7: Method Overloading


What will be the output of the following code?

class Test {

void display(int a) {

Java (OOP) 107


System.out.println("Integer: " + a);

void display(double b) {

System.out.println("Double: " + b);

public class Main {

public static void main(String[] args) {

Test test = new Test();

test.display(10); // Line A

test.display(10.5); // Line B

A) Integer: 10
Double: 10.5
B) Compilation Error
C) Integer: 10
Double: 10
D) Integer: 10
Double: 10.0
Answer: A) Integer: 10
Double: 10.5

Question 8: Interface Implementation


What is the output of the following code?

interface Animal {

void sound();

Java (OOP) 108


}

class Dog implements Animal {

public void sound() {

System.out.println("Dog barks!");

public class Main {

public static void main(String[] args) {

Animal myDog = new Dog();

myDog.sound();

A) Dog barks!
B) Compilation Error
C) Runtime Error
D) No output
Answer: A) Dog barks!

Question 9: Abstract Method


What happens if a class extends an abstract class but does
not implement its abstract methods?
A) The class can be instantiated.
B) A compilation error occurs.
C) The class is automatically made abstract.
D) Both B and C.
Answer: D) Both B and C.

Question 10: Aggregation


Which of the following statements about aggregation is
correct?
A) The lifetime of the contained object is managed by the container
object.

Java (OOP) 109


B) It represents a "part-of" relationship.
C) The contained object can exist independently of the container
object.
D) Both B and C.
Answer: D) Both B and C.

Question 11: Method Overriding


What is the result of the following code?

class Base {

void show() {

System.out.println("Base class");

class Derived extends Base {

void show() {

System.out.println("Derived class");

public class Main {

public static void main(String[] args) {

Base obj = new Derived();

obj.show();

A) Base class
B) Derived class
C) Compilation Error
D) Runtime Error
Java (OOP) 110
Answer: B) Derived class

Question 12: Final Keyword


What happens if you declare a class as final in Java?
A) The class can be inherited.
B) The class cannot be inherited.
C) The class cannot have any methods.
D) The class cannot be instantiated.
Answer: B) The class cannot be inherited.

Question 13: Abstract Class vs Interface


Which of the following statements is true regarding abstract
classes and interfaces?
A) An abstract class can implement multiple interfaces, but an
interface cannot extend classes.
B) An interface can have constructors, but an abstract class cannot.
C) An abstract class can have instance variables, but an interface
cannot.
D) Both A and C.
Answer: D) Both A and C.

Question 14: Composition Example


Which of the following best describes the relationship shown
in the code below?

class Engine {

// Engine properties and methods

class Car {

private Engine engine; // Composition relationship

Car(Engine engine) {

this.engine = engine;

Java (OOP) 111


}

A) Aggregation
B) Composition
C) Inheritance
D) Polymorphism

Answer: B) Composition

Question 15: Polymorphism with Interfaces


What will be the output of the following code?

interface Shape {

void draw();

class Circle implements Shape {

public void draw() {

System.out.println("Drawing Circle");

class Square implements Shape {

public void draw() {

System.out.println("Drawing Square");

public class Main {

public static void main(String[] args) {

Java (OOP) 112


Shape shape1 = new Circle();

Shape shape2 = new Square();

shape1.draw();

shape2.draw();

A) Drawing Circle
Drawing Square
B) Compilation Error
C) Drawing Circle
Circle
D) Drawing Square
Square
Answer: A) Drawing Circle
Drawing Square

Question 16: Abstract Class Instantiation


Can you instantiate an abstract class in Java?
A) Yes, it can be instantiated.
B) No, it cannot be instantiated.
C) Only if it has concrete methods.
D) Only if it has a constructor.
Answer: B) No, it cannot be instantiated.

Question 17: Inheritance Hierarchy


Given the following class hierarchy, what will be the output
of the code?

class Animal {

void eat() {

System.out.println("Animal eats");

Java (OOP) 113


class Dog extends Animal {

void bark() {

System.out.println("Dog barks");

public class Main {

public static void main(String[] args) {

Animal obj = new Dog();

obj.eat();

// obj.bark(); // Uncommenting this line will cause an error

A) Animal eats
B) Dog barks
C) Compilation Error
D) Runtime Error
Answer: A) Animal eats

Question 18: Interface Inheritance


Which of the following is true about an interface inheriting
another interface?
A) An interface cannot extend another interface.
B) An interface can extend multiple interfaces.
C) An interface can have constructors.
D) An interface can implement other interfaces.
Answer: B) An interface can extend multiple interfaces.

Question 19: Method Overloading


What is method overloading?
A) Defining multiple methods with the same name in different
classes.
B) Defining multiple methods with the same name but different

Java (OOP) 114


parameters in the same class.
C) Overriding a method in a subclass.
D) Changing the return type of a method.
Answer: B) Defining multiple methods with the same name but
different parameters in the same class.

Question 20: Access Modifiers


Which access modifier allows a class to be accessible only
within its own package?
A) public
B) private
C) protected
D) Default (no modifier)
Answer: D) Default (no modifier)

Question 21: Interface Implementation


If a class implements an interface, what must it do?
A) Provide implementations for all methods declared in the
interface.
B) Only implement some methods from the interface.
C) It can leave the methods unimplemented.
D) It can inherit from another class.
Answer: A) Provide implementations for all methods declared in the
interface.

Question 22: Abstract Class with Final Method


What will happen if you declare a method in an abstract
class as final?
A) The method can be overridden in subclasses.
B) The method cannot be overridden in subclasses.
C) The method cannot be defined in the abstract class.
D) The method must be abstract.
Answer: B) The method cannot be overridden in subclasses.

Question 23: Composition vs Inheritance


Which statement best describes the difference between
composition and inheritance?

Java (OOP) 115


A) Composition is a "is-a" relationship; inheritance is a "has-a"
relationship.
B) Inheritance is a "is-a" relationship; composition is a "has-a"
relationship.
C) Both represent the same relationship.
D) Neither supports code reusability.
Answer: B) Inheritance is a "is-a" relationship; composition is a
"has-a" relationship.
Question 24: Polymorphism at Runtime
What is runtime polymorphism in Java?
A) It occurs when a method is overloaded.
B) It is achieved through method overriding.
C) It is determined at compile-time.
D) It cannot be achieved in Java.
Answer: B) It is achieved through method overriding.

Question 25: Abstract Classes and Interfaces


Which of the following statements is false?
A) An abstract class can have both abstract and concrete methods.
B) An interface can have only abstract methods.
C) A class can implement multiple interfaces.
D) An abstract class can implement multiple interfaces.
Answer: B) An interface can have only abstract methods. (As of
Java 8, interfaces can also have default and static methods.)

Let’s illustrate various object-oriented programming concepts in


Java using the School Structure as an example. This example will
cover code reusability, inheritance, polymorphism, method
overriding, abstract classes, and interfaces.
1. Code Reusability
Code reusability is achieved through inheritance and interfaces. It
allows you to use existing code without rewriting it.
2. Concepts of Inheritance
Inheritance is a mechanism where one class (subclass/child) can
inherit fields and methods from another class (superclass/parent).
This promotes code reusability and establishes a hierarchical
relationship.
3. Implementing Inheritance

Java (OOP) 116


Example: School Structure
java
Copy
// Base class
class Person {
String name;
int age;

Person(String name, int age) {


this.name = name;
this.age = age;
}

void displayInfo() {
System.out.println("Name: " + name + ", Age: " + age);
}
}

// Derived class
class Student extends Person {
String studentID;

Student(String name, int age, String studentID) {


super(name, age); // Call the constructor of Person
this.studentID = studentID;
}

void displayInfo() {
super.displayInfo(); // Call the parent method
System.out.println("Student ID: " + studentID);
}
}

// Derived class
class Teacher extends Person {
String subject;

Teacher(String name, int age, String subject) {


super(name, age);
this.subject = subject;
}

void displayInfo() {
super.displayInfo();
System.out.println("Subject: " + subject);
}
}

public class School {


public static void main(String[] args) {
Student student = new Student("Alice", 20, "S123");
Teacher teacher = new Teacher("Mr. Smith", 40, "Mathematics");

Java (OOP) 117


student.displayInfo();
teacher.displayInfo();
}
}
Output:
Copy
Name: Alice, Age: 20
Student ID: S123
Name: Mr. Smith, Age: 40
Subject: Mathematics
4. Polymorphism & Method Overriding
Polymorphism allows methods to perform differently based on the
object that it is acting upon. Method overriding is a way to
achieve polymorphism.
Example:
java
Copy
// Base class
class Person {
void displayRole() {
System.out.println("I am a person.");
}
}

// Derived class
class Student extends Person {
@Override
void displayRole() {
System.out.println("I am a student.");
}
}

// Derived class
class Teacher extends Person {
@Override
void displayRole() {
System.out.println("I am a teacher.");
}
}

public class PolymorphismExample {


public static void main(String[] args) {
Person person1 = new Student();
Person person2 = new Teacher();

person1.displayRole(); // Output: I am a student.


person2.displayRole(); // Output: I am a teacher.
}
}

Java (OOP) 118


Output:
Copy
I am a student.
I am a teacher.
5. Abstract Classes & Interfaces
Abstract Classes provide a base for other classes. They can have
abstract methods (without body) that must be implemented by
subclasses.
Interfaces are contracts that classes can implement. They can
declare methods that must be defined in the classes that implement
them.
Example:
java
Copy
// Abstract class
abstract class Employee {
String name;

Employee(String name) {
this.name = name;
}

abstract void work(); // Abstract method


}

// Interface
interface Teach {
void teach();
}

// Derived class
class Teacher extends Employee implements Teach {
Teacher(String name) {
super(name);
}

@Override
void work() {
System.out.println(name + " is preparing lessons.");
}

@Override
public void teach() {
System.out.println(name + " is teaching.");
}
}

// Derived class
class Admin extends Employee {

Java (OOP) 119


Admin(String name) {
super(name);
}

@Override
void work() {
System.out.println(name + " is managing the school.");
}
}

public class SchoolStructure {


public static void main(String[] args) {
Teacher teacher = new Teacher("Mr. Smith");
Admin admin = new Admin("Mrs. Johnson");

teacher.work();
teacher.teach();
admin.work();
}
}
Output:
Copy
Mr. Smith is preparing lessons.
Mr. Smith is teaching.
Mrs. Johnson is managing the school.
6. Real-World Examples of Inheritance & Polymorphism
In a school system, you might have various roles that can be
modeled using inheritance and polymorphism.
Example of Real-World Application:
java
Copy
// Base class
class Course {
String courseName;

Course(String courseName) {
this.courseName = courseName;
}

void displayCourseInfo() {
System.out.println("Course: " + courseName);
}
}

// Derived class
class MathCourse extends Course {
MathCourse() {
super("Mathematics");
}

Java (OOP) 120


@Override
void displayCourseInfo() {
System.out.println("This is a Math course.");
}
}

// Derived class
class ScienceCourse extends Course {
ScienceCourse() {
super("Science");
}

@Override
void displayCourseInfo() {
System.out.println("This is a Science course.");
}
}

public class CourseExample {


public static void main(String[] args) {
Course math = new MathCourse();
Course science = new ScienceCourse();

math.displayCourseInfo(); // Output: This is a Math course.


science.displayCourseInfo(); // Output: This is a Science course.
}
}
Output:
Copy
This is a Math course.
This is a Science course.
Summary
 Code Reusability: Achieved through inheritance and
interfaces, allowing classes to reuse existing code.
 Inheritance: Establishes a hierarchical relationship, promoting
code reuse.
 Polymorphism & Method Overriding: Enables objects to be
treated as instances of their parent class, allowing method
implementation to vary based on object type.
 Abstract Classes & Interfaces: Provide a blueprint for other
classes and define contracts for methods that must be
implemented.
 Real-World Examples: Illustrate how these concepts apply to
common structures like schools, showcasing the utility of
inheritance and polymorphism in modeling various roles and
behaviors.
These examples demonstrate how to effectively use object-oriented
principles in Java to create a flexible and maintainable codebase.
Java (OOP) 121
Let’s expand on the concepts of inheritance, polymorphism, abstract
classes, and interfaces in Java, along with their implications in
software design, using our school structure example.
1. Code Reusability
Concept:
Code reusability means using existing code to create new
functionality without rewriting code. This is crucial in software
development as it reduces duplication, minimizes errors, and
enhances maintainability.
Benefits:
 Efficiency: Saves time and effort as developers can leverage
existing code.
 Consistency: Changes made in one place automatically
propagate to all classes that use that code.
 Maintainability: Easier to manage and update code, as
changes are centralized.
In Our Example:
In the school structure, classes like Student and Teacher inherit
common attributes and methods from the Person class, avoiding
duplication of code related to basic attributes like name and age.
2. Concepts of Inheritance
Definition:
Inheritance is a fundamental concept in object-oriented
programming that allows a new class (subclass) to inherit properties
and behaviors (methods) from an existing class (superclass). This
forms a parent-child relationship.
Types of Inheritance:
1. Single Inheritance: A class inherits from one superclass.
2. Multiple Inheritance (via Interfaces): A class can
implement multiple interfaces, overcoming the limitations of
single inheritance.
3. Multilevel Inheritance: A class inherits from a subclass,
forming a chain (e.g., Animal → Dog → Beagle).
4. Hierarchical Inheritance: Multiple subclasses inherit from a
single superclass.
In Our Example:
Student and Teacher inherit from the Person class, gaining access to its
attributes and methods.

Java (OOP) 122


3. Implementing Inheritance
Example Code Explanation:
java
Copy
// Base class
class Person {
String name;
int age;

Person(String name, int age) {


this.name = name;
this.age = age;
}

void displayInfo() {
System.out.println("Name: " + name + ", Age: " + age);
}
}

// Derived classes
class Student extends Person {
String studentID;

Student(String name, int age, String studentID) {


super(name, age); // Calls the constructor of Person
this.studentID = studentID;
}

void displayInfo() {
super.displayInfo(); // Calls the parent method
System.out.println("Student ID: " + studentID);
}
}

class Teacher extends Person {


String subject;

Teacher(String name, int age, String subject) {


super(name, age); // Calls the constructor of Person
this.subject = subject;
}

void displayInfo() {
super.displayInfo(); // Calls the parent method
System.out.println("Subject: " + subject);
}
}
4. Polymorphism & Method Overriding
Definition:
Polymorphism allows objects to be treated as instances of their
parent class, enabling a single interface to be used for different data
Java (OOP) 123
types. This is achieved through method overriding, where a subclass
provides a specific implementation of a method declared in its
superclass.
Benefits:
 Flexibility: Code can handle different types of objects through
a common interface.
 Extensibility: New classes can be added with minimal
changes to existing code.
Example Code Explanation:
java
Copy
class Person {
void displayRole() {
System.out.println("I am a person.");
}
}

class Student extends Person {


@Override
void displayRole() {
System.out.println("I am a student.");
}
}

class Teacher extends Person {


@Override
void displayRole() {
System.out.println("I am a teacher.");
}
}

public class PolymorphismExample {


public static void main(String[] args) {
Person person1 = new Student(); // Upcasting
Person person2 = new Teacher(); // Upcasting

person1.displayRole(); // Output: I am a student.


person2.displayRole(); // Output: I am a teacher.
}
}
5. Abstract Classes & Interfaces
Abstract Classes:
 Definition: An abstract class cannot be instantiated and may
contain abstract methods (methods without a body) that must
be implemented by subclasses.
 Use Case: Ideal for defining a common base with shared
behavior while leaving implementation details to subclasses.

Java (OOP) 124


Interfaces:
 Definition: An interface defines a contract for classes,
specifying methods that must be implemented but cannot
provide any implementation itself.
 Use Case: Useful for defining capabilities that can be shared
across unrelated classes through multiple inheritance.
Example Code Explanation:
java
Copy
abstract class Employee {
String name;

Employee(String name) {
this.name = name;
}

abstract void work(); // Abstract method


}

interface Teach {
void teach(); // Method declaration
}

class Teacher extends Employee implements Teach {


Teacher(String name) {
super(name);
}

@Override
void work() {
System.out.println(name + " is preparing lessons.");
}

@Override
public void teach() {
System.out.println(name + " is teaching.");
}
}

// Another derived class


class Admin extends Employee {
Admin(String name) {
super(name);
}

@Override
void work() {
System.out.println(name + " is managing the school.");
}
}

Java (OOP) 125


6. Real-World Examples of Inheritance & Polymorphism
Use Case in School Systems:
 Inheritance: Different roles (students, teachers,
administrators) utilize a common Person class, allowing for
shared attributes while also having specific behaviors.
 Polymorphism: Functions that accept Person objects can
handle any subclass (like Student or Teacher), allowing for
dynamic method resolution based on the actual object type at
runtime.
Example Code Explanation:
java
Copy
class Course {
String courseName;

Course(String courseName) {
this.courseName = courseName;
}

void displayCourseInfo() {
System.out.println("Course: " + courseName);
}
}

class MathCourse extends Course {


MathCourse() {
super("Mathematics");
}

@Override
void displayCourseInfo() {
System.out.println("This is a Math course.");
}
}

class ScienceCourse extends Course {


ScienceCourse() {
super("Science");
}

@Override
void displayCourseInfo() {
System.out.println("This is a Science course.");
}
}

public class CourseExample {


public static void main(String[] args) {
Course math = new MathCourse();

Java (OOP) 126


Course science = new ScienceCourse();

math.displayCourseInfo(); // Output: This is a Math course.


science.displayCourseInfo(); // Output: This is a Science course.
}
}
Summary of Key Concepts
1. Code Reusability: Achieved through inheritance and
interfaces, reducing redundancy.
2. Inheritance: Establishes a hierarchical relationship among
classes, allowing subclasses to inherit and extend functionality.
3. Polymorphism: Enables the use of a single interface to
represent different underlying forms (data types), enhancing
flexibility.
4. Method Overriding: Allows a subclass to provide a specific
implementation of a method already defined in its superclass.
5. Abstract Classes & Interfaces: Provide a way to define
common functionality and ensure that certain methods are
implemented by subclasses or implementing classes.
6. Real-World Examples: Help to visualize how these concepts
apply to everyday scenarios like school systems, enhancing
understanding of OOP principles.
Conclusion
Understanding these object-oriented programming concepts in Java
is crucial for building robust, maintainable software systems. They
enable developers to create flexible designs that can evolve over
time, adapting to new requirements without significant rewrites of
existing code.

Q&A Examples

Q1: What is inheritance in Java, and why is it important?


A1:
Inheritance in Java is a mechanism that allows one class (subclass)
to inherit properties and methods from another class (superclass). It
is important because it promotes code reusability, enables
polymorphism, and establishes a hierarchical relationship between
classes, making the code more organized and easier to maintain.

Java (OOP) 127


Q2: How do you implement inheritance in Java? Provide a
code example.
A2:
Inheritance is implemented using the extends keyword. Here’s a
simple example:
java
Copy
class Person {
String name;

Person(String name) {
this.name = name;
}
}

class Student extends Person {


String studentID;

Student(String name, String studentID) {


super(name); // Calls the constructor of Person
this.studentID = studentID;
}
}
In this example, the Student class inherits from the Person class.

Q3: What is polymorphism, and how does it work?


A3:
Polymorphism is the ability of objects to be treated as instances of
their parent class, allowing for method overriding. It enables a single
interface to represent different underlying forms (data types). This
means that a method can perform differently based on the object
that it is acting upon.

Q4: Can you give an example of method overriding?


A4:
Sure! Here’s an example of method overriding:
java
Copy
class Person {
void displayRole() {
System.out.println("I am a person.");
}
}

Java (OOP) 128


class Teacher extends Person {
@Override
void displayRole() {
System.out.println("I am a teacher.");
}
}

public class Test {


public static void main(String[] args) {
Person person = new Teacher();
person.displayRole(); // Output: I am a teacher.
}
}
In this example, the Teacher class overrides the displayRole method of
the Person class.

Q5: What is the difference between an abstract class and an


interface?
A5:
 Abstract Class: Can have both abstract methods (without a
body) and concrete methods (with a body). A class can extend
only one abstract class (single inheritance).
 Interface: Contains only abstract methods (until Java 8) and
can be implemented by multiple classes (multiple inheritance).
Classes can implement multiple interfaces.

Q6: How do you define an abstract class in Java?


A6:
An abstract class is defined using the abstract keyword. Here’s an
example:
java
Copy
abstract class Employee {
String name;

Employee(String name) {
this.name = name;
}

abstract void work(); // Abstract method


}

class Teacher extends Employee {


Teacher(String name) {
super(name);

Java (OOP) 129


}

@Override
void work() {
System.out.println(name + " is teaching.");
}
}

Q7: Can you implement multiple interfaces in a class?


Provide an example.
A7:
Yes, a class can implement multiple interfaces. Here’s an example:
java
Copy
interface Teach {
void teach();
}

interface Manage {
void manage();
}

class Principal implements Teach, Manage {


String name;

Principal(String name) {
this.name = name;
}

@Override
public void teach() {
System.out.println(name + " is teaching.");
}

@Override
public void manage() {
System.out.println(name + " is managing the school.");
}
}
In this example, the Principal class implements
both Teach and Manage interfaces.

Q8: What is the benefit of using interfaces in Java?


A8:
The benefits of using interfaces include:
 Multiple Inheritance: A class can implement multiple
interfaces, allowing for more flexible architectures.

Java (OOP) 130


 Decoupling: Interfaces allow for decoupling of code, making it
easier to change implementations without affecting the code
that uses the interface.
 Polymorphism: Interfaces provide a way to achieve
polymorphism, as different classes can implement the same
interface in different ways.

Q9: What is method overloading, and how is it different from


method overriding?
A9:
 Method Overloading: Occurs when multiple methods in the
same class have the same name but different parameter lists
(type, number, or both). It is a compile-time polymorphism.
java
Copy
class MathOperations {
int add(int a, int b) {
return a + b;
}

double add(double a, double b) {


return a + b;
}
}
 Method Overriding: Occurs when a subclass provides a
specific implementation of a method that is already defined in
its superclass. This is a runtime polymorphism.

Q10: How does inheritance support code maintenance and


scalability in software development?
A10:
Inheritance supports code maintenance and scalability by:
 Centralizing Changes: Changes made in the superclass
automatically propagate to subclasses, reducing the risk of
errors and inconsistencies.
 Encouraging Reuse: Common functionality is defined in the
parent class, which can be reused by multiple subclasses,
reducing redundancy.
 Facilitating Extensibility: New subclasses can be added with
minimal changes to existing code, allowing the system to
evolve without major rewrites.

Java (OOP) 131


Multiple Choice Questions (MCQs)

Q1: What is the main purpose of inheritance in Java?


A) To allow a class to inherit properties from multiple classes
B) To promote code reusability and establish a hierarchical
relationship
C) To improve performance of the application
D) To hide implementation details
Answer: B) To promote code reusability and establish a hierarchical
relationship

Q2: Which keyword is used to indicate that a class is


inheriting from a superclass?
A) implements
B) extends
C) inherits
D) super
Answer: B) extends

Q3: What is polymorphism?


A) A method that can have multiple parameters
B) The ability to create multiple classes
C) The ability of a method to perform different tasks based on the
object that it is acting upon
D) The ability to call a method without an object
Answer: C) The ability of a method to perform different tasks based
on the object that it is acting upon

Q4: Which of the following is an example of method


overriding?
A) Defining a method with the same name but different parameters
in the same class
B) A subclass providing a specific implementation of a method
already defined in its superclass
C) Using the final keyword to prevent method changes
D) Overloading methods in different classes
Answer: B) A subclass providing a specific implementation of a
method already defined in its superclass

Java (OOP) 132


Q5: What is an abstract class in Java?
A) A class that cannot be instantiated and may contain abstract
methods
B) A class that contains only static methods
C) A class that has no methods
D) A class that can be instantiated
Answer: A) A class that cannot be instantiated and may contain
abstract methods

Q6: Which of the following is true about interfaces in Java?


A) A class can only implement one interface
B) Interfaces can contain method implementations
C) Interfaces support multiple inheritance
D) Interfaces cannot have any methods
Answer: C) Interfaces support multiple inheritance

Q7: Which of the following statements about method


overloading is true?
A) It occurs when two or more methods in the same class have the
same name and same parameters.
B) It is a way to achieve runtime polymorphism.
C) It can occur in the same class or in subclasses.
D) It allows methods to perform different tasks based on the
parameters passed.
Answer: D) It allows methods to perform different tasks based on
the parameters passed.

Q8: What happens if a subclass does not override a method


from its superclass?
A) The subclass will not compile.
B) The subclass will use the method implementation from the
superclass.
C) The method will throw an exception.
D) The subclass will have its own version of the method.
Answer: B) The subclass will use the method implementation from
the superclass.

Q9: What is the primary benefit of using abstract classes?


A) They can be instantiated directly.
B) They provide a common base with shared behavior while allowing
specific implementations.

Java (OOP) 133


C) They can only contain abstract methods.
D) They cannot have constructors.
Answer: B) They provide a common base with shared behavior
while allowing specific implementations.

Q10: Which of the following is a characteristic of


composition?
A) Strong ownership where the part cannot exist without the whole.
B) A weak relationship where the part can exist independently.
C) A mechanism that allows a class to inherit properties from
multiple classes.
D) A relationship that promotes multiple inheritance.
Answer: A) Strong ownership where the part cannot exist without
the whole.

Q11: Which of the following best describes the concept of


encapsulation?
A) Hiding the implementation details of a class and restricting
access to its internal state.
B) The ability to create multiple instances of a class.
C) The mechanism to inherit attributes from a superclass.
D) A way to group related classes.
Answer: A) Hiding the implementation details of a class and
restricting access to its internal state.

Q12: In which scenario would you typically use an interface?


A) When you want to define a common behavior for unrelated
classes.
B) When you want to create a class that cannot be instantiated.
C) When you want to implement a single inheritance structure.
D) When you want to prevent method overriding.
Answer: A) When you want to define a common behavior for
unrelated classes.

Q13: What is a key feature of an interface in Java?


A) It can have instance variables.
B) It can have concrete methods.
C) It can be extended by other interfaces.
D) It can be instantiated.
Answer: C) It can be extended by other interfaces.

Java (OOP) 134


Q14: Which of the following statements about constructors
in inheritance is true?
A) A subclass can call a superclass's constructor using
the this keyword.
B) A superclass constructor is always called automatically when a
subclass is instantiated.
C) Constructors cannot be inherited.
D) You can override constructors in Java.
Answer: C) Constructors cannot be inherited.

Q15: Which of the following is an example of multilevel


inheritance?
A) Class A extends Class B, and Class B extends Class C.
B) Class A implements Interface B and Interface C.
C) Class A extends Class B and Class C.
D) Class A and Class B both extend Class C.
Answer: A) Class A extends Class B, and Class B extends Class C.

Q16: Which of the following correctly implements an


interface?
A) class MyClass implements MyInterface { }
B) class MyClass inherits MyInterface { }
C) class MyClass extends MyInterface { }
D) class MyClass uses MyInterface { }
Answer: A) class MyClass implements MyInterface { }

Q17: What will happen if you try to instantiate an abstract


class?
A) The program will compile but throw an error at runtime.
B) The program will not compile.
C) The abstract class will be instantiated, but its methods will not be
usable.
D) The abstract class will be instantiated, but only its concrete
methods will be accessible.
Answer: B) The program will not compile.

Q18: Which keyword is used to prevent a method from being


overridden in a subclass?

Java (OOP) 135


A) final
B) static
C) abstract
D) private
Answer: A) final

Q19: Which of the following allows a class to inherit from


multiple sources?
A) Single inheritance
B) Multilevel inheritance
C) Interfaces
D) Abstract classes
Answer: C) Interfaces

Q20: What is the output of the following code?


java
Copy
class Base {
void display() {
System.out.println("Base class");
}
}

class Derived extends Base {


void display() {
System.out.println("Derived class");
}
}

public class Test {


public static void main(String[] args) {
Base b = new Derived();
b.display();
}
}
A) Base class
B) Derived class
C) Compilation error
D) Runtime error
Answer: B) Derived class

Java Coding Questions

Q21: Write a Java program to demonstrate method


overloading.
Answer:

Java (OOP) 136


java
Copy
class MathOperations {
int add(int a, int b) {
return a + b;
}

double add(double a, double b) {


return a + b;
}

public static void main(String[] args) {


MathOperations math = new MathOperations();
System.out.println("Integer addition: " + math.add(5, 10));
System.out.println("Double addition: " + math.add(5.5, 10.5));
}
}
Output:
Copy
Integer addition: 15
Double addition: 16.0

Q22: Write a Java program that uses inheritance to create a


simple hierarchy of animals.
Answer:
java
Copy
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}

class Dog extends Animal {


void sound() {
System.out.println("Dog barks");
}
}

class Cat extends Animal {


void sound() {
System.out.println("Cat meows");
}
}

public class AnimalTest {


public static void main(String[] args) {
Animal myDog = new Dog();
Animal myCat = new Cat();

myDog.sound(); // Dog barks


myCat.sound(); // Cat meows

Java (OOP) 137


}
}
Output:
Copy
Dog barks
Cat meows

Q23: Create an interface Shape with a method area() and


implement it in classes Circle and Rectangle.
Answer:
java
Copy
interface Shape {
double area();
}

class Circle implements Shape {


double radius;

Circle(double radius) {
this.radius = radius;
}

@Override
public double area() {
return Math.PI * radius * radius;
}
}

class Rectangle implements Shape {


double length, width;

Rectangle(double length, double width) {


this.length = length;
this.width = width;
}

@Override
public double area() {
return length * width;
}
}

public class ShapeTest {


public static void main(String[] args) {
Shape circle = new Circle(5);
Shape rectangle = new Rectangle(4, 6);

System.out.println("Circle area: " + circle.area());


System.out.println("Rectangle area: " + rectangle.area());
}
}

Java (OOP) 138


Output:
Copy
Circle area: 78.53981633974483
Rectangle area: 24.0

Q24: Write a Java program to demonstrate the use of an


abstract class.
Answer:
java
Copy
abstract class Vehicle {
abstract void start();
}

class Car extends Vehicle {


void start() {
System.out.println("Car is starting");
}
}

class Bike extends Vehicle {


void start() {
System.out.println("Bike is starting");
}
}

public class VehicleTest {


public static void main(String[] args) {
Vehicle myCar = new Car();
Vehicle myBike = new Bike();

myCar.start(); // Car is starting


myBike.start(); // Bike is starting
}
}
Output:
Copy
Car is starting
Bike is starting

Q25: Implement a class Employee with a method calculateSalary().


Create subclasses FullTimeEmployee and PartTimeEmployee that
override this method.
Answer:
java
Copy
class Employee {
double calculateSalary() {
return 0;
}

Java (OOP) 139


}

class FullTimeEmployee extends Employee {


double salary;

FullTimeEmployee(double salary) {
this.salary = salary;
}

@Override
double calculateSalary() {
return salary;
}
}

class PartTimeEmployee extends Employee {


double hourlyRate;
int hoursWorked;

PartTimeEmployee(double hourlyRate, int hoursWorked) {


this.hourlyRate = hourlyRate;
this.hoursWorked = hoursWorked;
}

@Override
double calculateSalary() {
return hourlyRate * hoursWorked;
}
}

public class EmployeeTest {


public static void main(String[] args) {
Employee emp1 = new FullTimeEmployee(3000);
Employee emp2 = new PartTimeEmployee(20, 80);

System.out.println("Full-Time Salary: " + emp1.calculateSalary());


System.out.println("Part-Time Salary: " + emp2.calculateSalary());
}
}
Output:
Copy
Full-Time Salary: 3000.0
Part-Time Salary: 1600.0

Q26: Which of the following statements about


the super keyword is true?
A) It can be used to call a static method in the superclass.
B) It refers to the superclass of the current object.

Java (OOP) 140


C) It can be used to access private members of the superclass.
D) It can be used only in static methods.
Answer: B) It refers to the superclass of the current object.

Q27: What will happen if you declare a class as final?


A) It can be subclassed.
B) It cannot be instantiated.
C) It cannot be subclassed.
D) It can only have final methods.
Answer: C) It cannot be subclassed.

Q28: Which of the following best describes the "is-a"


relationship in OOP?
A) Composition
B) Aggregation
C) Inheritance
D) Encapsulation
Answer: C) Inheritance

Q29: What is the output of the following code?


java
Copy
class Parent {
void show() {
System.out.println("Parent class");
}
}

class Child extends Parent {


void show() {
System.out.println("Child class");
}

void display() {
System.out.println("Display method in Child");
}
}

public class Test {


public static void main(String[] args) {
Parent obj = new Child();
obj.show();
obj.display(); // Compilation error
}
}
A) Parent class
B) Child class

Java (OOP) 141


C) Display method in Child
D) Compilation error
Answer: D) Compilation error

Q30: Which feature of OOP allows a subclass to provide a


specific implementation of a method already defined in its
superclass?
A) Method overloading
B) Method overriding
C) Encapsulation
D) Abstraction
Answer: B) Method overriding

Q31: What will be the result of the following code?


java
Copy
class Base {
void show() {
System.out.println("Base show");
}
}

class Derived extends Base {


void show() {
System.out.println("Derived show");
}

void display() {
System.out.println("Derived display");
}
}

public class Test {


public static void main(String[] args) {
Base obj = new Derived();
obj.show();
}
}
A) Base show
B) Derived show
C) Derived display
D) Compilation error
Answer: B) Derived show

Java Coding Questions

Java (OOP) 142


Q32: Write a Java program to demonstrate the concept of
multiple inheritance using interfaces.
Answer:
java
Copy
interface Walk {
void walk();
}

interface Swim {
void swim();
}

class Frog implements Walk, Swim {


@Override
public void walk() {
System.out.println("Frog is walking");
}

@Override
public void swim() {
System.out.println("Frog is swimming");
}
}

public class FrogTest {


public static void main(String[] args) {
Frog frog = new Frog();
frog.walk();
frog.swim();
}
}
Output:
Copy
Frog is walking
Frog is swimming

Q33: Create an abstract class Appliance with an abstract


method turnOn(). Implement it in a class WashingMachine.
Answer:
java
Copy
abstract class Appliance {
abstract void turnOn();
}

class WashingMachine extends Appliance {


@Override
void turnOn() {
System.out.println("Washing Machine is now ON");
}

Java (OOP) 143


}

public class ApplianceTest {


public static void main(String[] args) {
Appliance myWashingMachine = new WashingMachine();
myWashingMachine.turnOn(); // Washing Machine is now ON
}
}
Output:
Copy
Washing Machine is now ON

Q34: Write a Java program to illustrate the concept of


method overloading with two different methods
named multiply().
Answer:
java
Copy
class Calculator {
int multiply(int a, int b) {
return a * b;
}

double multiply(double a, double b) {


return a * b;
}
}

public class CalculatorTest {


public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println("Integer multiplication: " + calc.multiply(5, 4));
System.out.println("Double multiplication: " + calc.multiply(5.5,
4.5));
}
}
Output:
Copy
Integer multiplication: 20
Double multiplication: 24.75

Q35: Implement a class hierarchy for a library system with


classes Book, Magazine, and a base class Publication.
Answer:
java
Copy
class Publication {
String title;

Publication(String title) {

Java (OOP) 144


this.title = title;
}

void display() {
System.out.println("Title: " + title);
}
}

class Book extends Publication {


Book(String title) {
super(title);
}

@Override
void display() {
System.out.println("Book Title: " + title);
}
}

class Magazine extends Publication {


Magazine(String title) {
super(title);
}

@Override
void display() {
System.out.println("Magazine Title: " + title);
}
}

public class LibraryTest {


public static void main(String[] args) {
Publication book = new Book("Effective Java");
Publication magazine = new Magazine("National Geographic");

book.display(); // Book Title: Effective Java


magazine.display(); // Magazine Title: National Geographic
}
}
Output:
Copy
Book Title: Effective Java
Magazine Title: National Geographic

Q36: Write a Java program that defines an


interface Vehicle with methods start() and stop(). Implement
this interface in classes Car and Bike.
Answer:
java
Copy
interface Vehicle {
void start();

Java (OOP) 145


void stop();
}

class Car implements Vehicle {


@Override
public void start() {
System.out.println("Car is starting");
}

@Override
public void stop() {
System.out.println("Car is stopping");
}
}

class Bike implements Vehicle {


@Override
public void start() {
System.out.println("Bike is starting");
}

@Override
public void stop() {
System.out.println("Bike is stopping");
}
}

public class VehicleTest {


public static void main(String[] args) {
Vehicle myCar = new Car();
Vehicle myBike = new Bike();

myCar.start(); // Car is starting


myBike.start(); // Bike is starting
myCar.stop(); // Car is stopping
myBike.stop(); // Bike is stopping
}
}
Output:
Copy
Car is starting
Bike is starting
Car is stopping
Bike is stopping

Q37: Write a program that demonstrates the use of


the final keyword with a class and a method.
Answer:
java
Copy
final class FinalClass {
void display() {
System.out.println("This is a final class.");

Java (OOP) 146


}
}

// Uncommenting the following class will cause a compilation error


// class SubClass extends FinalClass {}

public class FinalTest {


public static void main(String[] args) {
FinalClass obj = new FinalClass();
obj.display(); // This is a final class.
}
}
Output:
Copy
This is a final class.

These additional MCQs and coding questions should further enhance


your understanding of Java concepts related to inheritance,
polymorphism, abstract classes, interfaces, and more.

Q38: Which of the following statements is true about


encapsulation?
A) It allows the creation of classes.
B) It restricts access to the internal state of an object.
C) It provides a mechanism for method overloading.
D) It is the same as inheritance.
Answer: B) It restricts access to the internal state of an object.

Q39: What will be the output of the following code?


java
Copy
class A {
void display() {
System.out.println("Class A");
}
}

class B extends A {
void display() {
System.out.println("Class B");
}
}

class C extends B {
void display() {

Java (OOP) 147


System.out.println("Class C");
}
}

public class Test {


public static void main(String[] args) {
A obj = new C();
obj.display();
}
}
A) Class A
B) Class B
C) Class C
D) Compilation error
Answer: C) Class C

Q40: Which of the following correctly describes the "has-a"


relationship?
A) Inheritance
B) Composition
C) Abstraction
D) Encapsulation
Answer: B) Composition

Q41: What is the purpose of the interface keyword in Java?


A) To create a new class
B) To define a contract for classes to implement
C) To implement multiple inheritance
D) To create abstract classes
Answer: B) To define a contract for classes to implement

Q42: What will happen if a subclass does not implement all


abstract methods from its superclass?
A) The program will compile successfully.
B) The subclass will be abstract.
C) The subclass will throw an exception at runtime.
D) The program will not compile.
Answer: B) The subclass will be abstract.

Q43: Which of the following allows a class to inherit from


multiple sources?
A) Interfaces
B) Abstract classes

Java (OOP) 148


C) Single inheritance
D) Aggregation
Answer: A) Interfaces

Q44: What will be the outcome of the following code?


java
Copy
class Base {
final void show() {
System.out.println("Base show");
}
}

class Derived extends Base {


void show() { // Compilation error
System.out.println("Derived show");
}
}

public class Test {


public static void main(String[] args) {
Derived obj = new Derived();
obj.show();
}
}
A) Compilation error
B) Base show
C) Derived show
D) Runtime error
Answer: A) Compilation error

Q45: Which of the following is a valid way to create an


object of an abstract class?
A) AbstractClass obj = new AbstractClass();
B) AbstractClass obj = new SubClass();
C) AbstractClass obj = new AbstractClass();
D) AbstractClass obj;
Answer: B) AbstractClass obj = new SubClass();

Additional Java Coding Questions

Q46: Write a Java program demonstrating encapsulation.


Answer:
java
Copy
class BankAccount {
private double balance;

Java (OOP) 149


public void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}

public void withdraw(double amount) {


if (amount > 0 && amount <= balance) {
balance -= amount;
}
}

public double getBalance() {


return balance;
}
}

public class BankTest {


public static void main(String[] args) {
BankAccount account = new BankAccount();
account.deposit(1000);
account.withdraw(500);
System.out.println("Balance: " + account.getBalance()); // Balance:
500.0
}
}
Output:
Copy
Balance: 500.0

Q47: Create a program that implements multiple interfaces


for a class Bird that can Fly and Sing.
Answer:
java
Copy
interface Fly {
void fly();
}

interface Sing {
void sing();
}

class Bird implements Fly, Sing {


@Override
public void fly() {
System.out.println("Bird is flying");
}

@Override
public void sing() {
System.out.println("Bird is singing");

Java (OOP) 150


}
}

public class BirdTest {


public static void main(String[] args) {
Bird bird = new Bird();
bird.fly(); // Bird is flying
bird.sing(); // Bird is singing
}
}
Output:
Copy
Bird is flying
Bird is singing

Q48: Write a Java program that shows how to use method


overriding with a class hierarchy of Animal, Dog, and Cat.
Answer:
java
Copy
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}

class Dog extends Animal {


@Override
void sound() {
System.out.println("Dog barks");
}
}

class Cat extends Animal {


@Override
void sound() {
System.out.println("Cat meows");
}
}

public class AnimalTest {


public static void main(String[] args) {
Animal myDog = new Dog();
Animal myCat = new Cat();

myDog.sound(); // Dog barks


myCat.sound(); // Cat meows
}
}
Output:
Copy
Dog barks

Java (OOP) 151


Cat meows

Q49: Implement a class called Shape with an abstract


method draw(). Create subclasses Circle and Square that provide
implementation for the draw() method.
Answer:
java
Copy
abstract class Shape {
abstract void draw();
}

class Circle extends Shape {


@Override
void draw() {
System.out.println("Drawing a circle");
}
}

class Square extends Shape {


@Override
void draw() {
System.out.println("Drawing a square");
}
}

public class ShapeTest {


public static void main(String[] args) {
Shape circle = new Circle();
Shape square = new Square();

circle.draw(); // Drawing a circle


square.draw(); // Drawing a square
}
}
Output:
Copy
Drawing a circle
Drawing a square

Q50: Write a Java program that demonstrates the use


of final methods and classes.
Answer:
java
Copy
class FinalClass {
final void display() {
System.out.println("Final method in final class");
}
}

Java (OOP) 152


// Cannot extend FinalClass
// class SubClass extends FinalClass {}

public class FinalTest {


public static void main(String[] args) {
FinalClass obj = new FinalClass();
obj.display(); // Final method in final class
}
}
Output:
oxygene
Copy
Final method in final class

This extensive set of questions and code examples covers a broad


range of topics related to Java programming concepts, particularly
focusing on OOP principles.

Q51: What is the result of trying to override a private


method in a subclass?
A) It will compile, and the subclass can access it.
B) It will compile, but the subclass won't have access to the method.
C) It will not compile.
D) It will compile, but it will cause a runtime error.
Answer: B) It will compile, but the subclass won't have access to
the method.

Q52: In Java, which keyword is used to inherit attributes and


methods from another class?
A) implements
B) inherits
C) extends
D) uses
Answer: C) extends

Q53: Which of the following best describes an abstract


method?
A) A method with a body
B) A method that cannot be overridden
C) A method that has no body and must be implemented by

Java (OOP) 153


subclasses
D) A method that can be static
Answer: C) A method that has no body and must be implemented
by subclasses

Q54: What will be the output of the following code?


java
Copy
class X {
void method() {
System.out.println("Method in X");
}
}

class Y extends X {
void method() {
System.out.println("Method in Y");
}
}

class Z extends Y {
void method() {
System.out.println("Method in Z");
}
}

public class Test {


public static void main(String[] args) {
X obj = new Z();
obj.method();
}
}
A) Method in X
B) Method in Y
C) Method in Z
D) Compilation error
Answer: C) Method in Z

Q55: Which of the following statements is true about


method overloading?
A) It occurs when two or more methods in the same class have the
same name and same parameters.
B) It is a way to achieve runtime polymorphism.
C) It can occur in the same class or in subclasses.
D) It allows methods to have different return types only.
Answer: C) It can occur in the same class or in subclasses.

Java (OOP) 154


Q56: What is the output of the following code?
java
Copy
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}

class Dog extends Animal {


void sound() {
System.out.println("Dog barks");
}
}

class Cat extends Animal {


void sound() {
System.out.println("Cat meows");
}
}

public class Test {


public static void main(String[] args) {
Animal myAnimal = new Dog();
myAnimal.sound();
myAnimal = new Cat();
myAnimal.sound();
}
}
A) Animal makes a sound
B) Dog barks
C) Cat meows
D) Dog barks, Cat meows
Answer: D) Dog barks, Cat meows

Q57: Which of the following is NOT a feature of interfaces in


Java?
A) They can contain default methods.
B) They can contain instance variables.
C) They can extend multiple interfaces.
D) They can be implemented by multiple classes.
Answer: B) They can contain instance variables.

Additional Java Coding Questions

Q58: Write a Java program to demonstrate the use of


encapsulation with a Person class that has private fields.
Answer:

Java (OOP) 155


java
Copy
class Person {
private String name;
private int age;

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public int getAge() {


return age;
}

public void setAge(int age) {


if (age > 0) {
this.age = age;
}
}
}

public class PersonTest {


public static void main(String[] args) {
Person person = new Person();
person.setName("John");
person.setAge(30);
System.out.println("Name: " + person.getName() + ", Age: " +
person.getAge());
}
}
Output:
Copy
Name: John, Age: 30

Q59: Create a program that demonstrates the use of an


abstract class Shape with concrete
subclasses Triangle and Rectangle.
Answer:
java
Copy
abstract class Shape {
abstract void draw();
}

class Triangle extends Shape {


@Override
void draw() {

Java (OOP) 156


System.out.println("Drawing a triangle");
}
}

class Rectangle extends Shape {


@Override
void draw() {
System.out.println("Drawing a rectangle");
}
}

public class ShapeTest {


public static void main(String[] args) {
Shape triangle = new Triangle();
Shape rectangle = new Rectangle();

triangle.draw(); // Drawing a triangle


rectangle.draw(); // Drawing a rectangle
}
}
Output:
Copy
Drawing a triangle
Drawing a rectangle

Q60: Write a Java program that implements an


interface Calculator with methods add() and subtract(). Create a
class BasicCalculator that implements this interface.
Answer:
java
Copy
interface Calculator {
int add(int a, int b);
int subtract(int a, int b);
}

class BasicCalculator implements Calculator {


@Override
public int add(int a, int b) {
return a + b;
}

@Override
public int subtract(int a, int b) {
return a - b;
}
}

public class CalculatorTest {


public static void main(String[] args) {
BasicCalculator calc = new BasicCalculator();
System.out.println("Addition: " + calc.add(10, 5)); // Addition: 15

Java (OOP) 157


System.out.println("Subtraction: " + calc.subtract(10, 5)); //
Subtraction: 5
}
}
Output:
Copy
Addition: 15
Subtraction: 5

Q61: Implement a class hierarchy where Employee is the


superclass and FullTimeEmployee and PartTimeEmployee are
subclasses. Include a method to calculate the salary.
Answer:
java
Copy
class Employee {
String name;

Employee(String name) {
this.name = name;
}

double calculateSalary() {
return 0;
}
}

class FullTimeEmployee extends Employee {


double monthlySalary;

FullTimeEmployee(String name, double monthlySalary) {


super(name);
this.monthlySalary = monthlySalary;
}

@Override
double calculateSalary() {
return monthlySalary;
}
}

class PartTimeEmployee extends Employee {


double hourlyRate;
int hoursWorked;

PartTimeEmployee(String name, double hourlyRate, int hoursWorked) {


super(name);
this.hourlyRate = hourlyRate;
this.hoursWorked = hoursWorked;
}

@Override

Java (OOP) 158


double calculateSalary() {
return hourlyRate * hoursWorked;
}
}

public class EmployeeTest {


public static void main(String[] args) {
Employee emp1 = new FullTimeEmployee("Alice", 3000);
Employee emp2 = new PartTimeEmployee("Bob", 20, 80);

System.out.println(emp1.name + "'s Salary: " +


emp1.calculateSalary()); // Alice's Salary: 3000.0
System.out.println(emp2.name + "'s Salary: " +
emp2.calculateSalary()); // Bob's Salary: 1600.0
}
}
Output:
pgsql
Copy
Alice's Salary: 3000.0
Bob's Salary: 1600.0

Q62: Write a program that demonstrates method


overloading by creating a class Display with overloaded
methods show().
Answer:
java
Copy
class Display {
void show(int a) {
System.out.println("Integer: " + a);
}

void show(String b) {
System.out.println("String: " + b);
}

void show(double c) {
System.out.println("Double: " + c);
}
}

public class DisplayTest {


public static void main(String[] args) {
Display display = new Display();
display.show(10); // Integer: 10
display.show("Hello"); // String: Hello
display.show(15.5); // Double: 15.5
}
}
Output:

Java (OOP) 159


Copy
Integer: 10
String: Hello
Double: 15.5

These additional questions and coding examples further reinforce


your understanding of Java concepts, including OOP principles,
inheritance, polymorphism, abstract classes, interfaces,
encapsulation, and method overloading.

Q63: What happens when a subclass overrides a method


from its superclass?
A) The superclass method is hidden.
B) The superclass method can still be called using the super keyword.
C) The subclass method cannot have the same name.
D) The overridden method must be private.
Answer: B) The superclass method can still be called using
the super keyword.

Q64: Which of the following statements about interfaces is


true?
A) An interface can have constructors.
B) An interface can contain instance variables.
C) An interface can have static methods.
D) An interface can be instantiated.
Answer: C) An interface can have static methods. (Since Java 8)

Q65: What will be the output of the following code?


java
Copy
class A {
void display() {
System.out.println("Display A");
}
}

class B extends A {
void display() {
System.out.println("Display B");
}
}

public class Test {


public static void main(String[] args) {

Java (OOP) 160


A obj = new B();
obj.display();
}
}
A) Display A
B) Display B
C) Compilation error
D) Runtime error
Answer: B) Display B

Q66: Which keyword is used to prevent a class from being


subclassed?
A) final
B) static
C) abstract
D) private
Answer: A) final

Q67: Which of the following is a characteristic of method


overriding?
A) Method names must be different.
B) The return type must be the same or covariant.
C) The access modifier must be more restrictive.
D) It can only occur in the same class.
Answer: B) The return type must be the same or covariant.

Q68: What will happen if you try to create an instance of an


abstract class?
A) It will compile but throw an exception at runtime.
B) The program will not compile.
C) The abstract class will be instantiated with default values.
D) The program will compile successfully.
Answer: B) The program will not compile.

Q69: Which of the following correctly illustrates the use of


the super keyword?
A) To call a static method in the superclass.
B) To access a private method in the superclass.
C) To call the constructor of the superclass.
D) To declare a superclass variable.
Answer: C) To call the constructor of the superclass.

Q70: What is the main benefit of using interfaces in Java?


Java (OOP) 161
A) To allow multiple inheritance.
B) To enforce encapsulation.
C) To provide a way to define a contract for classes.
D) To create abstract classes.
Answer: C) To provide a way to define a contract for classes.

More Java Coding Questions

Q71: Write a Java program to demonstrate the use of


abstract classes with an abstract method calculateArea() in a
class Shape.
Answer:
java
Copy
abstract class Shape {
abstract double calculateArea();
}

class Circle extends Shape {


double radius;

Circle(double radius) {
this.radius = radius;
}

@Override
double calculateArea() {
return Math.PI * radius * radius;
}
}

class Rectangle extends Shape {


double length, width;

Rectangle(double length, double width) {


this.length = length;
this.width = width;
}

@Override
double calculateArea() {
return length * width;
}
}

public class ShapeTest {


public static void main(String[] args) {
Shape circle = new Circle(5);
Shape rectangle = new Rectangle(4, 6);

System.out.println("Circle Area: " + circle.calculateArea());

Java (OOP) 162


System.out.println("Rectangle Area: " + rectangle.calculateArea());
}
}
Output:
Copy
Circle Area: 78.53981633974483
Rectangle Area: 24.0

Q72: Create a Java program that demonstrates a


class Student with encapsulated fields for name and grade.
Answer:
java
Copy
class Student {
private String name;
private char grade;

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public char getGrade() {


return grade;
}

public void setGrade(char grade) {


this.grade = grade;
}
}

public class StudentTest {


public static void main(String[] args) {
Student student = new Student();
student.setName("Alice");
student.setGrade('A');

System.out.println("Student Name: " + student.getName() + ", Grade: "


+ student.getGrade());
}
}
Output:
Copy
Student Name: Alice, Grade: A

Q73: Write a program that implements method overloading


in a class called MathOperations that contains methods
for multiply().
Java (OOP) 163
Answer:
java
Copy
class MathOperations {
int multiply(int a, int b) {
return a * b;
}

double multiply(double a, double b) {


return a * b;
}

int multiply(int a, int b, int c) {


return a * b * c;
}
}

public class MathTest {


public static void main(String[] args) {
MathOperations math = new MathOperations();
System.out.println("Multiply 2 ints: " + math.multiply(2, 3)); // 6
System.out.println("Multiply 2 doubles: " + math.multiply(2.5, 3.5));
// 8.75
System.out.println("Multiply 3 ints: " + math.multiply(2, 3, 4)); //
24
}
}
Output:
Copy
Multiply 2 ints: 6
Multiply 2 doubles: 8.75
Multiply 3 ints: 24

Q74: Implement a simple interface Playable with a


method play() and create two classes Game and Movie that
implement this interface.
Answer:
java
Copy
interface Playable {
void play();
}

class Game implements Playable {


@Override
public void play() {
System.out.println("Playing a game");
}
}

class Movie implements Playable {

Java (OOP) 164


@Override
public void play() {
System.out.println("Playing a movie");
}
}

public class PlayableTest {


public static void main(String[] args) {
Playable game = new Game();
Playable movie = new Movie();

game.play(); // Playing a game


movie.play(); // Playing a movie
}
}
Output:
Copy
Playing a game
Playing a movie

Q75: Write a Java program that demonstrates the use of


inheritance with a base class Vehicle and derived
classes Car and Truck.
Answer:
java
Copy
class Vehicle {
void start() {
System.out.println("Vehicle is starting");
}
}

class Car extends Vehicle {


@Override
void start() {
System.out.println("Car is starting");
}
}

class Truck extends Vehicle {


@Override
void start() {
System.out.println("Truck is starting");
}
}

public class VehicleTest {


public static void main(String[] args) {
Vehicle myCar = new Car();
Vehicle myTruck = new Truck();

myCar.start(); // Car is starting

Java (OOP) 165


myTruck.start(); // Truck is starting
}
}
Output:
Copy
Car is starting
Truck is starting

These additional questions and coding examples further enhance


your understanding of Java concepts, particularly focusing on OOP
principles and features.

Q76: What is the output of the following code?


java
Copy
class Base {
void method() {
System.out.println("Base method");
}
}

class Derived extends Base {


void method() {
System.out.println("Derived method");
}
}

public class Test {


public static void main(String[] args) {
Base obj = new Derived();
obj.method();
}
}
A) Base method
B) Derived method
C) Compilation error
D) Runtime error
Answer: B) Derived method

Q77: Which concept allows a subclass to define its own


version of a method that is already defined in its superclass?
A) Encapsulation
B) Inheritance
C) Polymorphism
D) Abstraction

Java (OOP) 166


Answer: C) Polymorphism

Q78: If a class is declared as abstract, which of the following is


true?
A) It cannot have any methods.
B) It cannot be instantiated.
C) It cannot have constructors.
D) It cannot have fields.
Answer: B) It cannot be instantiated.

Q79: What is the purpose of the instanceof operator in Java?


A) To check if an object is of a particular type.
B) To create instances of classes.
C) To define a new class.
D) To implement interfaces.
Answer: A) To check if an object is of a particular type.

Q80: Which of the following statements is true regarding


method overloading?
A) It requires methods to have the same parameters.
B) It allows methods to have different names.
C) It can occur in the same class or subclasses.
D) It can occur only in the same class.
Answer: C) It can occur in the same class or subclasses.

Q81: What is the result of the following code?


java
Copy
class Animal {
void makeSound() {
System.out.println("Animal sound");
}
}

class Dog extends Animal {


void makeSound() {
System.out.println("Bark");
}
}

public class Test {


public static void main(String[] args) {
Animal myDog = new Dog();
myDog.makeSound();
}
}

Java (OOP) 167


A) Animal sound
B) Bark
C) Compilation error
D) Runtime error
Answer: B) Bark

Q82: Which keyword is used to implement an interface in a


class?
A) extends
B) implements
C) inherits
D) uses
Answer: B) implements

Q83: What is the output of the following code snippet?


java
Copy
class Parent {
void show() {
System.out.println("Parent");
}
}

class Child extends Parent {


void show() {
System.out.println("Child");
}

void display() {
System.out.println("Display Child");
}
}

public class Test {


public static void main(String[] args) {
Parent obj = new Child();
obj.show();
// obj.display(); // Uncommenting this will cause a compilation error
}
}
A) Parent
B) Child
C) Display Child
D) Compilation error
Answer: B) Child

Additional Java Coding Questions

Java (OOP) 168


Q84: Write a Java program that demonstrates the use of
interfaces with a Drivable interface and Car and Bike classes.
Answer:
java
Copy
interface Drivable {
void drive();
}

class Car implements Drivable {


@Override
public void drive() {
System.out.println("Car is driving");
}
}

class Bike implements Drivable {


@Override
public void drive() {
System.out.println("Bike is riding");
}
}

public class VehicleTest {


public static void main(String[] args) {
Drivable myCar = new Car();
Drivable myBike = new Bike();

myCar.drive(); // Car is driving


myBike.drive(); // Bike is riding
}
}
Output:
Copy
Car is driving
Bike is riding

Q85: Create a program that uses an abstract


class Appliance with a concrete method turnOn() and an abstract
method use(). Implement it in a class WashingMachine.
Answer:
java
Copy
abstract class Appliance {
void turnOn() {
System.out.println("Appliance is turned on");
}

abstract void use();

Java (OOP) 169


}

class WashingMachine extends Appliance {


@Override
void use() {
System.out.println("Using the washing machine");
}
}

public class ApplianceTest {


public static void main(String[] args) {
Appliance machine = new WashingMachine();
machine.turnOn(); // Appliance is turned on
machine.use(); // Using the washing machine
}
}
Output:
Copy
Appliance is turned on
Using the washing machine

Q86: Write a Java program that demonstrates method


overloading with a class Printer that has overloaded
methods print().
Answer:
java
Copy
class Printer {
void print(int a) {
System.out.println("Printing integer: " + a);
}

void print(String b) {
System.out.println("Printing string: " + b);
}

void print(String b, int a) {


System.out.println("Printing string and integer: " + b + ", " + a);
}
}

public class PrinterTest {


public static void main(String[] args) {
Printer printer = new Printer();
printer.print(100); // Printing integer: 100
printer.print("Hello World"); // Printing string: Hello
World
printer.print("Number", 42); // Printing string and
integer: Number, 42
}
}
Output:
Java (OOP) 170
Copy
Printing integer: 100
Printing string: Hello World
Printing string and integer: Number, 42

Q87: Implement a class hierarchy where Shape is an abstract


class with a method area(), and
subclasses Circle and Square implement this method.
Answer:
java
Copy
abstract class Shape {
abstract double area();
}

class Circle extends Shape {


double radius;

Circle(double radius) {
this.radius = radius;
}

@Override
double area() {
return Math.PI * radius * radius;
}
}

class Square extends Shape {


double side;

Square(double side) {
this.side = side;
}

@Override
double area() {
return side * side;
}
}

public class ShapeTest {


public static void main(String[] args) {
Shape circle = new Circle(5);
Shape square = new Square(4);

System.out.println("Circle Area: " + circle.area()); // Circle Area:


78.53981633974483
System.out.println("Square Area: " + square.area()); // Square Area:
16.0
}
}

Java (OOP) 171


Output:
Copy
Circle Area: 78.53981633974483
Square Area: 16.0

Q88: Write a program that demonstrates inheritance with a


base class Person and derived classes Employee and Manager.
Answer:
java
Copy
class Person {
String name;

Person(String name) {
this.name = name;
}

void display() {
System.out.println("Name: " + name);
}
}

class Employee extends Person {


Employee(String name) {
super(name);
}

void display() {
System.out.println("Employee Name: " + name);
}
}

class Manager extends Employee {


Manager(String name) {
super(name);
}

void display() {
System.out.println("Manager Name: " + name);
}
}

public class PersonTest {


public static void main(String[] args) {
Person emp = new Employee("Alice");
Person mgr = new Manager("Bob");

emp.display(); // Employee Name: Alice


mgr.display(); // Manager Name: Bob
}
}
Output:

Java (OOP) 172


Copy
Employee Name: Alice
Manager Name: Bob

These additional questions and coding examples further explore


Java programming concepts, emphasizing OOP principles such as
inheritance, polymorphism, abstraction, encapsulation, and method
overloading.

Java (OOP) 173

You might also like