Chapter 2 4 Java
Chapter 2 4 Java
Java (OOP) 1
Copy
import java.util.ArrayList;
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!
// 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.
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.
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
}
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.
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
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
Java (OOP) 11
Symb Examp
Operator Description
ol le
than right
3. Logical Operators
These operators are used to combine boolean expressions.
Operat Symb Examp
Description
or ol le
OR ` `
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
Performs OR
Bitwise OR ` `
operation
5. Assignment Operators
These operators are used to assign values to variables.
Symb Examp
Operator Description
ol le
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
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
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;
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;
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.
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.
// if statement
if (score >= 60) {
Java (OOP) 22
System.out.println("You passed the exam.");
} else {
System.out.println("You failed the exam.");
}
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
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
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.
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
}
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}
};
Java (OOP) 30
public static void main(String[] args) {
String[] fruits = {"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;
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.
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
// 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));
}
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;
4. Using Arrays.fill()
Description: The Arrays.fill() method can fill an array with a
specific value.
Illustration:
java
Copy
import java.util.Arrays;
Java (OOP) 34
int[] numbers = new int[5];
Java (OOP) 35
printArray(numbers); // Passing the array to the method
}
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.
Java (OOP) 36
// Initialization at declaration
int[] moreNumbers = {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
Java (OOP) 37
public class ArrayIteration {
public static void main(String[] args) {
String[] fruits = {"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}
};
Java (OOP) 38
}
}
Output:
basic
Copy
2D Array Elements:
1 2 3
4 5 6
7 8 9
Java (OOP) 39
Copy
Sorted Array: [1, 2, 3, 4, 5]
Filling Arrays:
java
Copy
import java.util.Arrays;
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.
Example Code
1. Basic String Operations
Illustration:
java
Copy
public class BasicStringOperations {
public static void main(String[] args) {
String greeting = "Hello, World!";
// 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
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
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.
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;
}
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;
}
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");
}
}
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;
}
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;
}
}
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");
}
}
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.
// Constructor
public Book(String title, String author, double price) {
this.title = title;
this.author = author;
this.price = price;
}
Java (OOP) 51
void draw() {
System.out.println("Drawing a shape");
}
}
Java (OOP) 52
System.out.println("Printing decimal: " + decimal);
}
}
Java (OOP) 53
}
void sleep() {
System.out.println("The animal is sleeping");
}
}
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
}
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!");
}
}
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.
Java (OOP) 57
public double getBalance() {
return balance; // Getter
}
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.
class Student {
String name;
Student(String name) {
this.name = name;
}
class Course {
Java (OOP) 59
String title;
List<Student> students = new ArrayList<>();
Course(String title) {
this.title = title;
}
void showStudents() {
System.out.println("Students in " + title + ":");
for (Student student : students) {
System.out.println(student.name);
}
}
}
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 showBooks() {
System.out.println("Books in the library:");
for (Book book : books) {
System.out.println(book.title);
}
}
}
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);
}
}
}
Summary of Relationships
Relationship
Definition Example
Type
Student(String name) {
this.name = name;
}
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 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
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
// 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
}
}
// 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
}
}
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
}
}
// 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.");
}
}
// Usage
public class Main {
public static void main(String[] args) {
Soccer soccer = new Soccer();
soccer.start(); // From Game
soccer.play(); // From Playable
}
}
Java (OOP) 71
// Define an interface
interface Animal {
void sound();
}
// Usage
public class Main {
public static void main(String[] args) {
Animal myDog = new Dog();
Animal myCat = new Cat();
Java (OOP) 72
private double height;
@Override
public double area() {
return width * height;
}
}
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) };
Java (OOP) 73
// Define the first interface
interface Playable {
void play();
}
@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.
}
}
Java (OOP) 74
}
// 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.
}
}
Java (OOP) 75
// Method that uses the interface
public class Main {
public static void displayGreeting(Greeting greeting, String name)
{
greeting.greet(name);
}
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...");
}
}
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!
}
}
Java (OOP) 77
void roll() {
System.out.println("Wheel is rolling.");
}
}
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();
}
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());
Configuration(String setting) {
this.setting = setting;
}
String getSetting() {
return setting;
}
}
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
}
}
Document(Printer printer) {
this.printer = printer; // Dependency injection
}
// 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!
}
}
Java (OOP) 81
System.out.println("Playing music...");
}
}
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;
}
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.
// Usage
public class Main {
public static void main(String[] args) {
int sum = MathUtils.add(5, 10);
System.out.println("Sum: " + sum); // Output: Sum: 15
}
}
// 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
}
}
// 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
}
}
Java (OOP) 85
// Usage
public class Main {
public static void main(String[] args) {
Config.displayConfig(); // Output: Application Configuration
Loaded
}
}
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!
}
}
Java (OOP) 86
}
// Usage
public class Main {
public static void main(String[] args) {
Display.show(100); // Output: Integer: 100
Display.show("Hello!"); // Output: Message: Hello!
}
}
// 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.
src/
└── com/
└── example/
└── utils/
└── MathUtils.java
// File: src/com/example/utils/MathUtils.java
package com.example.utils;
// File: src/Main.java
import com.example.utils.MathUtils;
Java (OOP) 88
public class Main {
└── com/
└── example/
└── shapes/
├── Circle.java
└── Rectangle.java
Circle Class
// File: src/com/example/shapes/Circle.java
package com.example.shapes;
Java (OOP) 89
public Circle(double radius) {
this.radius = radius;
Rectangle Class
// File: src/com/example/shapes/Rectangle.java
package com.example.shapes;
this.width = width;
this.height = height;
Java (OOP) 90
public double area() {
// File: src/Main.java
import com.example.shapes.Circle;
import com.example.shapes.Rectangle;
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;
System.out.println("Dog barks!");
Cat Class
// File: src/com/example/animals/Cat.java
package com.example.animals;
Java (OOP) 92
System.out.println("Cat meows!");
// File: src/Main.java
import com.example.animals.Dog;
import com.example.animals.Cat;
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;
dog.bark();
cat.meow();
Java (OOP) 94
// File: src/Main.java
import com.example.services.AnimalService;
animalService.makeSound();
// Output:
// Dog barks!
// Cat meows!
// File: src/com/example/animals/Cat.java
package com.example.animals;
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;
cat.meow();
System.out.println("Dog barks!");
// File: src/Main.java
import com.example.animals.Dog;
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.
import java.util.ArrayList;
import java.util.Collections;
import java.util.Arrays;
import java.util.List;
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();
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
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.
// Abstract class
abstract class Animal {
// Abstract method (does not have a body)
abstract void sound();
// Concrete method
void sleep() {
System.out.println("Sleeping...");
}
}
// Usage
public class Main {
public static void main(String[] args) {
Animal myDog = new Dog();
myDog.sound(); // Output: Dog barks!
myDog.sleep(); // Output: Sleeping...
}
}
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;
}
}
@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.
}
}
// Abstract class
Circle(double radius) {
this.radius = radius;
}
@Override
double area() {
return Math.PI * radius * radius;
}
}
@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);
// 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);
}
}
@Override
double calculateSalary() {
return monthlySalary * 12; // Annual salary
}
}
@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
}
}
// Abstract class
abstract class Animal {
abstract void sound(); // Abstract method
// Final method
// 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.
}
}
@Override
public double area() {
return Math.PI * radius * radius;
}
}
@Override
public double area() {
return width * height;
}
}
class Parent {
void display() {
System.out.println("Parent");
void display() {
System.out.println("Child");
obj.display();
A) Parent
B) Child
C) Compilation Error
D) Runtime Error
Answer: B) Child
class Test {
void display(int a) {
void display(double b) {
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
interface Animal {
void sound();
System.out.println("Dog barks!");
myDog.sound();
A) Dog barks!
B) Compilation Error
C) Runtime Error
D) No output
Answer: A) Dog barks!
class Base {
void show() {
System.out.println("Base class");
void show() {
System.out.println("Derived class");
obj.show();
A) Base class
B) Derived class
C) Compilation Error
D) Runtime Error
Java (OOP) 110
Answer: B) Derived class
class Engine {
class Car {
Car(Engine engine) {
this.engine = engine;
A) Aggregation
B) Composition
C) Inheritance
D) Polymorphism
Answer: B) Composition
interface Shape {
void draw();
System.out.println("Drawing Circle");
System.out.println("Drawing 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
class Animal {
void eat() {
System.out.println("Animal eats");
void bark() {
System.out.println("Dog barks");
obj.eat();
A) Animal eats
B) Dog barks
C) Compilation Error
D) Runtime Error
Answer: A) Animal eats
void displayInfo() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
// Derived class
class Student extends Person {
String studentID;
void displayInfo() {
super.displayInfo(); // Call the parent method
System.out.println("Student ID: " + studentID);
}
}
// Derived class
class Teacher extends Person {
String subject;
void displayInfo() {
super.displayInfo();
System.out.println("Subject: " + subject);
}
}
// 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.");
}
}
Employee(String name) {
this.name = name;
}
// 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 {
@Override
void work() {
System.out.println(name + " is managing the school.");
}
}
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");
}
// Derived class
class ScienceCourse extends Course {
ScienceCourse() {
super("Science");
}
@Override
void displayCourseInfo() {
System.out.println("This is a Science course.");
}
}
void displayInfo() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
// Derived classes
class Student extends Person {
String studentID;
void displayInfo() {
super.displayInfo(); // Calls the parent method
System.out.println("Student ID: " + studentID);
}
}
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.");
}
}
Employee(String name) {
this.name = name;
}
interface Teach {
void teach(); // Method declaration
}
@Override
void work() {
System.out.println(name + " is preparing lessons.");
}
@Override
public void teach() {
System.out.println(name + " is teaching.");
}
}
@Override
void work() {
System.out.println(name + " is managing the school.");
}
}
Course(String courseName) {
this.courseName = courseName;
}
void displayCourseInfo() {
System.out.println("Course: " + courseName);
}
}
@Override
void displayCourseInfo() {
System.out.println("This is a Math course.");
}
}
@Override
void displayCourseInfo() {
System.out.println("This is a Science course.");
}
}
Q&A Examples
Person(String name) {
this.name = name;
}
}
Employee(String name) {
this.name = name;
}
@Override
void work() {
System.out.println(name + " is teaching.");
}
}
interface Manage {
void manage();
}
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.
Circle(double radius) {
this.radius = radius;
}
@Override
public double area() {
return Math.PI * radius * radius;
}
}
@Override
public double area() {
return length * width;
}
}
FullTimeEmployee(double salary) {
this.salary = salary;
}
@Override
double calculateSalary() {
return salary;
}
}
@Override
double calculateSalary() {
return hourlyRate * hoursWorked;
}
}
void display() {
System.out.println("Display method in Child");
}
}
void display() {
System.out.println("Derived display");
}
}
interface Swim {
void swim();
}
@Override
public void swim() {
System.out.println("Frog is swimming");
}
}
Publication(String title) {
void display() {
System.out.println("Title: " + title);
}
}
@Override
void display() {
System.out.println("Book Title: " + title);
}
}
@Override
void display() {
System.out.println("Magazine Title: " + title);
}
}
@Override
public void stop() {
System.out.println("Car is stopping");
}
}
@Override
public void stop() {
System.out.println("Bike is stopping");
}
}
class B extends A {
void display() {
System.out.println("Class B");
}
}
class C extends B {
void display() {
interface Sing {
void sing();
}
@Override
public void sing() {
System.out.println("Bird is singing");
class Y extends X {
void method() {
System.out.println("Method in Y");
}
}
class Z extends Y {
void method() {
System.out.println("Method in Z");
}
}
@Override
public int subtract(int a, int b) {
return a - b;
}
}
Employee(String name) {
this.name = name;
}
double calculateSalary() {
return 0;
}
}
@Override
double calculateSalary() {
return monthlySalary;
}
}
@Override
void show(String b) {
System.out.println("String: " + b);
}
void show(double c) {
System.out.println("Double: " + c);
}
}
class B extends A {
void display() {
System.out.println("Display B");
}
}
Circle(double radius) {
this.radius = radius;
}
@Override
double calculateArea() {
return Math.PI * radius * radius;
}
}
@Override
double calculateArea() {
return length * width;
}
}
void display() {
System.out.println("Display Child");
}
}
void print(String b) {
System.out.println("Printing string: " + b);
}
Circle(double radius) {
this.radius = radius;
}
@Override
double area() {
return Math.PI * radius * radius;
}
}
Square(double side) {
this.side = side;
}
@Override
double area() {
return side * side;
}
}
Person(String name) {
this.name = name;
}
void display() {
System.out.println("Name: " + name);
}
}
void display() {
System.out.println("Employee Name: " + name);
}
}
void display() {
System.out.println("Manager Name: " + name);
}
}