From bac5daf6c354152b5db1fd63fdb893d48d737e1d Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Tue, 21 Mar 2023 22:32:46 +0530
Subject: [PATCH 001/178] update
---
README.md | 38 ++++++++++++++++++++++++++++++++++++++
1 file changed, 38 insertions(+)
diff --git a/README.md b/README.md
index 9ac941c4..5ee72a5b 100644
--- a/README.md
+++ b/README.md
@@ -123,6 +123,44 @@ In this step, we:
* Stated our first programming challenge, *PMT-Challenge*
* Identified basic Java concepts to learn, to solve this challenge
+Quiz:
+
+Question 1: What is the aim of the PMT-Challenge?
+a) To solve a mathematical equation
+b) To read out a multiplication table
+c) To learn basic Java concepts
+
+Answer: b) To read out a multiplication table
+
+Question 2: What are some basic Java concepts that will be introduced in the PMT-Challenge?
+a) Numbers and alphabets
+b) Loops and conditionals
+c) Colors and shapes
+
+Answer: b) Loops and conditionals
+
+Question 3: Which of the following is NOT a basic Java concept introduced in the PMT-Challenge?
+a) Variables
+b) Methods
+c) Booleans
+Answer: c) Booleans
+
+Hands-on Exercise:
+
+Write a Java program to compute the multiplication table for 7, with entries from 1 to 12. Display this table in the following format:
+7 * 1 = 7
+7 * 2 = 14
+7 * 3 = 21
+7 * 4 = 28
+7 * 5 = 35
+7 * 6 = 42
+7 * 7 = 49
+7 * 8 = 56
+7 * 9 = 63
+7 * 10 = 70
+7 * 11 = 77
+7 * 12 = 84
+
### Step 02: Introducing ```JShell```
- - -
From 4638517b25f94ebf2b016a7214d43275be0583fc Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Tue, 21 Mar 2023 22:33:40 +0530
Subject: [PATCH 002/178] update
---
README.md | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/README.md b/README.md
index 5ee72a5b..980c7fdc 100644
--- a/README.md
+++ b/README.md
@@ -123,7 +123,7 @@ In this step, we:
* Stated our first programming challenge, *PMT-Challenge*
* Identified basic Java concepts to learn, to solve this challenge
-Quiz:
+#### Quiz:
Question 1: What is the aim of the PMT-Challenge?
a) To solve a mathematical equation
@@ -145,7 +145,7 @@ b) Methods
c) Booleans
Answer: c) Booleans
-Hands-on Exercise:
+#### Hands-on Exercise:
Write a Java program to compute the multiplication table for 7, with entries from 1 to 12. Display this table in the following format:
7 * 1 = 7
From 9648ec1c6441e7b2c9a9864f2e30e1cfb01a28e9 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Tue, 21 Mar 2023 22:34:19 +0530
Subject: [PATCH 003/178] update
---
README.md | 2 ++
1 file changed, 2 insertions(+)
diff --git a/README.md b/README.md
index 980c7fdc..37bf5b2f 100644
--- a/README.md
+++ b/README.md
@@ -148,6 +148,7 @@ Answer: c) Booleans
#### Hands-on Exercise:
Write a Java program to compute the multiplication table for 7, with entries from 1 to 12. Display this table in the following format:
+```
7 * 1 = 7
7 * 2 = 14
7 * 3 = 21
@@ -160,6 +161,7 @@ Write a Java program to compute the multiplication table for 7, with entries fro
7 * 10 = 70
7 * 11 = 77
7 * 12 = 84
+```
### Step 02: Introducing ```JShell```
- - -
From 6f26323062e45da0f6997ebede88371ed40fd607 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Tue, 21 Mar 2023 22:36:39 +0530
Subject: [PATCH 004/178] update
---
README.md | 29 +++++++++++++++++++++++++++++
1 file changed, 29 insertions(+)
diff --git a/README.md b/README.md
index 37bf5b2f..5fbd4859 100644
--- a/README.md
+++ b/README.md
@@ -291,6 +291,35 @@ In this step, we learned:
* How to launch ```JShell``` from our terminal, and run a few commands on it
* How to run Java code on the ```JShell``` prompt
+#### Here are the three multiple choice questions based on the given steps:
+
+What is JShell?
+A. A programming tool
+B. A game
+C. A text editor
+Answer: A
+
+What does REPL stand for?
+A. Read, Evaluate, Print, Loop
+B. Run, Edit, Print, Launch
+C. Record, Edit, Play, Loop
+Answer: A
+
+How do you exit JShell?
+A. /terminate
+B. /exit
+C. /quit
+Answer: B
+
+#### Here's a hands-on exercise:
+
+Exercise: Launch JShell and Evaluate an Expression
+
+Launch JShell on your terminal.
+Type 2+3 at the JShell prompt and press enter.
+Observe the output.
+Type /exit to exit JShell.
+
### Step 03: Welcome to Problem Solving
Lets try to break down the *PMT-Challenge* problem to be able to solve it.
From 26f7ea2c054361a0d305b895a849848df59c12d7 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Tue, 21 Mar 2023 22:37:44 +0530
Subject: [PATCH 005/178] update
---
README.md | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/README.md b/README.md
index 5fbd4859..50ef595e 100644
--- a/README.md
+++ b/README.md
@@ -291,7 +291,7 @@ In this step, we learned:
* How to launch ```JShell``` from our terminal, and run a few commands on it
* How to run Java code on the ```JShell``` prompt
-#### Here are the three multiple choice questions based on the given steps:
+#### Quiz:
What is JShell?
A. A programming tool
@@ -311,7 +311,7 @@ B. /exit
C. /quit
Answer: B
-#### Here's a hands-on exercise:
+#### Hands-on exercise:
Exercise: Launch JShell and Evaluate an Expression
From 62de71fcd4a64053d24a08aae0935eeaa2343e39 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Tue, 21 Mar 2023 22:41:15 +0530
Subject: [PATCH 006/178] update
---
README.md | 34 ++++++++++++++++++++++++++++++++++
1 file changed, 34 insertions(+)
diff --git a/README.md b/README.md
index 50ef595e..ffbc4e95 100644
--- a/README.md
+++ b/README.md
@@ -320,6 +320,40 @@ Type 2+3 at the JShell prompt and press enter.
Observe the output.
Type /exit to exit JShell.
+
+## Response 2
+
+Multiple Choice Quiz
+Step 02: Introducing JShell
+JShell is a programming tool, introduced in Java SE 9. JShell is a REPL interface. The term REPL refers to this:
+
+'R' stands for Read; Read the input Java code
+'E' means Eval; Evaluate the source code
+'P' translates to Print; Print out the result
+'L' indicates Loop; Loop around, and wait for the next input
+Quiz Questions:
+
+What does REPL stand for?
+A) Read, Edit, Print, Loop
+B) Read, Eval, Print, Loop (Correct)
+C) Run, Evaluate, Print, Loop
+How do you launch JShell?
+A) jshell command (Correct)
+B) java -version command
+C) /help intro command
+What does JShell allow you to do?
+A) Execute Python code
+B) Execute JavaScript code
+C) Execute Java code and get immediate results (Correct)
+Hands-on Exercise:
+
+Write a JShell command to assign the value 10 to a variable named x, and then print the value of x to the console.
+
+java
+Copy code
+jshell> int x = 10;
+jshell> System.out.println(x);
+
### Step 03: Welcome to Problem Solving
Lets try to break down the *PMT-Challenge* problem to be able to solve it.
From 2516d306baadaab0941aae72af2316e98318fec3 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Tue, 21 Mar 2023 22:42:18 +0530
Subject: [PATCH 007/178] update
---
README.md | 66 ++++++++++++++++++++++++++++++-------------------------
1 file changed, 36 insertions(+), 30 deletions(-)
diff --git a/README.md b/README.md
index ffbc4e95..5a407dd2 100644
--- a/README.md
+++ b/README.md
@@ -323,36 +323,42 @@ Type /exit to exit JShell.
## Response 2
-Multiple Choice Quiz
-Step 02: Introducing JShell
-JShell is a programming tool, introduced in Java SE 9. JShell is a REPL interface. The term REPL refers to this:
-
-'R' stands for Read; Read the input Java code
-'E' means Eval; Evaluate the source code
-'P' translates to Print; Print out the result
-'L' indicates Loop; Loop around, and wait for the next input
-Quiz Questions:
-
-What does REPL stand for?
-A) Read, Edit, Print, Loop
-B) Read, Eval, Print, Loop (Correct)
-C) Run, Evaluate, Print, Loop
-How do you launch JShell?
-A) jshell command (Correct)
-B) java -version command
-C) /help intro command
-What does JShell allow you to do?
-A) Execute Python code
-B) Execute JavaScript code
-C) Execute Java code and get immediate results (Correct)
-Hands-on Exercise:
-
-Write a JShell command to assign the value 10 to a variable named x, and then print the value of x to the console.
-
-java
-Copy code
-jshell> int x = 10;
-jshell> System.out.println(x);
+
+
+
+ Codebeautify.org Text to HTML Converter
+
+
+ Here are the three multiple choice questions based on the given steps:
+
+What is JShell?
+A. A programming tool
+B. A game
+C. A text editor
+Answer: A
+
+What does REPL stand for?
+A. Read, Evaluate, Print, Loop
+B. Run, Edit, Print, Launch
+C. Record, Edit, Play, Loop
+Answer: A
+
+How do you exit JShell?
+A. /terminate
+B. /exit
+C. /quit
+Answer: B
+
+Here's a hands-on exercise:
+
+Exercise: Launch JShell and Evaluate an Expression
+
+Launch JShell on your terminal.
+Type 2+3 at the JShell prompt and press enter.
+Observe the output.
+Type /exit to exit JShell.
+
+
### Step 03: Welcome to Problem Solving
From 1dda794c7e8143be2c21fc9b40cc9899019db3db Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Tue, 21 Mar 2023 22:45:41 +0530
Subject: [PATCH 008/178] update
---
README.md | 83 +++++++++++++++++++++++++++++--------------------------
1 file changed, 44 insertions(+), 39 deletions(-)
diff --git a/README.md b/README.md
index 5a407dd2..96c27f83 100644
--- a/README.md
+++ b/README.md
@@ -321,45 +321,6 @@ Observe the output.
Type /exit to exit JShell.
-## Response 2
-
-
-
-
- Codebeautify.org Text to HTML Converter
-
-
- Here are the three multiple choice questions based on the given steps:
-
-What is JShell?
-A. A programming tool
-B. A game
-C. A text editor
-Answer: A
-
-What does REPL stand for?
-A. Read, Evaluate, Print, Loop
-B. Run, Edit, Print, Launch
-C. Record, Edit, Play, Loop
-Answer: A
-
-How do you exit JShell?
-A. /terminate
-B. /exit
-C. /quit
-Answer: B
-
-Here's a hands-on exercise:
-
-Exercise: Launch JShell and Evaluate an Expression
-
-Launch JShell on your terminal.
-Type 2+3 at the JShell prompt and press enter.
-Observe the output.
-Type /exit to exit JShell.
-
-
-
### Step 03: Welcome to Problem Solving
Lets try to break down the *PMT-Challenge* problem to be able to solve it.
@@ -389,6 +350,50 @@ In this step, we:
* Broke down the *PMT-Challenge* problem into sub-problems
+#### Quiz:
+
+Question 1: What is the aim of breaking down a problem into sub-problems?
+a) To make the problem more complicated
+b) To make the problem easier to solve
+c) To avoid solving the problem altogether
+
+Answer: b) To make the problem easier to solve
+
+Question 2: How many times do we need to perform the calculation in the PMT-Challenge?
+a) Five times
+b) Ten times
+c) Fifteen times
+
+Answer: b) Ten times
+
+Question 3: What is the first step to solve the PMT-Challenge according to the draft steps?
+a) Print 5 * 3 = 15
+b) Calculate 5 * 3 and print result as 15
+c) Do this ten times
+
+Answer: b) Calculate 5 * 3 and print result as 15
+
+#### Hands-on Exercise:
+
+Write a Java program to compute the multiplication table for 9, with entries from 1 to 15. Use the draft steps mentioned above to solve the problem. Display this table in the following format:
+```
+9 * 1 = 9
+9 * 2 = 18
+9 * 3 = 27
+9 * 4 = 36
+9 * 5 = 45
+9 * 6 = 54
+9 * 7 = 63
+9 * 8 = 72
+9 * 9 = 81
+9 * 10 = 90
+9 * 11 = 99
+9 * 12 = 108
+9 * 13 = 117
+9 * 14 = 126
+9 * 15 = 135
+```
+
### Step 04: Introducing Expressions
The first part of solving our *PMT-Challenge* is to calculate the product of ```5``` and another number, say ```3```.
From a1593b92e61ce7b66dcd8a0b6fb44b4da347c05d Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Tue, 21 Mar 2023 22:50:40 +0530
Subject: [PATCH 009/178] update
---
README.md | 61 +++++++++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 61 insertions(+)
diff --git a/README.md b/README.md
index 96c27f83..3c81049e 100644
--- a/README.md
+++ b/README.md
@@ -510,6 +510,31 @@ In this step, we:
* Learned how to construct numeric expressions
* Discovered that operators are predefined symbols
* Combined several operators to form larger expressions
+
+
+#### Quiz:
+
+What is an expression in Java programming?
+a) A set of instructions to be executed
+b) A combination of operands and operators that results in a value
+c) A way to define a variable
+Answer: b
+
+Which symbol is used for multiplication in Java programming?
+a) X
+b) *
+c) /
+Answer: b
+
+What does the modulo operator do in Java programming?
+a) Adds two numbers
+b) Subtracts two numbers
+c) Gives the remainder when integer division is performed
+Answer: c
+
+#### Hands-on exercise:
+
+Create a Java program that calculates the product of two numbers and displays the result. Use the multiplication operator (*) to perform the calculation.
### Step 05: Programming Exercise PE-1 (With Solutions)
@@ -540,6 +565,42 @@ $jshell>60 * 60 * 24
$1 ==> 86400
```
+#### Quiz:
+
+Question 1: What is the purpose of Step 05 in this book?
+a) To learn basic math concepts
+b) To practice evaluating Java expressions
+c) To explore advanced Java programming concepts
+
+Answer: b) To practice evaluating Java expressions
+
+Question 2: What is the expression to calculate the number of minutes in a day?
+a) 60 * 24
+b) 60 + 24
+c) 24 * 60 * 60
+
+Answer: a) 60 * 24
+
+Question 3: What is the expression to calculate the number of seconds in a day?
+a) 60 * 60
+b) 60 * 60 * 24
+c) 24 / 60 / 60
+
+Answer: b) 60 * 60 * 24
+
+#### Hands-on Exercise:
+
+Write a Java expression to calculate the number of milliseconds in a day.
+Display the result using System.out.println() method.
+
+Solution:
+1000 (milliseconds in a second) multiplied by 60 (seconds in a minute) multiplied by 60 (minutes in an hour) multiplied by 24 (hours in a day)
+
+```
+long millisecondsInADay = 1000L * 60 * 60 * 24;
+System.out.println("Number of milliseconds in a day: " + millisecondsInADay);
+```
+
### Step 06: Operators
Lets look at a few more examples to understand operators.
From 151c0e0d31dd3479d958158f88884d1654bb8fe0 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Tue, 21 Mar 2023 22:53:46 +0530
Subject: [PATCH 010/178] update
---
README.md | 31 +++++++++++++++++++++++++++++++
1 file changed, 31 insertions(+)
diff --git a/README.md b/README.md
index 3c81049e..c635b500 100644
--- a/README.md
+++ b/README.md
@@ -748,6 +748,37 @@ In this step, we:
* Learned that result of operation depends on operand types
* Understood what operator precedence means
* Used parentheses to group parts of an expression
+
+
+
+#### Quiz
+
+What is the result of the expression 5 / 2?
+a) 2
+b) 2.5
+c) Error
+Correct answer: a) 2
+
+Which of the following operators has the highest precedence?
+a) +
+b) *
+c) %
+Correct answer: b) *
+
+Which of the following is the correct way to group the sub-expressions in the expression 5 + 5 * 6?
+a) 5 + (5 * 6)
+b) (5 + 5) * 6
+c) 5 + 5 * 6
+Correct answer: a) 5 + (5 * 6)
+
+#### Hands-on Exercise:
+Write a Java program that takes two integers as input from the user and performs the following operations on them:
+
+* Addition
+* Subtraction
+* Multiplication
+* Division
+Make sure to display the results of each operation to the user. Use parentheses to group the sub-expressions in each operation for better readability.
### Step 07: Introducing Console Output
From 61b6aae4fcad363b6e2718f9ffa8a67467e02b17 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Tue, 21 Mar 2023 22:54:14 +0530
Subject: [PATCH 011/178] update
---
README.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/README.md b/README.md
index c635b500..f18e17bb 100644
--- a/README.md
+++ b/README.md
@@ -778,6 +778,7 @@ Write a Java program that takes two integers as input from the user and performs
* Subtraction
* Multiplication
* Division
+
Make sure to display the results of each operation to the user. Use parentheses to group the sub-expressions in each operation for better readability.
### Step 07: Introducing Console Output
From 97bc05cf1b353c24601443499f938f3a8c305790 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Tue, 21 Mar 2023 22:56:58 +0530
Subject: [PATCH 012/178] update
---
README.md | 28 ++++++++++++++++++++++++++++
1 file changed, 28 insertions(+)
diff --git a/README.md b/README.md
index f18e17bb..b0a77436 100644
--- a/README.md
+++ b/README.md
@@ -877,6 +877,34 @@ In this step, we:
* Were introduced to the ```System.out.println()``` method for console output
* Used this utility to print a single *PMT-Challenge* table entry
+#### Quiz
+
+Question 1: What is the syntax for calling the System.out.println() method in Java?
+a) System.out.println
+b) println.System.out
+c) System.out.print
+
+Correct answer: a) System.out.println
+
+Question 2: What is a String literal in Java?
+a) A sequence of characters enclosed within double quotes
+b) A method call used to display text on the console
+c) A variable used to store numeric values
+
+Correct answer: a) A sequence of characters enclosed within double quotes
+
+Question 3: How do you display the text "5 * 2 = 10" on the console in Java?
+a) System.out.println(5 * 2 = 10)
+b) System.out.println("5 * 2 = 10")
+c) System.out.print("5 * 2 = 10")
+
+Correct answer: b) System.out.println("5 * 2 = 10")
+
+#### Hands-on exercise:
+
+Write a Java program that computes the product of two integers, and displays the result in the format "a * b = c", where a and b are the input integers, and c is their product. Use the System.out.println() method to display the result on the console.
+
+
### Step 08: Programming Exercise PE-02
Try and solve the following exercises:
From 04e0d051f1b82b286d038dac92901ba9b4e5c282 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Tue, 21 Mar 2023 23:01:08 +0530
Subject: [PATCH 013/178] update
---
README.md | 40 ++++++++++++++++++++++++++++++++++++++++
1 file changed, 40 insertions(+)
diff --git a/README.md b/README.md
index b0a77436..ff168c98 100644
--- a/README.md
+++ b/README.md
@@ -924,6 +924,46 @@ Try and solve the following exercises:
* Operands
* Method calls
+
+#### Quiz:
+
+Question 1: What is the first exercise in Programming Exercise PE-02?
+a) Print the calculated value of 5 * 3
+b) Print the number of seconds in a day
+c) Print Hello World onto the console
+
+Answer: c) Print Hello World onto the console
+
+Question 2: What do you need to identify in your code when doing a syntax revision for the exercises in Programming Exercise PE-02?
+a) Loops and conditionals
+b) Numeric and string literals, expressions, operators, operands, and method calls
+c) Classes and objects
+
+Answer: b) Numeric and string literals, expressions, operators, operands, and method calls
+
+Question 3: What should be printed when you execute the code for the second exercise in Programming Exercise PE-02?
+a) "5 * 3"
+b) "15"
+c) 5 * 3
+
+Answer: a) "5 * 3"
+
+#### Hands-on Exercise:
+
+Write a Java program to print the following:
+
+- Your name
+- The year you were born
+- The year you will turn 30
+
+Do a syntax revision for your code, and identify the following elements:
+
+- Numeric and string literals
+- Expressions
+- Operators
+- Operands
+- Method calls
+
### Step 09: Solutions to PE-02
#### Solution 1
From 1f48644696e99e414bca32be64c890c547de7652 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Tue, 21 Mar 2023 23:04:05 +0530
Subject: [PATCH 014/178] update
---
README.md | 28 ++++++++++++++++++++++++++++
1 file changed, 28 insertions(+)
diff --git a/README.md b/README.md
index ff168c98..2a00194e 100644
--- a/README.md
+++ b/README.md
@@ -1002,6 +1002,34 @@ Do a syntax revision for your code, and identify the following elements:
```
+#### Quiz:
+
+Question 1: What is the output of Solution 1?
+a) "5 * 3"
+b) "Hello World"
+c) 15
+
+Answer: b) "Hello World"
+
+Question 2: What is the output of Solution 2?
+a) "15"
+b) "5 * 3"
+c) Syntax Error
+
+Answer: b) "5 * 3"
+
+Question 3: What is the output of Solution 4?
+a) 86400
+b) 5184000
+c) 3600
+
+Answer: a) 86400
+
+#### Hands-on Exercise:
+
+Write a Java program to print the following sentence using the System.out.println() statement:
+- "Java is a programming language."
+
### Step 10: Whitespace, Case sensitiveness and Escape Characters
The term *whitespace* refers to any sequence of continuous space, tab or newline characters.
From f8193a72b50988a89a801e1faf49f67e57c69271 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Tue, 21 Mar 2023 23:05:37 +0530
Subject: [PATCH 015/178] update
---
README.md | 26 ++++++++++++++++++++++++++
1 file changed, 26 insertions(+)
diff --git a/README.md b/README.md
index 2a00194e..d2f7e444 100644
--- a/README.md
+++ b/README.md
@@ -1178,6 +1178,32 @@ In this step, we:
* Discovered the uses of whitespace characters
* Learned about Java escape sequences
+
+#### Quiz
+What happens when you use whitespace around string literals in Java?
+a) It is ignored by the compiler
+b) It produces a syntax error
+Correct answer: a) It is ignored by the compiler
+
+Is Java case sensitive?
+a) Yes
+b) No
+Correct answer: a) Yes
+
+What is the role of the backslash character in Java?
+a) It is a special symbol used for escape sequences
+b) It is used to indicate a syntax error
+Correct answer: a) It is a special symbol used for escape sequences
+
+#### Hands-on exercise:
+Write a Java program that prints the following output to the console:
+````
+Hello
+World
+````
+
+Hint: You can use the escape sequence "\n" to insert a newline and "\t" to insert a tab.
+
### Step 11: More On Method Calls
Let's look at method calls with a few more examples.
From fee7d7940ebcc0c30dc0c5e796f0efe133ea38a0 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Thu, 23 Mar 2023 23:25:45 +0530
Subject: [PATCH 016/178] Thank You
---
RESOURCE.md | 90 +++++++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 90 insertions(+)
create mode 100644 RESOURCE.md
diff --git a/RESOURCE.md b/RESOURCE.md
new file mode 100644
index 00000000..34ee68a5
--- /dev/null
+++ b/RESOURCE.md
@@ -0,0 +1,90 @@
+# Java Multiple Choice Quiz & Code Challenge
+
+# Step 01: First Challenge : The Print-Multiplication-Table (PMT-Challenge)
+
+1. What is the objective of the PMT-Challenge?
+
+ a. To write a program that prints out a multiplication table for 10, with entries from 1 to 5.
+
+ b. To write a program that prints out a multiplication table for 5, with entries from 1 to 10.
+
+ c. To write a program that prints out a multiplication table for 5, with entries from 1 to 5.
+
+ **Answer: b**
+
+2. What is JShell?
+
+ a. A tool for creating and managing databases in Java.
+
+ b. A tool for interactive Java programming, allowing you to experiment with Java code and test snippets of code.
+
+ c. A tool for creating and managing user interfaces in Java.
+
+ **Answer: b**
+
+3. Which Java concept is used to execute a set of statements repeatedly?
+
+ a. Conditionals
+
+ b. Methods
+
+ c. Loops
+
+ **Answer: c**
+
+
+
+## Exercise 1: PMT Challenge Using For Loop
+
+Using JShell, write a program to display the multiplication table for 7, with entries from 1 to 10 using a for loop.
+
+### Solution
+
+Launch JShell and enter the following commands:
+
+javaCopy code
+
+`for(int i = 1; i <= 10; i++) {
+ System.out.println("7 * " + i + " = " + (7*i));
+}`
+
+Output:
+
+Copy code
+
+`7 * 1 = 7
+7 * 2 = 14
+7 * 3 = 21
+7 * 4 = 28
+7 * 5 = 35
+7 * 6 = 42
+7 * 7 = 49
+7 * 8 = 56
+7 * 9 = 63
+7 * 10 = 70`
+
+## Exercise 2: PMT Challenge Using While Loop
+
+Using JShell, write a program to display the multiplication table for 3, with entries from 1 to 5 using a while loop.
+
+### Solution
+
+Launch JShell and enter the following commands:
+
+javaCopy code
+
+`int i = 1;
+while(i <= 5) {
+ System.out.println("3 * " + i + " = " + (3*i));
+ i++;
+}`
+
+Output:
+
+Copy code
+
+`3 * 1 = 3
+3 * 2 = 6
+3 * 3 = 9
+3 * 4 = 12
+3 * 5 = 15`
From 1020d09ec26ef203cb1e6ef7b01539aaa9326f2d Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Thu, 23 Mar 2023 23:27:03 +0530
Subject: [PATCH 017/178] Thank You
---
RESOURCE.md | 12 ++++++------
1 file changed, 6 insertions(+), 6 deletions(-)
diff --git a/RESOURCE.md b/RESOURCE.md
index 34ee68a5..e12d70aa 100644
--- a/RESOURCE.md
+++ b/RESOURCE.md
@@ -1,6 +1,6 @@
-# Java Multiple Choice Quiz & Code Challenge
+## Java Multiple Choice Quiz & Code Challenge
-# Step 01: First Challenge : The Print-Multiplication-Table (PMT-Challenge)
+### Step 01: First Challenge : The Print-Multiplication-Table (PMT-Challenge)
1. What is the objective of the PMT-Challenge?
@@ -34,11 +34,11 @@
-## Exercise 1: PMT Challenge Using For Loop
+#### Exercise 1: PMT Challenge Using For Loop
Using JShell, write a program to display the multiplication table for 7, with entries from 1 to 10 using a for loop.
-### Solution
+###### Solution
Launch JShell and enter the following commands:
@@ -63,11 +63,11 @@ Copy code
7 * 9 = 63
7 * 10 = 70`
-## Exercise 2: PMT Challenge Using While Loop
+#### Exercise 2: PMT Challenge Using While Loop
Using JShell, write a program to display the multiplication table for 3, with entries from 1 to 5 using a while loop.
-### Solution
+###### Solution
Launch JShell and enter the following commands:
From e542acc0b8ba9aaff9573fd9346068f6277757de Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Thu, 23 Mar 2023 23:27:44 +0530
Subject: [PATCH 018/178] Thank You
---
RESOURCE.md | 16 ++++++++--------
1 file changed, 8 insertions(+), 8 deletions(-)
diff --git a/RESOURCE.md b/RESOURCE.md
index e12d70aa..b8410da9 100644
--- a/RESOURCE.md
+++ b/RESOURCE.md
@@ -44,15 +44,15 @@ Launch JShell and enter the following commands:
javaCopy code
-`for(int i = 1; i <= 10; i++) {
+```for(int i = 1; i <= 10; i++) {
System.out.println("7 * " + i + " = " + (7*i));
-}`
+}```
Output:
Copy code
-`7 * 1 = 7
+```7 * 1 = 7
7 * 2 = 14
7 * 3 = 21
7 * 4 = 28
@@ -61,7 +61,7 @@ Copy code
7 * 7 = 49
7 * 8 = 56
7 * 9 = 63
-7 * 10 = 70`
+7 * 10 = 70```
#### Exercise 2: PMT Challenge Using While Loop
@@ -73,18 +73,18 @@ Launch JShell and enter the following commands:
javaCopy code
-`int i = 1;
+```int i = 1;
while(i <= 5) {
System.out.println("3 * " + i + " = " + (3*i));
i++;
-}`
+}```
Output:
Copy code
-`3 * 1 = 3
+```3 * 1 = 3
3 * 2 = 6
3 * 3 = 9
3 * 4 = 12
-3 * 5 = 15`
+3 * 5 = 15```
From 19dc1f5d7d0c9c15e2930e92bf9292c6e5fd9eee Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Thu, 23 Mar 2023 23:28:28 +0530
Subject: [PATCH 019/178] .
---
RESOURCE.md | 28 ++++++++++++++++------------
1 file changed, 16 insertions(+), 12 deletions(-)
diff --git a/RESOURCE.md b/RESOURCE.md
index b8410da9..df137fb1 100644
--- a/RESOURCE.md
+++ b/RESOURCE.md
@@ -42,17 +42,18 @@ Using JShell, write a program to display the multiplication table for 7, with en
Launch JShell and enter the following commands:
-javaCopy code
-```for(int i = 1; i <= 10; i++) {
+```
+for(int i = 1; i <= 10; i++) {
System.out.println("7 * " + i + " = " + (7*i));
-}```
+}
+```
Output:
-Copy code
-```7 * 1 = 7
+```
+7 * 1 = 7
7 * 2 = 14
7 * 3 = 21
7 * 4 = 28
@@ -61,7 +62,8 @@ Copy code
7 * 7 = 49
7 * 8 = 56
7 * 9 = 63
-7 * 10 = 70```
+7 * 10 = 70
+```
#### Exercise 2: PMT Challenge Using While Loop
@@ -71,20 +73,22 @@ Using JShell, write a program to display the multiplication table for 3, with en
Launch JShell and enter the following commands:
-javaCopy code
-```int i = 1;
+```
+int i = 1;
while(i <= 5) {
System.out.println("3 * " + i + " = " + (3*i));
i++;
-}```
+}
+```
Output:
-Copy code
-```3 * 1 = 3
+```
+3 * 1 = 3
3 * 2 = 6
3 * 3 = 9
3 * 4 = 12
-3 * 5 = 15```
+3 * 5 = 15
+```
From 341886fb57af2e91550d83b3eafd3c9579a2b48b Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Thu, 23 Mar 2023 23:31:51 +0530
Subject: [PATCH 020/178] .
---
CODECHALLENGE.md | 63 ++++++++++++++++++++++++++++++++++++++++++
RESOURCE.md => QUIZ.md | 0
2 files changed, 63 insertions(+)
create mode 100644 CODECHALLENGE.md
rename RESOURCE.md => QUIZ.md (100%)
diff --git a/CODECHALLENGE.md b/CODECHALLENGE.md
new file mode 100644
index 00000000..4ec18bc2
--- /dev/null
+++ b/CODECHALLENGE.md
@@ -0,0 +1,63 @@
+## Java Multiple Choice Quiz & Code Challenge
+
+### Step 01: First Challenge : The Print-Multiplication-Table (PMT-Challenge)
+
+
+#### Exercise 1: PMT Challenge Using For Loop
+
+Using JShell, write a program to display the multiplication table for 7, with entries from 1 to 10 using a for loop.
+
+###### Solution
+
+Launch JShell and enter the following commands:
+
+
+```
+for(int i = 1; i <= 10; i++) {
+ System.out.println("7 * " + i + " = " + (7*i));
+}
+```
+
+Output:
+
+
+```
+7 * 1 = 7
+7 * 2 = 14
+7 * 3 = 21
+7 * 4 = 28
+7 * 5 = 35
+7 * 6 = 42
+7 * 7 = 49
+7 * 8 = 56
+7 * 9 = 63
+7 * 10 = 70
+```
+
+#### Exercise 2: PMT Challenge Using While Loop
+
+Using JShell, write a program to display the multiplication table for 3, with entries from 1 to 5 using a while loop.
+
+###### Solution
+
+Launch JShell and enter the following commands:
+
+
+```
+int i = 1;
+while(i <= 5) {
+ System.out.println("3 * " + i + " = " + (3*i));
+ i++;
+}
+```
+
+Output:
+
+
+```
+3 * 1 = 3
+3 * 2 = 6
+3 * 3 = 9
+3 * 4 = 12
+3 * 5 = 15
+```
diff --git a/RESOURCE.md b/QUIZ.md
similarity index 100%
rename from RESOURCE.md
rename to QUIZ.md
From d15b96966e3586baa9a74bcea167eb3b417289b7 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Thu, 23 Mar 2023 23:39:38 +0530
Subject: [PATCH 021/178] .
---
CODECHALLENGE.md | 79 ++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 79 insertions(+)
diff --git a/CODECHALLENGE.md b/CODECHALLENGE.md
index 4ec18bc2..978942d1 100644
--- a/CODECHALLENGE.md
+++ b/CODECHALLENGE.md
@@ -61,3 +61,82 @@ Output:
3 * 4 = 12
3 * 5 = 15
```
+
+
+### Step 02: Introducing JShell
+
+
+#### Exercise 1:
+
+Create a JShell snippet that defines a variable `myNumber` with a value of 10, then use an expression to calculate and display the square of `myNumber`.
+
+##### Solution:
+
+```
+
+`jshell> int myNumber = 10;
+myNumber ==> 10
+ jshell> myNumber * myNumber
+$1 ==> 100`
+```
+
+#### Exercise 2:
+
+Create a JShell snippet that defines a method called `isEven` that takes an integer argument `n` and returns a boolean value indicating whether `n` is even or not. Then, call the method with an integer value of your choice and display the result.
+
+##### Solution:
+
+```
+
+`jshell> boolean isEven(int n) {
+ ...> return n % 2 == 0;
+ ...> }
+| created method isEven(int)
+
+jshell> isEven(7)
+$1 ==> false
+
+jshell> isEven(12)
+$2 ==> true`
+```
+
+
+
+### Step 03: Welcome to Problem Solving
+
+
+#### Java Coding Exercise 1
+
+Using JShell, write a Java code snippet to calculate and print the result of multiplying 7 by 4.
+
+##### Solution
+
+```
+
+`jshell> int result = 7 * 4;
+result ==> 28
+
+jshell> System.out.println(result);
+28`
+```
+
+#### Java Coding Exercise 2
+
+Using JShell, write a Java code snippet to print the multiplication table for 9, with entries from 1 to 5.
+
+##### Solution
+
+```
+
+`jshell> for (int i = 1; i <= 5; i++) {
+ ...> int result = 9 * i;
+ ...> System.out.println("9 * " + i + " = " + result);
+ ...> }
+9 * 1 = 9
+9 * 2 = 18
+9 * 3 = 27
+9 * 4 = 36
+9 * 5 = 45`
+```
+
+Note: The above solution uses a for loop to execute the code 5 times, once for each table entry, and prints the result of each calculation.
\ No newline at end of file
From 40e9640d35f79b8d31174fbb66d4bd56f06da87f Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Thu, 23 Mar 2023 23:40:34 +0530
Subject: [PATCH 022/178] .
---
CODECHALLENGE.md | 16 ++++++++--------
1 file changed, 8 insertions(+), 8 deletions(-)
diff --git a/CODECHALLENGE.md b/CODECHALLENGE.md
index 978942d1..35eebe9b 100644
--- a/CODECHALLENGE.md
+++ b/CODECHALLENGE.md
@@ -74,10 +74,10 @@ Create a JShell snippet that defines a variable `myNumber` with a value of 10, t
```
-`jshell> int myNumber = 10;
+jshell> int myNumber = 10;
myNumber ==> 10
jshell> myNumber * myNumber
-$1 ==> 100`
+$1 ==> 100
```
#### Exercise 2:
@@ -88,7 +88,7 @@ Create a JShell snippet that defines a method called `isEven` that takes an inte
```
-`jshell> boolean isEven(int n) {
+jshell> boolean isEven(int n) {
...> return n % 2 == 0;
...> }
| created method isEven(int)
@@ -97,7 +97,7 @@ jshell> isEven(7)
$1 ==> false
jshell> isEven(12)
-$2 ==> true`
+$2 ==> true
```
@@ -113,11 +113,11 @@ Using JShell, write a Java code snippet to calculate and print the result of mul
```
-`jshell> int result = 7 * 4;
+jshell> int result = 7 * 4;
result ==> 28
jshell> System.out.println(result);
-28`
+28
```
#### Java Coding Exercise 2
@@ -128,7 +128,7 @@ Using JShell, write a Java code snippet to print the multiplication table for 9,
```
-`jshell> for (int i = 1; i <= 5; i++) {
+jshell> for (int i = 1; i <= 5; i++) {
...> int result = 9 * i;
...> System.out.println("9 * " + i + " = " + result);
...> }
@@ -136,7 +136,7 @@ Using JShell, write a Java code snippet to print the multiplication table for 9,
9 * 2 = 18
9 * 3 = 27
9 * 4 = 36
-9 * 5 = 45`
+9 * 5 = 45
```
Note: The above solution uses a for loop to execute the code 5 times, once for each table entry, and prints the result of each calculation.
\ No newline at end of file
From a8e86d7c7d8caf2feb76cdae4701fafbd92c2d62 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Thu, 23 Mar 2023 23:47:12 +0530
Subject: [PATCH 023/178] .
---
CODECHALLENGE.md | 59 +++++++++++++++++++++++++++++++++++++++++++++++-
1 file changed, 58 insertions(+), 1 deletion(-)
diff --git a/CODECHALLENGE.md b/CODECHALLENGE.md
index 35eebe9b..0e1fc55f 100644
--- a/CODECHALLENGE.md
+++ b/CODECHALLENGE.md
@@ -139,4 +139,61 @@ jshell> for (int i = 1; i <= 5; i++) {
9 * 5 = 45
```
-Note: The above solution uses a for loop to execute the code 5 times, once for each table entry, and prints the result of each calculation.
\ No newline at end of file
+Note: The above solution uses a for loop to execute the code 5 times, once for each table entry, and prints the result of each calculation.
+
+
+
+### Step 04: Introducing Expressions
+
+
+#### Exercise 1:
+Write a Java program using JShell to calculate the area of a square with side length of 7 units. Use the appropriate Java operators and follow the steps below:
+
+1. Start JShell.
+2. Define a variable `sideLength` with a value of 7.
+3. Calculate the area of the square and store it in a variable called `area`.
+4. Print the value of `area`.
+5. Exit JShell.
+
+##### Solution:
+
+```
+
+jshell> int sideLength = 7;
+sideLength ==> 7
+ jshell> int area = sideLength * sideLength;
+area ==> 49
+ jshell> System.out.println("Area of the square is: " + area);
+Area of the square is: 49
+ jshell> /exit
+ ```
+
+#### Exercise 2:
+Write a Java program using JShell to calculate the volume of a rectangular prism with length, width, and height of 4, 5, and 6 units respectively. Use the appropriate Java operators and follow the steps below:
+
+1. Start JShell.
+2. Define three variables `length`, `width`, and `height` with values of 4, 5, and 6 respectively.
+3. Calculate the volume of the rectangular prism and store it in a variable called `volume`.
+4. Print the value of `volume`.
+5. Exit JShell.
+
+##### Solution:
+
+````
+jshell> int length = 4;
+length ==> 4
+
+jshell> int width = 5;
+width ==> 5
+
+jshell> int height = 6;
+height ==> 6
+
+jshell> int volume = length * width * height;
+volume ==> 120
+
+jshell> System.out.println("Volume of the rectangular prism is: " + volume);
+Volume of the rectangular prism is: 120
+
+jshell> /exit
+````
\ No newline at end of file
From 34cc46e4e3e624a19115bdf047d3a1223f23472a Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Thu, 23 Mar 2023 23:51:58 +0530
Subject: [PATCH 024/178] .
---
CODECHALLENGE.md | 35 ++++++++++++++++++++++++++++++++++-
1 file changed, 34 insertions(+), 1 deletion(-)
diff --git a/CODECHALLENGE.md b/CODECHALLENGE.md
index 0e1fc55f..06fa125e 100644
--- a/CODECHALLENGE.md
+++ b/CODECHALLENGE.md
@@ -196,4 +196,37 @@ jshell> System.out.println("Volume of the rectangular prism is: " + volume);
Volume of the rectangular prism is: 120
jshell> /exit
-````
\ No newline at end of file
+```
+
+### Step 05: Programming Exercise PE-1 (With Solutions)
+
+
+#### Exercise 1
+
+Write a JShell command to calculate the average of three integers: 10, 20, and 30.
+
+##### Solution:
+
+```
+jshell> int num1 = 10;
+jshell> int num2 = 20;
+jshell> int num3 = 30;
+jshell> int average = (num1 + num2 + num3) / 3;
+jshell> average
+average ==> 20
+```
+
+#### Exercise 2
+
+Write a JShell command to convert a temperature of 75 degrees Fahrenheit to Celsius.
+
+##### Solution:
+
+```
+jshell> double fahrenheit = 75.0;
+jshell> double celsius = (fahrenheit - 32) * 5 / 9;
+jshell> celsius
+celsius ==> 23.88888888888889
+```
+
+Note: The formula to convert Fahrenheit to Celsius is: (°F - 32) * 5/9 = °C
\ No newline at end of file
From 1c73b376ca0fe40ed649b2474c09fa246c23f20b Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Thu, 23 Mar 2023 23:52:45 +0530
Subject: [PATCH 025/178] .
---
CODECHALLENGE.md | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/CODECHALLENGE.md b/CODECHALLENGE.md
index 06fa125e..9a34c0ff 100644
--- a/CODECHALLENGE.md
+++ b/CODECHALLENGE.md
@@ -179,7 +179,7 @@ Write a Java program using JShell to calculate the volume of a rectangular prism
##### Solution:
-````
+```
jshell> int length = 4;
length ==> 4
@@ -196,6 +196,7 @@ jshell> System.out.println("Volume of the rectangular prism is: " + volume);
Volume of the rectangular prism is: 120
jshell> /exit
+
```
### Step 05: Programming Exercise PE-1 (With Solutions)
From 83217ba25ef8043bb3419551be9cba44822195df Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Thu, 23 Mar 2023 23:59:27 +0530
Subject: [PATCH 026/178] .
---
CODECHALLENGE.md | 51 +++++++++++++++++++++++++++++++++++++++++++++++-
1 file changed, 50 insertions(+), 1 deletion(-)
diff --git a/CODECHALLENGE.md b/CODECHALLENGE.md
index 9a34c0ff..0049728a 100644
--- a/CODECHALLENGE.md
+++ b/CODECHALLENGE.md
@@ -230,4 +230,53 @@ jshell> celsius
celsius ==> 23.88888888888889
```
-Note: The formula to convert Fahrenheit to Celsius is: (°F - 32) * 5/9 = °C
\ No newline at end of file
+Note: The formula to convert Fahrenheit to Celsius is: (°F - 32) * 5/9 = °C
+
+
+### Step 06: Operators
+
+#### Exercise 1: Operator Practice
+
+Write a Java program using JShell that takes two integers as input and prints their sum, difference, product, and quotient. Use appropriate operators to perform these operations.
+
+##### Solution
+
+```
+// Use JShell to declare variables and perform arithmetic operations
+int num1 = 10;
+int num2 = 5;
+
+// Calculate and print sum, difference, product, and quotient
+System.out.println("Sum: " + (num1 + num2));
+System.out.println("Difference: " + (num1 - num2));
+System.out.println("Product: " + (num1 * num2));
+System.out.println("Quotient: " + (num1 / num2));
+```
+
+#### Exercise 2: Operator Precedence
+
+Write a Java program using JShell that takes three integers as input and calculates the value of the following expression:
+
+`(num1 + num2) * num3 / 2`
+
+##### Solution
+
+```
+// Use JShell to declare variables and perform arithmetic operations
+int num1 = 5;
+int num2 = 10;
+int num3 = 2;
+
+// Calculate the value of the expression
+int result = (num1 + num2) * num3 / 2;
+
+// Print the result
+System.out.println("Result: " + result);
+
+```
+
+Explanation:
+
+- First, the expressions inside the parentheses `(num1 + num2)` are evaluated, resulting in the sum of `num1` and `num2`.
+- Next, the result of the previous step is multiplied by `num3`, giving `(num1 + num2) * num3`.
+- Finally, the result of the previous step is divided by `2`, resulting in the final value of the expression.
From d1951733e8ddd8986925ffeea9accffaea50b0f9 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Fri, 24 Mar 2023 00:07:46 +0530
Subject: [PATCH 027/178] .
---
CODECHALLENGE.md | 38 ++++++++++++++++++++++++++++++++++++++
1 file changed, 38 insertions(+)
diff --git a/CODECHALLENGE.md b/CODECHALLENGE.md
index 0049728a..f5574126 100644
--- a/CODECHALLENGE.md
+++ b/CODECHALLENGE.md
@@ -280,3 +280,41 @@ Explanation:
- First, the expressions inside the parentheses `(num1 + num2)` are evaluated, resulting in the sum of `num1` and `num2`.
- Next, the result of the previous step is multiplied by `num3`, giving `(num1 + num2) * num3`.
- Finally, the result of the previous step is divided by `2`, resulting in the final value of the expression.
+
+
+### Step 07: Introducing Console Output
+
+
+#### Exercise 1:
+
+Challenge: Write a Java program that takes a user's name as input and greets the user by printing "Hello, [name]!" to the console using JShell.
+
+##### Solution:
+
+```
+jshell> String name = "Alice";
+name ==> "Alice"
+
+jshell> System.out.println("Hello, " + name + "!");
+Hello, Alice!
+```
+
+#### Exercise 2:
+
+Challenge: Write a Java program that takes two numbers as input and prints their product in the format "[num1] * [num2] = [product]" to the console using JShell.
+
+##### Solution:
+
+```
+jshell> int num1 = 5;
+num1 ==> 5
+
+jshell> int num2 = 3;
+num2 ==> 3
+
+jshell> int product = num1 * num2;
+product ==> 15
+
+jshell> System.out.println(num1 + " * " + num2 + " = " + product);
+5 * 3 = 15
+```
From d6e97bc9c16b1a6af9bfce172ceef9789930f858 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Fri, 24 Mar 2023 00:12:30 +0530
Subject: [PATCH 028/178] .
---
CODECHALLENGE.md | 69 ++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 69 insertions(+)
diff --git a/CODECHALLENGE.md b/CODECHALLENGE.md
index f5574126..9c9f1d8f 100644
--- a/CODECHALLENGE.md
+++ b/CODECHALLENGE.md
@@ -318,3 +318,72 @@ product ==> 15
jshell> System.out.println(num1 + " * " + num2 + " = " + product);
5 * 3 = 15
```
+
+
+
+
+### Programming Exercise PE-02
+
+
+
+#### Exercise 1
+
+Using JShell, write a program that prints out the message "Hello World" onto the console.
+
+##### Solution
+
+```
+System.out.println("Hello World");
+```
+
+#### Syntax Revision
+
+```
+//Numeric and string literals
+System.out.println("Hello World");
+
+//Expressions
+//There are no expressions in this code.
+
+//Operators
+//There are no operators in this code.
+
+//Operands
+//There are no operands in this code.
+
+//Method calls
+System.out.println();
+```
+
+#### Exercise 2
+
+Using JShell, write a program that prints out the result of the expression 5 * 3, both as an expression and as the calculated value.
+
+##### Solution
+
+```
+//Print the expression
+System.out.println("5 * 3");
+
+//Print the calculated value
+System.out.println(5 * 3);
+```
+
+#### Syntax Revision
+
+```
+//Numeric and string literals
+System.out.println("5 * 3");
+
+//Expressions
+System.out.println(5 * 3);
+
+//Operators
+//The * operator is used to multiply 5 and 3.
+
+//Operands
+//The operands in this code are 5 and 3.
+
+//Method calls
+System.out.println();
+```
\ No newline at end of file
From ff1eb8866e755a29cf0a10078b0ccf836ca5abdf Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Fri, 24 Mar 2023 00:12:52 +0530
Subject: [PATCH 029/178] .
---
CODECHALLENGE.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/CODECHALLENGE.md b/CODECHALLENGE.md
index 9c9f1d8f..d1f20975 100644
--- a/CODECHALLENGE.md
+++ b/CODECHALLENGE.md
@@ -322,7 +322,7 @@ jshell> System.out.println(num1 + " * " + num2 + " = " + product);
-### Programming Exercise PE-02
+### 8. Programming Exercise PE-02
From cc408a3273b5acc0ee8314762df33f428b873851 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Fri, 24 Mar 2023 00:13:08 +0530
Subject: [PATCH 030/178] .
---
CODECHALLENGE.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/CODECHALLENGE.md b/CODECHALLENGE.md
index d1f20975..afe15fae 100644
--- a/CODECHALLENGE.md
+++ b/CODECHALLENGE.md
@@ -322,7 +322,7 @@ jshell> System.out.println(num1 + " * " + num2 + " = " + product);
-### 8. Programming Exercise PE-02
+### Step 08: Programming Exercise PE-02
From 31436f5b0e2d637162f0e08fb76e0f58a6924788 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Fri, 24 Mar 2023 00:14:44 +0530
Subject: [PATCH 031/178] .
---
CODECHALLENGE.md | 34 ++++++++++++++++++++++++++++++++++
1 file changed, 34 insertions(+)
diff --git a/CODECHALLENGE.md b/CODECHALLENGE.md
index afe15fae..4ef29524 100644
--- a/CODECHALLENGE.md
+++ b/CODECHALLENGE.md
@@ -386,4 +386,38 @@ System.out.println(5 * 3);
//Method calls
System.out.println();
+```
+
+
+
+### Step 09: Solutions to PE-02
+
+#### Exercise 1
+
+Create a program in JShell that displays the sum of 2 and 3.
+
+**Solution:**
+
+pythonCopy code
+
+```
+jshell> int sum = 2 + 3;
+sum ==> 5
+jshell> System.out.println("The sum of 2 and 3 is: " + sum);
+The sum of 2 and 3 is: 5
+```
+
+#### Exercise 2
+
+Create a program in JShell that converts a temperature from Celsius to Fahrenheit. The formula for converting Celsius to Fahrenheit is F = (C * 1.8) + 32.
+
+**Solution:**
+
+```
+jshell> double celsius = 20.0;
+celsius ==> 20.0
+jshell> double fahrenheit = (celsius * 1.8) + 32;
+fahrenheit ==> 68.0
+jshell> System.out.println(celsius + " degrees Celsius is equal to " + fahrenheit + " degrees Fahrenheit.");
+20.0 degrees Celsius is equal to 68.0 degrees Fahrenheit.
```
\ No newline at end of file
From 006d2025292c18e833966c1321d28488f3ec4841 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Fri, 24 Mar 2023 00:20:54 +0530
Subject: [PATCH 032/178] .
---
CODECHALLENGE.md | 56 +++++++++++++++++++++++++++++++++++++++++++++++-
1 file changed, 55 insertions(+), 1 deletion(-)
diff --git a/CODECHALLENGE.md b/CODECHALLENGE.md
index 4ef29524..0b7db3b0 100644
--- a/CODECHALLENGE.md
+++ b/CODECHALLENGE.md
@@ -398,7 +398,6 @@ Create a program in JShell that displays the sum of 2 and 3.
**Solution:**
-pythonCopy code
```
jshell> int sum = 2 + 3;
@@ -420,4 +419,59 @@ jshell> double fahrenheit = (celsius * 1.8) + 32;
fahrenheit ==> 68.0
jshell> System.out.println(celsius + " degrees Celsius is equal to " + fahrenheit + " degrees Fahrenheit.");
20.0 degrees Celsius is equal to 68.0 degrees Fahrenheit.
+```
+
+
+### Step 10: Whitespace, Case sensitiveness and Escape Characters
+
+#### Exercise 1: Whitespace Counter
+
+Write a program that takes a string input and counts the number of whitespace characters in it. Use JShell to test your program with the following inputs:
+
+Input 1:
+
+
+`"The quick brown fox jumps over the lazy dog."`
+
+Expected Output 1:
+
+`8`
+
+Input 2:
+
+`"Java Programming is Fun!"`
+
+Expected Output 2:
+
+`6`
+
+##### Solution:
+
+
+
+```
+int whitespaceCount = 0;
+String input = "The quick brown fox jumps over the lazy dog.";
+for (int i = 0; i < input.length(); i++) {
+ if (Character.isWhitespace(input.charAt(i))) {
+ whitespaceCount++;
+ }
+}
+System.out.println(whitespaceCount);
+```
+
+#### Exercise 2: Escape Sequence Example
+
+Write a program that uses escape sequences to print the following message exactly as shown below:
+
+
+`Java is a "programming" language.`
+
+Use JShell to test your program.
+
+##### Solution:
+
+
+```
+System.out.println("Java is a \"programming\" language.");
```
\ No newline at end of file
From cfb97dc984d58030ec087590790937d681a97620 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Fri, 24 Mar 2023 10:23:01 +0530
Subject: [PATCH 033/178] Update CODECHALLENGE.md
---
CODECHALLENGE.md | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/CODECHALLENGE.md b/CODECHALLENGE.md
index 0b7db3b0..96f871c6 100644
--- a/CODECHALLENGE.md
+++ b/CODECHALLENGE.md
@@ -1,4 +1,4 @@
-## Java Multiple Choice Quiz & Code Challenge
+## Java Code Challenge
### Step 01: First Challenge : The Print-Multiplication-Table (PMT-Challenge)
@@ -474,4 +474,4 @@ Use JShell to test your program.
```
System.out.println("Java is a \"programming\" language.");
-```
\ No newline at end of file
+```
From 649d7ca5e3454dbc2ec331d0ec6016a726890bee Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Fri, 24 Mar 2023 10:23:12 +0530
Subject: [PATCH 034/178] Update QUIZ.md
---
QUIZ.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/QUIZ.md b/QUIZ.md
index df137fb1..1988933c 100644
--- a/QUIZ.md
+++ b/QUIZ.md
@@ -1,4 +1,4 @@
-## Java Multiple Choice Quiz & Code Challenge
+## Java Multiple Choice Quiz
### Step 01: First Challenge : The Print-Multiplication-Table (PMT-Challenge)
From ad9fee4d1056798e2b26fe7719222a95483f97aa Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Fri, 24 Mar 2023 15:09:03 +0530
Subject: [PATCH 035/178] .
---
CODECHALLENGE.md | 56 ++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 56 insertions(+)
diff --git a/CODECHALLENGE.md b/CODECHALLENGE.md
index 96f871c6..4fd63d36 100644
--- a/CODECHALLENGE.md
+++ b/CODECHALLENGE.md
@@ -475,3 +475,59 @@ Use JShell to test your program.
```
System.out.println("Java is a \"programming\" language.");
```
+
+
+### Step 11: More On Method Calls
+
+
+#### Exercise 1: JShell Math Practice
+
+Create a program using JShell that does the following:
+
+1. Generates a random integer between 1 and 10 inclusive using the Math.random() method.
+2. Prints out the random integer.
+3. Calculates the square root of the random integer using the Math.sqrt() method.
+4. Prints out the square root.
+
+##### Solution:
+
+```
+jshell> int randomNum = (int)(Math.random() * 10 + 1)
+randomNum ==> 6
+
+jshell> double sqrtNum = Math.sqrt(randomNum)
+sqrtNum ==> 2.449489742783178
+
+jshell> System.out.println("Random integer: " + randomNum);
+Random integer: 6
+
+jshell> System.out.println("Square root of random integer: " + sqrtNum);
+Square root of random integer: 2.449489742783178
+```
+
+#### Exercise 2: Max of Three Numbers
+
+Create a program using JShell that finds the maximum of three numbers using the Math.max() method.
+
+1. Declare three integer variables and assign them values.
+2. Call the Math.max() method with the three variables as parameters.
+3. Print out the result.
+
+##### Solution:
+
+```
+jshell> int num1 = 10;
+num1 ==> 10
+
+jshell> int num2 = 15;
+num2 ==> 15
+
+jshell> int num3 = 8;
+num3 ==> 8
+
+jshell> int maxNum = Math.max(Math.max(num1, num2), num3);
+maxNum ==> 15
+
+jshell> System.out.println("Maximum of " + num1 + ", " + num2 + ", and " + num3 + " is: " + maxNum);
+Maximum of 10, 15, and 8 is: 15
+```
From e98c08ef25d46963b5f1c6da3c36228cb3f9bb0c Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Fri, 24 Mar 2023 15:13:19 +0530
Subject: [PATCH 036/178] .
---
CODECHALLENGE.md | 59 ++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 59 insertions(+)
diff --git a/CODECHALLENGE.md b/CODECHALLENGE.md
index 4fd63d36..05cbc0cc 100644
--- a/CODECHALLENGE.md
+++ b/CODECHALLENGE.md
@@ -531,3 +531,62 @@ maxNum ==> 15
jshell> System.out.println("Maximum of " + num1 + ", " + num2 + ", and " + num3 + " is: " + maxNum);
Maximum of 10, 15, and 8 is: 15
```
+
+
+
+### Step 12: More Formatted Output
+
+
+#### Exercise 1:
+Create a Java program using JShell to print the following multiplication table on the console:
+
+1 * 1 = 1 1 * 2 = 2 1 * 3 = 3 ... 1 * 10 = 10
+
+##### Solution 1:
+
+```
+// Using JShell to print multiplication table for 1
+for (int i = 1; i <= 10; i++) {
+ System.out.printf("1 * %d = %d%n", i, 1 * i);
+}
+```
+Output:
+
+```
+1 * 1 = 1
+1 * 2 = 2
+1 * 3 = 3
+1 * 4 = 4
+1 * 5 = 5
+1 * 6 = 6
+1 * 7 = 7
+1 * 8 = 8
+1 * 9 = 9
+1 * 10 = 10
+```
+
+Explanation: The for loop iterates from 1 to 10, and for each iteration, it uses the printf method to print the multiplication table for 1. The `%d` format specifier is used to print the value of the loop variable `i`, and `%n` is used to print a newline character.
+
+#### Exercise 2:
+Create a Java program using JShell to print the following output on the console:
+
+3.5 + 2.8 + 1.9 = 8.2
+
+##### Solution 2:
+
+```
+// Using JShell to print the sum of three decimal numbers
+double a = 3.5;
+double b = 2.8;
+double c = 1.9;
+double sum = a + b + c;
+System.out.printf("%.1f + %.1f + %.1f = %.1f%n", a, b, c, sum);
+```
+
+Output:
+
+```
+3.5 + 2.8 + 1.9 = 8.2
+```
+
+Explanation: The program declares three double variables `a`, `b`, and `c`, and initializes them with the values 3.5, 2.8, and 1.9 respectively. It then calculates the sum of these variables and stores it in the `sum` variable. Finally, it uses the printf method to print the output with one decimal point using the `%f` format specifier and the `%.1f` modifier. `%n` is used to print a newline character.
From 08f0de9e467dd0b2bc44ad038335f26ceb0eaebe Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Fri, 24 Mar 2023 15:25:10 +0530
Subject: [PATCH 037/178] .
---
CODECHALLENGE.md | 108 +++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 108 insertions(+)
diff --git a/CODECHALLENGE.md b/CODECHALLENGE.md
index 05cbc0cc..b74ca7a0 100644
--- a/CODECHALLENGE.md
+++ b/CODECHALLENGE.md
@@ -590,3 +590,111 @@ Output:
```
Explanation: The program declares three double variables `a`, `b`, and `c`, and initializes them with the values 3.5, 2.8, and 1.9 respectively. It then calculates the sum of these variables and stores it in the `sum` variable. Finally, it uses the printf method to print the output with one decimal point using the `%f` format specifier and the `%.1f` modifier. `%n` is used to print a newline character.
+
+
+### Step 13: Introducing Variables
+
+
+#### Exercise 1: Simple Variable Assignment
+
+In this exercise, you will use JShell to create a variable and assign a value to it. You will then modify the value of the variable and print out the new value.
+
+1. Open up JShell in your command prompt or terminal.
+2. Define an integer variable named "number" and assign it a value of 5.
+3. Print out the value of the "number" variable.
+4. Change the value of the "number" variable to 10.
+5. Print out the new value of the "number" variable.
+
+##### Solution:
+
+1. Open up JShell in your command prompt or terminal.
+
+2. Define an integer variable named "number" and assign it a value of 5.
+
+
+```
+jshell> int number = 5
+number ==> 5
+```
+
+3. Print out the value of the "number" variable.
+
+```
+jshell> System.out.println(number)
+5
+```
+
+4. Change the value of the "number" variable to 10.
+
+```
+jshell> number = 10
+number ==> 10
+```
+
+5. Print out the new value of the "number" variable.
+
+```
+jshell> System.out.println(number)
+10
+```
+
+#### Exercise 2: Multiplication Table with Variables
+
+In this exercise, you will use JShell to create a multiplication table using variables. You will define a variable "i" and use it to print out the multiplication table for the number 5.
+
+1. Open up JShell in your command prompt or terminal.
+2. Define an integer variable named "i" and assign it a value of 1.
+3. Print out the multiplication table for the number 5 using the "i" variable.
+4. Change the value of the "i" variable to 2 and print out the corresponding multiplication table.
+5. Repeat step 4 for the values of "i" from 3 to 10.
+
+##### Solution:
+
+1. Open up JShell in your command prompt or terminal.
+
+2. Define an integer variable named "i" and assign it a value of 1.
+
+
+```
+jshell> int i = 1
+i ==> 1
+```
+
+3. Print out the multiplication table for the number 5 using the "i" variable.
+
+```
+jshell> System.out.printf("%d * %d = %d\n", 5, i, 5*i)
+5 * 1 = 5
+```
+
+4. Change the value of the "i" variable to 2 and print out the corresponding multiplication table.
+
+```
+jshell> i = 2
+i ==> 2
+jshell> System.out.printf("%d * %d = %d\n", 5, i, 5*i)
+5 * 2 = 10
+```
+
+5. Repeat step 4 for the values of "i" from 3 to 10.
+
+```
+jshell> i = 3
+i ==> 3
+jshell> System.out.printf("%d * %d = %d\n", 5, i, 5*i)
+5 * 3 = 15
+
+jshell> i = 4
+i ==> 4
+jshell> System.out.printf("%d * %d = %d\n", 5, i, 5*i)
+5 * 4 = 20
+
+jshell> i = 5
+i ==> 5
+jshell> System.out.printf("%d * %d = %d\n", 5, i, 5*i)
+5 * 5 = 25
+
+jshell> i = 6
+i ==> 6
+jshell> System.out.printf("%d * %d = %d
+```
\ No newline at end of file
From cb0607389c1d43cf89e5fc9831d7cf080393b57e Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Fri, 24 Mar 2023 15:28:46 +0530
Subject: [PATCH 038/178] .
---
CODECHALLENGE.md | 61 ++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 61 insertions(+)
diff --git a/CODECHALLENGE.md b/CODECHALLENGE.md
index b74ca7a0..87a9e01c 100644
--- a/CODECHALLENGE.md
+++ b/CODECHALLENGE.md
@@ -697,4 +697,65 @@ jshell> System.out.printf("%d * %d = %d\n", 5, i, 5*i)
jshell> i = 6
i ==> 6
jshell> System.out.printf("%d * %d = %d
+```
+
+
+
+
+### Step 14: Programming Exercise PE-03 (With solution)
+
+
+
+#### Exercise 1: JShell Basics
+
+1. Open JShell and declare an integer variable called `myNum` with a value of 10.
+2. Print the value of `myNum`.
+3. Change the value of `myNum` to 15 and print it again.
+
+##### Solution to Exercise 1:
+
+```
+jshell> int myNum = 10;
+myNum ==> 10
+ jshell> System.out.println(myNum);
+10
+ jshell> myNum = 15;
+myNum ==> 15
+ jshell> System.out.println(myNum);
+15
+```
+
+#### Exercise 2: Looping with JShell
+
+1. Use a for loop to print the numbers from 1 to 10.
+2. Create a new variable called `sum` and initialize it to 0.
+3. Use a for loop to add the numbers from 1 to 10 to `sum`.
+4. Print the value of `sum`.
+
+##### Solution to Exercise 2:
+
+```
+jshell> for (int i = 1; i <= 10; i++) {
+ ...> System.out.println(i);
+ ...> }
+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+
+jshell> int sum = 0;
+sum ==> 0
+
+jshell> for (int i = 1; i <= 10; i++) {
+ ...> sum += i;
+ ...> }
+
+jshell> System.out.println(sum);
+55
```
\ No newline at end of file
From ff5d09e25dde7d54c12e26bfdb4de0279e38b9a2 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Fri, 24 Mar 2023 15:30:45 +0530
Subject: [PATCH 039/178] .
---
CODECHALLENGE.md | 34 ++++++++++++++++++++++++++++++++++
1 file changed, 34 insertions(+)
diff --git a/CODECHALLENGE.md b/CODECHALLENGE.md
index 87a9e01c..ed2bd6ed 100644
--- a/CODECHALLENGE.md
+++ b/CODECHALLENGE.md
@@ -758,4 +758,38 @@ jshell> for (int i = 1; i <= 10; i++) {
jshell> System.out.println(sum);
55
+```
+
+
+### Step 15: Using Variables
+
+#### Java Coding Exercise 1
+
+Write a Java program using JShell to declare an integer variable called "age" and assign it a value of 25. Then, print the value of "age" on the console.
+
+##### Solution:
+
+```
+jshell> int age = 25;
+age ==> 25
+
+jshell> System.out.println(age);
+25
+```
+
+#### Java Coding Exercise 2
+
+Write a Java program using JShell to declare two variables, "name" and "age". Assign your name to the variable "name" and your age to the variable "age". Then, print the values of both variables on the console in the following format: "My name is [name] and I am [age] years old."
+
+##### Solution:
+
+```
+jshell> String name = "John Doe";
+name ==> "John Doe"
+
+jshell> int age = 30;
+age ==> 30
+
+jshell> System.out.println("My name is " + name + " and I am " + age + " years old.");
+My name is John Doe and I am 30 years old.
```
\ No newline at end of file
From 665b4c41f6ee2559c94dbc8651a342876011c861 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sat, 25 Mar 2023 09:45:12 +0530
Subject: [PATCH 040/178] .
---
CODECHALLENGE.md | 48 ++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 48 insertions(+)
diff --git a/CODECHALLENGE.md b/CODECHALLENGE.md
index ed2bd6ed..1845ca9a 100644
--- a/CODECHALLENGE.md
+++ b/CODECHALLENGE.md
@@ -792,4 +792,52 @@ age ==> 30
jshell> System.out.println("My name is " + name + " and I am " + age + " years old.");
My name is John Doe and I am 30 years old.
+```
+
+
+
+### Step 16: Variables: Behind-The-Scenes
+
+
+
+#### Exercise 1
+
+Create a JShell program that declares three variables of type `int`, initializes the first two variables with integer values, and assigns the sum of the first two variables to the third variable.
+
+##### Solution
+
+```
+`// Declare three variables and assign values to the first two variables
+jshell> int num1 = 10;
+num1 ==> 10
+jshell> int num2 = 20;
+num2 ==> 20
+
+// Assign the sum of the first two variables to the third variable
+jshell> int sum = num1 + num2;
+sum ==> 30
+
+// Verify that the third variable has the correct value
+jshell> sum
+sum ==> 30
+```
+
+#### Exercise 2
+
+Create a JShell program that declares two variables of type `double`, initializes the first variable with a double value, and assigns the sum of the first variable and a second double value to the second variable.
+
+##### Solution
+
+```
+// Declare two variables of type double and initialize the first variable with a double value
+jshell> double num1 = 3.14;
+num1 ==> 3.14
+
+// Assign the sum of the first variable and a second double value to the second variable
+jshell> double num2 = num1 + 2.0;
+num2 ==> 5.14
+
+// Verify that the second variable has the correct value
+jshell> num2
+num2 ==> 5.14
```
\ No newline at end of file
From 3ee9713b8af35cc5dce52530da1918605fb4c495 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sat, 25 Mar 2023 09:54:25 +0530
Subject: [PATCH 041/178] .
---
CODECHALLENGE.md | 117 ++++++++++++++++++++++++++++++++++++++++++++++-
1 file changed, 116 insertions(+), 1 deletion(-)
diff --git a/CODECHALLENGE.md b/CODECHALLENGE.md
index 1845ca9a..f8ebfb8d 100644
--- a/CODECHALLENGE.md
+++ b/CODECHALLENGE.md
@@ -840,4 +840,119 @@ num2 ==> 5.14
// Verify that the second variable has the correct value
jshell> num2
num2 ==> 5.14
-```
\ No newline at end of file
+```
+
+
+
+### Step 17: Naming Variables
+
+
+#### Exercise 1
+
+Create a variable of type `int` in JShell with the following requirements:
+
+1. The variable name should start with a letter.
+2. The variable name should be in CamelCase.
+3. The variable name should be descriptive.
+
+**Solution:**
+
+```
+jshell> int numberOfStudents
+numberOfStudents ==> 0
+```
+
+#### Exercise 2
+
+Create a variable of type `String` in JShell with the following requirements:
+
+1. The variable name should contain an underscore.
+2. The variable name should be descriptive.
+
+**Solution:**
+
+```
+jshell> String student_name
+student_name ==> null
+```
+
+
+
+### Step 18: Introducing Primitive Types
+
+#### Exercise 1: Using JShell to Perform Arithmetic Operations on Primitive Types
+
+**Problem:**
+
+In this exercise, you will use JShell to perform arithmetic operations on various primitive types in Java. Perform the following operations and observe the results:
+
+1. Add two `int` values.
+2. Multiply two `float` values.
+3. Divide a `double` value by an `int` value.
+4. Find the remainder when a `long` value is divided by an `int` value.
+
+**Solution:**
+
+Open JShell and execute the following commands:
+
+```
+int a = 15;
+int b = 25;
+int sum = a + b;
+System.out.println("The sum of a and b is: " + sum);
+
+float c = 3.5f;
+float d = 2.0f;
+float product = c * d;
+System.out.println("The product of c and d is: " + product);
+
+double e = 30.0;
+int f = 4;
+double division = e / f;
+System.out.println("The result of dividing e by f is: " + division);
+
+long g = 10000000000L;
+int h = 7;
+long remainder = g % h;
+System.out.println("The remainder when g is divided by h is: " + remainder);
+```
+
+#### Exercise 2: Comparing Primitive Types in JShell
+
+**Problem:**
+
+In this exercise, you will use JShell to compare various primitive types in Java. Compare the following pairs of values and determine if they are equal:
+
+1. Two `int` values.
+2. Two `float` values.
+3. Two `double` values.
+4. Two `char` values.
+
+**Solution:**
+
+Open JShell and execute the following commands:
+
+```
+int i1 = 42;
+int i2 = 42;
+boolean intsEqual = (i1 == i2);
+System.out.println("Are i1 and i2 equal? " + intsEqual);
+
+float f1 = 3.14f;
+float f2 = 3.14f;
+boolean floatsEqual = (f1 == f2);
+System.out.println("Are f1 and f2 equal? " + floatsEqual);
+
+double d1 = 25.678;
+double d2 = 25.678;
+boolean doublesEqual = (d1 == d2);
+System.out.println("Are d1 and d2 equal? " + doublesEqual);
+
+char c1 = 'A';
+char c2 = 'A';
+boolean charsEqual = (c1 == c2);
+System.out.println("Are c1 and c2 equal? " + charsEqual);
+```
+
+These exercises will help you gain hands-on experience with primitive types and their operations in Java using JShell.
+
From 984221bbe6371f9ab2f16619784c616f0dda7ec8 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sat, 25 Mar 2023 09:59:42 +0530
Subject: [PATCH 042/178] .
---
CODECHALLENGE.md | 51 ++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 51 insertions(+)
diff --git a/CODECHALLENGE.md b/CODECHALLENGE.md
index f8ebfb8d..ad95a0aa 100644
--- a/CODECHALLENGE.md
+++ b/CODECHALLENGE.md
@@ -956,3 +956,54 @@ System.out.println("Are c1 and c2 equal? " + charsEqual);
These exercises will help you gain hands-on experience with primitive types and their operations in Java using JShell.
+
+### Step 19: Choosing A Data Type
+
+
+#### Exercise 1: Calculating average temperature
+
+**Problem:**
+
+Write a program in JShell to calculate the average temperature of a week. Store the daily temperatures in an array, and then calculate and display the average temperature.
+
+**Solution:**
+
+```
+// Initialize the array with daily temperatures (in Celsius)
+double[] dailyTemperatures = {20.5, 22.3, 18.9, 19.6, 21.4, 23.7, 20.1};
+
+// Calculate the sum of temperatures
+double sumTemperatures = 0;
+for (int i = 0; i < dailyTemperatures.length; i++) {
+ sumTemperatures += dailyTemperatures[i];
+}
+
+// Calculate the average temperature
+double averageTemperature = sumTemperatures / dailyTemperatures.length;
+
+// Display the average temperature
+System.out.println("The average temperature for the week is: " + averageTemperature);
+```
+
+#### Exercise 2: Determining leap years
+
+**Problem:**
+
+Write a program in JShell to determine if a given year is a leap year or not. A leap year is a year that is exactly divisible by 4, except for years that are exactly divisible by 100. However, years that are exactly divisible by 400 are also considered leap years.
+
+**Solution:**
+
+```
+// Define a year to check if it's a leap year
+int year = 2024;
+
+// Determine if the year is a leap year
+boolean isLeapYear = (year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0);
+
+// Display the result
+if (isLeapYear) {
+ System.out.println(year + " is a leap year.");
+} else {
+ System.out.println(year + " is not a leap year.");
+}
+```
\ No newline at end of file
From de4716c3284c8121abd074d4ed9163cb0330583c Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sat, 25 Mar 2023 10:05:26 +0530
Subject: [PATCH 043/178] .
---
CODECHALLENGE.md | 59 ++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 59 insertions(+)
diff --git a/CODECHALLENGE.md b/CODECHALLENGE.md
index ad95a0aa..2d585ac9 100644
--- a/CODECHALLENGE.md
+++ b/CODECHALLENGE.md
@@ -1006,4 +1006,63 @@ if (isLeapYear) {
} else {
System.out.println(year + " is not a leap year.");
}
+```
+
+
+
+
+### Step 20: The Assignment Operator =
+
+
+
+
+#### Exercise 1: Increment and Decrement Counter
+
+**Problem**
+
+Write a Java program using JShell to demonstrate the use of increment and decrement operations on a counter variable `counter`. Follow these steps:
+
+1. Initialize `counter` with 0.
+2. Increment `counter` by 5.
+3. Decrement `counter` by 2.
+
+**Solution**
+
+```
+jshell> int counter = 0;
+counter ==> 0
+
+jshell> counter = counter + 5;
+counter ==> 5
+
+jshell> counter = counter - 2;
+counter ==> 3
+
+jshell> counter;
+counter ==> 3
+```
+
+#### Exercise 2: Calculate the power of a number using increments
+
+**Problem**
+
+Write a Java program using JShell to calculate the power of a number `base` raised to an exponent `exponent`. Do this using increments and a loop.
+
+**Solution**
+
+```
+jshell> int base = 2;
+base ==> 2
+
+jshell> int exponent = 3;
+exponent ==> 3
+
+jshell> int result = 1;
+result ==> 1
+
+jshell> for (int i = 0; i < exponent; i++) {
+ ...> result = result * base;
+ ...> }
+jshell> result;
+result ==> 8
```
\ No newline at end of file
From f22d03a13832d06b981ff5edf119959811f87aad Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sat, 25 Mar 2023 10:21:19 +0530
Subject: [PATCH 044/178] .
---
CODECHALLENGE.md | 258 +++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 258 insertions(+)
diff --git a/CODECHALLENGE.md b/CODECHALLENGE.md
index 2d585ac9..f114fdae 100644
--- a/CODECHALLENGE.md
+++ b/CODECHALLENGE.md
@@ -1065,4 +1065,262 @@ jshell> for (int i = 0; i < exponent; i++) {
...> }
jshell> result;
result ==> 8
+```
+
+
+
+### Step 21: Assignment Puzzles, and PMT-Challenge revisited
+
+
+
+#### Exercise 1: Pre- and Post- Increment and Decrement with JShell
+
+**Problem:**
+
+Using JShell, create a variable called `count` and initialize it with the value `10`. Then, apply pre- and post-increment and pre- and post-decrement operators. Print the value of the `count` variable after each operation to observe the differences.
+
+**Solution:**
+
+```
+jshell> int count = 10
+count ==> 10
+
+jshell> ++count
+$1 ==> 11
+
+jshell> count
+count ==> 11
+
+jshell> count++
+$2 ==> 11
+
+jshell> count
+count ==> 12
+
+jshell> --count
+$3 ==> 11
+
+jshell> count
+count ==> 11
+
+jshell> count--
+$4 ==> 11
+
+jshell> count
+count ==> 10
+```
+
+#### Exercise 2: Compound Assignment Operators with JShell
+
+**Problem:**
+
+Using JShell, create a variable called `value` and initialize it with the value `8`. Apply various compound assignment operators on `value` and print its value after each operation.
+
+**Solution:**
+
+```
+jshell> int value = 8
+value ==> 8
+
+jshell> value += 4
+$1 ==> 12
+
+jshell> value
+value ==> 12
+
+jshell> value -= 2
+$2 ==> 10
+
+jshell> value
+value ==> 10
+
+jshell> value *= 3
+$3 ==> 30
+
+jshell> value
+value ==> 30
+
+jshell> value /= 2
+$4 ==> 15
+
+jshell> value
+value ==> 15
+
+jshell> value %= 4
+$5 ==> 3
+
+jshell> value
+value ==> 3
+```
+
+
+
+
+### Step 22: Some `JShell` Usage Tips
+
+#### Exercise 1
+
+#### Problem
+
+Write a short program in JShell to calculate the area of a rectangle using the given length and width. Use JShell internal variables to store the results of your calculations. Finally, print the area of the rectangle.
+
+##### Solution
+
+1. Open JShell by typing `jshell` in your command prompt or terminal.
+2. Enter the following commands one by one in JShell:
+
+```
+int length = 10
+int width = 5
+int area = length * width
+System.out.println("Area of the rectangle: " + area)
+```
+
+3. You should see the output: `Area of the rectangle: 50`
+
+#### Exercise 2
+
+#### Problem
+
+Create a simple program in JShell to add two numbers and print their sum. Then, use JShell shortcuts to modify the previous input and calculate the sum of two different numbers.
+
+##### Solution
+
+1. Open JShell by typing `jshell` in your command prompt or terminal.
+2. Enter the following commands one by one in JShell:
+
+```
+int num1 = 3
+int num2 = 7
+int sum = num1 + num2
+System.out.println("Sum of the numbers: " + sum)
+```
+
+3. You should see the output: `Sum of the numbers: 10`
+4. Now, use the up-arrow key to navigate back to the `int num1 = 3` line and modify the value of `num1`:
+
+```
+int num1 = 5
+```
+
+5. Use the up-arrow key again to navigate back to the `int num2 = 7` line and modify the value of `num2`:
+
+```
+int num2 = 9
+```
+
+6. Finally, use the up-arrow key to navigate back to the `int sum = num1 + num2` and `System.out.println("Sum of the numbers: " + sum)` lines to re-execute them.
+7. You should now see the output: `Sum of the numbers: 14`
+
+
+
+
+### Step 23: Introducing Conditionals - the if
+
+
+
+#### Exercise 1: Check if a Number is Even
+
+**Problem**: Write a Java program using JShell that checks if a given number is even or odd. If the number is even, print "The number is even", otherwise print "The number is odd".
+
+**Solution**:
+
+```
+int number = 10;
+
+if (number % 2 == 0) {
+ System.out.println("The number is even");
+} else {
+ System.out.println("The number is odd");
+}
+```
+
+#### Exercise 2: Compare Two Numbers
+
+**Problem**: Write a Java program using JShell that takes two integer values as input and compares them. If the first number is greater than the second number, print "The first number is greater than the second number".
+
+**Solution**:
+
+```
+int num1 = 15;
+int num2 = 7;
+
+if (num1 > num2) {
+ System.out.println("The first number is greater than the second number");
+```
+
+
+
+
+### Step 24: Programming Exercise PE-04
+
+#### Exercise 1: JShell Arithmetic Comparison
+
+In this exercise, you will use JShell to create four integer variables a, b, c, and d, and compare the sums of a + b and c + d.
+
+#### Problem
+
+1. Start a JShell session.
+2. Declare four integer variables a, b, c, and d, and initialize them with any integer values.
+3. Write an if statement to print if the sum of a and b is greater than the sum of c and d.
+
+##### Solution
+
+```
+`// Start JShell
+$ jshell
+
+// Declare and initialize four integer variables
+jshell> int a = 10;
+a ==> 10
+
+jshell> int b = 20;
+b ==> 20
+
+jshell> int c = 5;
+c ==> 5
+
+jshell> int d = 15;
+d ==> 15
+
+// Write an if statement to compare the sums and print the result
+jshell> if (a + b > c + d) {
+ ...> System.out.println("The sum of a and b is greater than the sum of c and d.");
+ ...> }
+The sum of a and b is greater than the sum of c and d.
+```
+
+#### Exercise 2: JShell Triangle Angle Check
+
+In this exercise, you will use JShell to check if three given angles can form a triangle.
+
+#### Problem
+
+1. Start a JShell session if you haven't already.
+2. Declare three integer variables angle1, angle2, and angle3, and initialize them with any integer values.
+3. Write an if statement to check if the sum of angle1, angle2, and angle3 equals 180 degrees. If so, print that the angles can form a triangle; otherwise, print that the angles cannot form a triangle.
+
+##### Solution
+
+```
+// Start JShell if not already open
+$ jshell
+
+// Declare and initialize three integer variables for the angles
+jshell> int angle1 = 60;
+angle1 ==> 60
+
+jshell> int angle2 = 60;
+angle2 ==> 60
+
+jshell> int angle3 = 60;
+angle3 ==> 60
+
+// Write an if statement to check if the angles can form a triangle
+jshell> if (angle1 + angle2 + angle3 == 180) {
+ ...> System.out.println("The angles can form a triangle.");
+ ...> } else {
+ ...> System.out.println("The angles cannot form a triangle.");
+ ...> }
+The angles can form a triangle.
```
\ No newline at end of file
From 44d9a6ac0beac059c6a966df63128c0983fdccc7 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sat, 25 Mar 2023 10:26:15 +0530
Subject: [PATCH 045/178] .
---
CODECHALLENGE.md | 44 +++++++++++++++++++++++++++++++++++++++++++-
1 file changed, 43 insertions(+), 1 deletion(-)
diff --git a/CODECHALLENGE.md b/CODECHALLENGE.md
index f114fdae..af842374 100644
--- a/CODECHALLENGE.md
+++ b/CODECHALLENGE.md
@@ -1323,4 +1323,46 @@ jshell> if (angle1 + angle2 + angle3 == 180) {
...> System.out.println("The angles cannot form a triangle.");
...> }
The angles can form a triangle.
-```
\ No newline at end of file
+```
+
+
+
+
+
+
+### Step 26: if Statement again
+#### Exercise 1
+
+**Problem Statement:**
+
+Create a JShell script that assigns a value to an integer `x` and checks if `x` is equal to 10. If `x` is equal to 10, print "x is equal to 10" and "x is even". If `x` is not equal to 10, print "x is not equal to 10".
+
+**Solution:**
+
+```
+jshell> int x = 10;
+jshell> if (x == 10) {
+ ...> System.out.println("x is equal to 10");
+ ...> System.out.println("x is even");
+ ...> } else {
+ ...> System.out.println("x is not equal to 10");
+ ...> }
+ ```
+
+#### Exercise 2
+
+**Problem Statement:**
+
+Create a JShell script that assigns a value to an integer `y` and checks if `y` is greater than 15. If `y` is greater than 15, print "y is greater than 15" and "y is a large number". If `y` is not greater than 15, print "y is not greater than 15".
+
+**Solution:**
+
+```
+jshell> int y = 20;
+jshell> if (y > 15) {
+ ...> System.out.println("y is greater than 15");
+ ...> System.out.println("y is a large number");
+ ...> } else {
+ ...> System.out.println("y is not greater than 15");
+ ...> }
+ ```
\ No newline at end of file
From da24e646637a0a5e0872b2a32e3e353bfa5078b0 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sat, 25 Mar 2023 10:30:37 +0530
Subject: [PATCH 046/178] .
---
CODECHALLENGE.md | 53 +++++++++++++++++++++++++++++++++++++++++++++++-
1 file changed, 52 insertions(+), 1 deletion(-)
diff --git a/CODECHALLENGE.md b/CODECHALLENGE.md
index af842374..f93db36c 100644
--- a/CODECHALLENGE.md
+++ b/CODECHALLENGE.md
@@ -1365,4 +1365,55 @@ jshell> if (y > 15) {
...> } else {
...> System.out.println("y is not greater than 15");
...> }
- ```
\ No newline at end of file
+```
+
+
+### Step 27: Introducing Loops: The `for` Statement
+
+#### Exercise 1: Printing Even Numbers
+
+**Problem:** Write a Java code snippet in JShell that uses a `for` loop to print the even numbers from 2 to 20.
+
+**Solution:**
+
+```
+jshell> for (int i = 2; i <= 20; i += 2) {
+...> System.out.println(i);
+...> }
+```
+
+**Output:**
+
+```
+2
+4
+6
+8
+10
+12
+14
+16
+18
+20
+```
+
+#### Exercise 2: Sum of Natural Numbers
+
+**Problem:** Write a Java code snippet in JShell that uses a `for` loop to find the sum of the first 15 natural numbers.
+
+**Solution:**
+
+```
+jshell> int sum = 0;
+sum ==> 0
+jshell> for (int i = 1; i <= 15; i++) {
+...> sum += i;
+...> }
+jshell> System.out.println("Sum of first 15 natural numbers: " + sum);
+```
+
+**Output:**
+
+```
+Sum of first 15 natural numbers: 120
+```
From 3d94e7fef24451808d0978ff9e960f50d56ad213 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sat, 25 Mar 2023 10:34:10 +0530
Subject: [PATCH 047/178] .
---
CODECHALLENGE.md | 55 ++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 55 insertions(+)
diff --git a/CODECHALLENGE.md b/CODECHALLENGE.md
index f93db36c..5e90d469 100644
--- a/CODECHALLENGE.md
+++ b/CODECHALLENGE.md
@@ -1417,3 +1417,58 @@ jshell> System.out.println("Sum of first 15 natural numbers: " + sum);
```
Sum of first 15 natural numbers: 120
```
+
+
+
+### Step 28: Programming Exercise PE-05
+
+
+#### Exercise 1: Calculate the sum of the first 10 even numbers using JShell
+
+**Problem:**
+
+Using JShell, write a program to calculate the sum of the first 10 even numbers.
+
+**Solution:**
+
+Open JShell and follow the instructions below.
+
+```
+// Declare a variable to store the sum
+int sum = 0;
+
+// Iterate through the first 10 even numbers
+for (int i = 2; i <= 20; i += 2) {
+ // Add the current even number to the sum
+ sum += i;
+}
+
+// Print the sum
+System.out.println("The sum of the first 10 even numbers is: " + sum);
+```
+
+#### Exercise 2: Calculate the factorial of a number using JShell
+
+**Problem:**
+
+Using JShell, write a program to calculate the factorial of a number (n). For this exercise, let n = 5.
+
+**Solution:**
+
+Open JShell and follow the instructions below.
+
+```
+// Declare a variable to store the factorial
+int factorial = 1;
+
+// Declare the number n
+int n = 5;
+
+// Calculate the factorial of n
+for (int i = 1; i <= n; i++) {
+ factorial *= i;
+}
+
+// Print the factorial
+System.out.println("The factorial of " + n + " is: " + factorial);
+```
From d4c096f6f22b9e3cf3de582c50daf7e0808dd023 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sat, 25 Mar 2023 10:37:26 +0530
Subject: [PATCH 048/178] .
---
CODECHALLENGE.md | 48 ++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 48 insertions(+)
diff --git a/CODECHALLENGE.md b/CODECHALLENGE.md
index 5e90d469..c0d4290e 100644
--- a/CODECHALLENGE.md
+++ b/CODECHALLENGE.md
@@ -1472,3 +1472,51 @@ for (int i = 1; i <= n; i++) {
// Print the factorial
System.out.println("The factorial of " + n + " is: " + factorial);
```
+
+
+### Step 30: Puzzling You With `for`
+
+#### Exercise 1
+
+**Problem:** Write a Java code snippet in JShell to find the sum of all even numbers between 1 and 10 (inclusive).
+
+**Solution:**
+
+```
+jshell> int sum = 0;
+sum ==> 0
+
+jshell> for (int i = 2; i <= 10; i += 2) {
+ ...> sum += i;
+ ...> }
+
+jshell> sum
+sum ==> 30
+```
+
+### Exercise 2
+
+**Problem:** Write a Java code snippet in JShell to print the multiplication table of 5.
+
+**Solution:**
+
+```
+jshell> for (int i = 1; i <= 10; i++) {
+ ...> System.out.println("5 * " + i + " = " + (5 * i));
+ ...> }
+ ```
+
+Output:
+
+```
+5 * 1 = 5
+5 * 2 = 10
+5 * 3 = 15
+5 * 4 = 20
+5 * 5 = 25
+5 * 6 = 30
+5 * 7 = 35
+5 * 8 = 40
+5 * 9 = 45
+5 * 10 = 50
+```
\ No newline at end of file
From 06cfcd77c015793bd062bd76816802c926121fe4 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sat, 25 Mar 2023 18:39:52 +0530
Subject: [PATCH 049/178] .
---
CODECHALLENGE.md | 166 ++++++++++++++++++++++-------------------------
1 file changed, 76 insertions(+), 90 deletions(-)
diff --git a/CODECHALLENGE.md b/CODECHALLENGE.md
index c0d4290e..f81e1009 100644
--- a/CODECHALLENGE.md
+++ b/CODECHALLENGE.md
@@ -1,145 +1,131 @@
## Java Code Challenge
-### Step 01: First Challenge : The Print-Multiplication-Table (PMT-Challenge)
+### Step 02: Introducing JShell
-#### Exercise 1: PMT Challenge Using For Loop
-
-Using JShell, write a program to display the multiplication table for 7, with entries from 1 to 10 using a for loop.
-
-###### Solution
-
-Launch JShell and enter the following commands:
-
-
-```
-for(int i = 1; i <= 10; i++) {
- System.out.println("7 * " + i + " = " + (7*i));
-}
-```
-
-Output:
-```
-7 * 1 = 7
-7 * 2 = 14
-7 * 3 = 21
-7 * 4 = 28
-7 * 5 = 35
-7 * 6 = 42
-7 * 7 = 49
-7 * 8 = 56
-7 * 9 = 63
-7 * 10 = 70
-```
+#### Exercise 1: Simple Calculation using JShell
-#### Exercise 2: PMT Challenge Using While Loop
+In this exercise, you will use JShell to perform a simple calculation.
-Using JShell, write a program to display the multiplication table for 3, with entries from 1 to 5 using a while loop.
+#### Problem
-###### Solution
+1. Launch JShell
+2. Type `3 + 4` and press enter
+3. Verify that the result is displayed as `7`
+4. Exit JShell using `/exit` command
-Launch JShell and enter the following commands:
+##### Solution
+1. Launch JShell
+2. Type `3 + 4` and press enter
```
-int i = 1;
-while(i <= 5) {
- System.out.println("3 * " + i + " = " + (3*i));
- i++;
-}
+jshell> 3 + 4
+$1 ==> 7
```
-Output:
-
+3. Verify that the result is displayed as `7`
+4. Exit JShell using `/exit` command
```
-3 * 1 = 3
-3 * 2 = 6
-3 * 3 = 9
-3 * 4 = 12
-3 * 5 = 15
+jshell> /exit
+| Goodbye
```
-### Step 02: Introducing JShell
+#### Exercise 2: Simple Calculation using JShell
+In this exercise, you will use JShell to perform a simple calculation.
-#### Exercise 1:
+#### Problem
-Create a JShell snippet that defines a variable `myNumber` with a value of 10, then use an expression to calculate and display the square of `myNumber`.
+1. Launch JShell
+2. Type `8 - 3` and press enter
+3. Verify that the result is displayed as `5`
+4. Exit JShell using `/exit` command
-##### Solution:
+##### Solution
-```
+1. Launch JShell
+2. Type `8 - 3` and press enter
-jshell> int myNumber = 10;
-myNumber ==> 10
- jshell> myNumber * myNumber
-$1 ==> 100
+```
+jshell> 8 - 3
+$1 ==> 5
```
-#### Exercise 2:
-
-Create a JShell snippet that defines a method called `isEven` that takes an integer argument `n` and returns a boolean value indicating whether `n` is even or not. Then, call the method with an integer value of your choice and display the result.
-
-##### Solution:
+3. Verify that the result is displayed as `5`
+4. Exit JShell using `/exit` command
```
+jshell> /exit
+| Goodbye
+```
-jshell> boolean isEven(int n) {
- ...> return n % 2 == 0;
- ...> }
-| created method isEven(int)
-
-jshell> isEven(7)
-$1 ==> false
-jshell> isEven(12)
-$2 ==> true
-```
+### Step 03: Welcome to Problem Solving
-### Step 03: Welcome to Problem Solving
+#### Exercise 1: Simple Multiplication using JShell
+In this exercise, you will use JShell to perform a simple multiplication.
-#### Java Coding Exercise 1
+#### Problem
-Using JShell, write a Java code snippet to calculate and print the result of multiplying 7 by 4.
+1. Launch JShell
+2. Type `7 * 4` and press enter
+3. Verify that the result is displayed as `28`
+4. Exit JShell using `/exit` command
##### Solution
+1. Launch JShell
+2. Type `7 * 4` and press enter
+
+```
+jshell> 7 * 4
+$1 ==> 28
```
-jshell> int result = 7 * 4;
-result ==> 28
+3. Verify that the result is displayed as `28`
+4. Exit JShell using `/exit` command
-jshell> System.out.println(result);
-28
+```
+jshell> /exit
+| Goodbye
```
-#### Java Coding Exercise 2
+#### Exercise 2: Simple Multiplication using JShell
-Using JShell, write a Java code snippet to print the multiplication table for 9, with entries from 1 to 5.
+In this exercise, you will use JShell to perform a simple multiplication.
-##### Solution
+#### Problem
-```
+1. Launch JShell
+2. Type `9 * 6` and press enter
+3. Verify that the result is displayed as `54`
+4. Exit JShell using `/exit` command
+
+##### Solution
+
+1. Launch JShell
+2. Type `9 * 6` and press enter
-jshell> for (int i = 1; i <= 5; i++) {
- ...> int result = 9 * i;
- ...> System.out.println("9 * " + i + " = " + result);
- ...> }
-9 * 1 = 9
-9 * 2 = 18
-9 * 3 = 27
-9 * 4 = 36
-9 * 5 = 45
```
+jshell> 9 * 6
+$1 ==> 54
+```
+
+3. Verify that the result is displayed as `54`
+4. Exit JShell using `/exit` command
+
+shellCopy code
-Note: The above solution uses a for loop to execute the code 5 times, once for each table entry, and prints the result of each calculation.
+`jshell> /exit
+| Goodbye`
From c3e87eb2e469ba08a74803920845cc5caa1f4b9c Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sat, 25 Mar 2023 18:45:37 +0530
Subject: [PATCH 050/178] .
---
CODECHALLENGE.md | 87 ++++++++++++++++++++++++++----------------------
1 file changed, 47 insertions(+), 40 deletions(-)
diff --git a/CODECHALLENGE.md b/CODECHALLENGE.md
index f81e1009..e8f1e739 100644
--- a/CODECHALLENGE.md
+++ b/CODECHALLENGE.md
@@ -122,67 +122,74 @@ $1 ==> 54
3. Verify that the result is displayed as `54`
4. Exit JShell using `/exit` command
-shellCopy code
-
-`jshell> /exit
-| Goodbye`
+```
+jshell> /exit
+| Goodbye
+```
### Step 04: Introducing Expressions
-#### Exercise 1:
-Write a Java program using JShell to calculate the area of a square with side length of 7 units. Use the appropriate Java operators and follow the steps below:
-1. Start JShell.
-2. Define a variable `sideLength` with a value of 7.
-3. Calculate the area of the square and store it in a variable called `area`.
-4. Print the value of `area`.
-5. Exit JShell.
+#### Exercise 1: Simple Division using JShell
-##### Solution:
+In this exercise, you will use JShell to perform a simple division.
-```
+#### Problem
+
+1. Launch JShell
+2. Type `10 / 2` and press enter
+3. Verify that the result is displayed as `5`
+4. Exit JShell using `/exit` command
-jshell> int sideLength = 7;
-sideLength ==> 7
- jshell> int area = sideLength * sideLength;
-area ==> 49
- jshell> System.out.println("Area of the square is: " + area);
-Area of the square is: 49
- jshell> /exit
- ```
+##### Solution
-#### Exercise 2:
-Write a Java program using JShell to calculate the volume of a rectangular prism with length, width, and height of 4, 5, and 6 units respectively. Use the appropriate Java operators and follow the steps below:
+1. Launch JShell
+2. Type `10 / 2` and press enter
-1. Start JShell.
-2. Define three variables `length`, `width`, and `height` with values of 4, 5, and 6 respectively.
-3. Calculate the volume of the rectangular prism and store it in a variable called `volume`.
-4. Print the value of `volume`.
-5. Exit JShell.
+```
+jshell> 10 / 2
+$1 ==> 5
+```
-##### Solution:
+3. Verify that the result is displayed as `5`
+4. Exit JShell using `/exit` command
```
-jshell> int length = 4;
-length ==> 4
+jshell> /exit
+| Goodbye
+```
+
+#### Exercise 2: Simple Modulus using JShell
-jshell> int width = 5;
-width ==> 5
+In this exercise, you will use JShell to perform a simple modulus.
-jshell> int height = 6;
-height ==> 6
+#### Problem
-jshell> int volume = length * width * height;
-volume ==> 120
+1. Launch JShell
+2. Type `25 % 7` and press enter
+3. Verify that the result is displayed as `4`
+4. Exit JShell using `/exit` command
-jshell> System.out.println("Volume of the rectangular prism is: " + volume);
-Volume of the rectangular prism is: 120
+##### Solution
-jshell> /exit
+1. Launch JShell
+2. Type `25 % 7` and press enter
+
+```
+jshell> 25 % 7
+$1 ==> 4
+```
+
+3. Verify that the result is displayed as `4`
+4. Exit JShell using `/exit` command
+```
+jshell> /exit
+| Goodbye
+```
```
### Step 05: Programming Exercise PE-1 (With Solutions)
From d3881484714742f9df521db40f4111d7f42db2d8 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sat, 25 Mar 2023 18:46:08 +0530
Subject: [PATCH 051/178] .
---
CODECHALLENGE.md | 1 -
1 file changed, 1 deletion(-)
diff --git a/CODECHALLENGE.md b/CODECHALLENGE.md
index e8f1e739..5efd533c 100644
--- a/CODECHALLENGE.md
+++ b/CODECHALLENGE.md
@@ -190,7 +190,6 @@ $1 ==> 4
jshell> /exit
| Goodbye
```
-```
### Step 05: Programming Exercise PE-1 (With Solutions)
From d16dc28fb2a62633d10546b1c337fce49f25a059 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sat, 25 Mar 2023 18:52:29 +0530
Subject: [PATCH 052/178] .
---
CODECHALLENGE.md | 63 +++++++++++++++++++++++++++++++++++-------------
1 file changed, 46 insertions(+), 17 deletions(-)
diff --git a/CODECHALLENGE.md b/CODECHALLENGE.md
index 5efd533c..db228fc9 100644
--- a/CODECHALLENGE.md
+++ b/CODECHALLENGE.md
@@ -194,35 +194,64 @@ jshell> /exit
### Step 05: Programming Exercise PE-1 (With Solutions)
-#### Exercise 1
+#### Exercise 1: Simple Expression using JShell
-Write a JShell command to calculate the average of three integers: 10, 20, and 30.
+In this exercise, you will use JShell to calculate an expression.
-##### Solution:
+#### Problem
+
+1. Launch JShell
+2. Write an expression to calculate the area of a rectangle with length 10 and width 5
+3. Verify that the result is displayed as `50`
+4. Exit JShell using `/exit` command
+
+##### Solution
+
+1. Launch JShell
+2. Write an expression to calculate the area of a rectangle with length 10 and width 5: `10 * 5`
```
-jshell> int num1 = 10;
-jshell> int num2 = 20;
-jshell> int num3 = 30;
-jshell> int average = (num1 + num2 + num3) / 3;
-jshell> average
-average ==> 20
+jshell> 10 * 5
+$1 ==> 50
```
-#### Exercise 2
+3. Verify that the result is displayed as `50`
+4. Exit JShell using `/exit` command
-Write a JShell command to convert a temperature of 75 degrees Fahrenheit to Celsius.
+```
+jshell> /exit
+| Goodbye
+```
-##### Solution:
+
+#### Exercise 2: Celsius to Fahrenheit Conversion using JShell
+
+In this exercise, you will use JShell to convert a temperature in Celsius to Fahrenheit.
+
+#### Problem
+
+1. Launch JShell
+2. Write an expression to convert 30 degrees Celsius to Fahrenheit
+3. Verify that the result is displayed as `86`
+4. Exit JShell using `/exit` command
+
+##### Solution
+
+1. Launch JShell
+2. Write an expression to convert 30 degrees Celsius to Fahrenheit: `(30 * 9/5) + 32`
```
-jshell> double fahrenheit = 75.0;
-jshell> double celsius = (fahrenheit - 32) * 5 / 9;
-jshell> celsius
-celsius ==> 23.88888888888889
+jshell> (30 * 9/5) + 32
+$1 ==> 86
```
-Note: The formula to convert Fahrenheit to Celsius is: (°F - 32) * 5/9 = °C
+3. Verify that the result is displayed as `86`
+4. Exit JShell using `/exit` command
+
+```
+jshell> /exit
+| Goodbye
+```
### Step 06: Operators
From 8c8553a698a4adc64057dd9e6c07ca2f2a89c424 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sat, 25 Mar 2023 19:01:57 +0530
Subject: [PATCH 053/178] .
---
CODECHALLENGE.md | 79 +++++++++++++++++++++++++++++++-----------------
1 file changed, 51 insertions(+), 28 deletions(-)
diff --git a/CODECHALLENGE.md b/CODECHALLENGE.md
index db228fc9..148fd911 100644
--- a/CODECHALLENGE.md
+++ b/CODECHALLENGE.md
@@ -256,51 +256,74 @@ jshell> /exit
### Step 06: Operators
-#### Exercise 1: Operator Practice
-Write a Java program using JShell that takes two integers as input and prints their sum, difference, product, and quotient. Use appropriate operators to perform these operations.
+#### Exercise 11: Simple Expression using JShell
-##### Solution
+In this exercise, you will use JShell to calculate some expressions.
+#### Problem
+
+1. Launch JShell
+2. Write an expression to calculate the result of `11.0 / 2.0`
+3. Verify that the result is displayed as `5.5`
+4. Write an expression to calculate the result of `6 + 6 * 10`
+5. Verify that the result is displayed as `66`
+6. Exit JShell using `/exit` command
+
+##### Solution
+
+1. Launch JShell
+2. Write an expression to calculate the result of `11.0 / 2.0`: `11.0 / 2.0`
+
+```
+jshell> 11.0 / 2.0
+$1 ==> 5.5
```
-// Use JShell to declare variables and perform arithmetic operations
-int num1 = 10;
-int num2 = 5;
-// Calculate and print sum, difference, product, and quotient
-System.out.println("Sum: " + (num1 + num2));
-System.out.println("Difference: " + (num1 - num2));
-System.out.println("Product: " + (num1 * num2));
-System.out.println("Quotient: " + (num1 / num2));
+3. Verify that the result is displayed as `5.5`
+4. Write an expression to calculate the result of `6 + 6 * 10`: `6 + 6 * 10`
+
+```
+jshell> 6 + 6 * 10
+$2 ==> 66
```
-#### Exercise 2: Operator Precedence
+5. Verify that the result is displayed as `66`
+6. Exit JShell using `/exit` command
-Write a Java program using JShell that takes three integers as input and calculates the value of the following expression:
+```
+jshell> /exit
+| Goodbye
+```
-`(num1 + num2) * num3 / 2`
+#### Exercise 12: Simple Expression using JShell
-##### Solution
+In this exercise, you will use JShell to calculate an expression.
-```
-// Use JShell to declare variables and perform arithmetic operations
-int num1 = 5;
-int num2 = 10;
-int num3 = 2;
+#### Problem
+
+1. Launch JShell
+2. Write an expression to calculate the result of `(10 - 3) * 4`
+3. Verify that the result is displayed as `28`
+4. Exit JShell using `/exit` command
-// Calculate the value of the expression
-int result = (num1 + num2) * num3 / 2;
+##### Solution
-// Print the result
-System.out.println("Result: " + result);
+1. Launch JShell
+2. Write an expression to calculate the result of `(10 - 3) * 4`: `(10 - 3) * 4`
+```
+jshell> (10 - 3) * 4
+$1 ==> 28
```
-Explanation:
+3. Verify that the result is displayed as `28`
+4. Exit JShell using `/exit` command
-- First, the expressions inside the parentheses `(num1 + num2)` are evaluated, resulting in the sum of `num1` and `num2`.
-- Next, the result of the previous step is multiplied by `num3`, giving `(num1 + num2) * num3`.
-- Finally, the result of the previous step is divided by `2`, resulting in the final value of the expression.
+```
+jshell> /exit
+| Goodbye
+```
### Step 07: Introducing Console Output
From 720ec45d95c104eac7e093640b997b100604a006 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sat, 25 Mar 2023 19:42:42 +0530
Subject: [PATCH 054/178] .
---
CODECHALLENGE.md | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/CODECHALLENGE.md b/CODECHALLENGE.md
index 148fd911..4f20be2b 100644
--- a/CODECHALLENGE.md
+++ b/CODECHALLENGE.md
@@ -257,7 +257,7 @@ jshell> /exit
### Step 06: Operators
-#### Exercise 11: Simple Expression using JShell
+#### Exercise 1: Simple Expression using JShell
In this exercise, you will use JShell to calculate some expressions.
@@ -296,7 +296,7 @@ jshell> /exit
| Goodbye
```
-#### Exercise 12: Simple Expression using JShell
+#### Exercise 2: Simple Expression using JShell
In this exercise, you will use JShell to calculate an expression.
From 5374506435d7954ab61af8978ffd8d5fd6a9b693 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sat, 25 Mar 2023 21:50:20 +0530
Subject: [PATCH 055/178] .
---
CODECHALLENGE.md | 182 +++++++++++++++++++++++++++--------------------
1 file changed, 103 insertions(+), 79 deletions(-)
diff --git a/CODECHALLENGE.md b/CODECHALLENGE.md
index 4f20be2b..6de802c0 100644
--- a/CODECHALLENGE.md
+++ b/CODECHALLENGE.md
@@ -329,140 +329,164 @@ jshell> /exit
### Step 07: Introducing Console Output
-#### Exercise 1:
-Challenge: Write a Java program that takes a user's name as input and greets the user by printing "Hello, [name]!" to the console using JShell.
+#### Exercise 1: Simple Arithmetic with Printing using JShell 1
-##### Solution:
+1. Launch JShell
+2. Write an expression to calculate the result of `7 * 2`
+3. Print the result using `System.out.println()`
+4. Write an expression to calculate the result of `7 / 2`
+5. Print the result using `System.out.println()`
+6. Exit JShell using `/exit` command
-```
-jshell> String name = "Alice";
-name ==> "Alice"
+##### Solution 1
-jshell> System.out.println("Hello, " + name + "!");
-Hello, Alice!
-```
-
-#### Exercise 2:
+1. Launch JShell
+2. Write an expression to calculate the result of `7 * 2`: `7 * 2`
+3. Print the result using `System.out.println()`
-Challenge: Write a Java program that takes two numbers as input and prints their product in the format "[num1] * [num2] = [product]" to the console using JShell.
+```
+jshell> System.out.println(7 * 2);
+14
+```
-##### Solution:
+4. Write an expression to calculate the result of `7 / 2`: `7 / 2`
+5. Print the result using `System.out.println()`
```
-jshell> int num1 = 5;
-num1 ==> 5
-
-jshell> int num2 = 3;
-num2 ==> 3
+jshell> System.out.println(7 / 2);
+3
+```
-jshell> int product = num1 * num2;
-product ==> 15
+6. Exit JShell using `/exit` command
-jshell> System.out.println(num1 + " * " + num2 + " = " + product);
-5 * 3 = 15
+```
+jshell> /exit
+| Goodbye
```
+#### Exercise 2: Simple Arithmetic with Printing using JShell 2
+1. Launch JShell
+2. Write an expression to calculate the result of `7 + 4`
+3. Print the result using `System.out.println()`
+4. Write an expression to calculate the result of `7 - 2`
+5. Print the result using `System.out.println()`
+6. Exit JShell using `/exit` command
+##### Solution 2
-### Step 08: Programming Exercise PE-02
-
+1. Launch JShell
+2. Write an expression to calculate the result of `7 + 4`: `7 + 4`
+3. Print the result using `System.out.println()`
+```
+jshell> System.out.println(7 + 4);
+11
+```
-#### Exercise 1
+4. Write an expression to calculate the result of `7 - 2`: `7 - 2`
+5. Print the result using `System.out.println()`
-Using JShell, write a program that prints out the message "Hello World" onto the console.
+```
+`jshell> System.out.println(7 - 2);
+5
+```
-##### Solution
+6. Exit JShell using `/exit` command
```
-System.out.println("Hello World");
+jshell> /exit
+| Goodbye
```
-#### Syntax Revision
-```
-//Numeric and string literals
-System.out.println("Hello World");
-//Expressions
-//There are no expressions in this code.
+### Step 08: Programming Exercise PE-02
+### Step 09: Solutions to PE-02
-//Operators
-//There are no operators in this code.
-//Operands
-//There are no operands in this code.
-//Method calls
-System.out.println();
-```
+#### Exercise 1: Simple Arithmetic with Printing using JShell 1
-#### Exercise 2
+1. Launch JShell
+2. Write an expression to calculate the result of `7 * 5`
+3. Print the expression and result in the format `7 * 5 = 35`
+4. Write an expression to calculate the result of `12 - 3 / 2 + 4 * 8`
+5. Print the expression and result in the format `12 - 3 / 2 + 4 * 8 = 41`
+6. Exit JShell using `/exit` command
-Using JShell, write a program that prints out the result of the expression 5 * 3, both as an expression and as the calculated value.
+##### Solution 1
-##### Solution
+1. Launch JShell
+2. Write an expression to calculate the result of `7 * 5`: `7 * 5`
+3. Print the expression and result in the format `7 * 5 = 35` using `System.out.println()`
```
-//Print the expression
-System.out.println("5 * 3");
+jshell> int result = 7 * 5;
+result ==> 35
-//Print the calculated value
-System.out.println(5 * 3);
+jshell> System.out.println("7 * 5 = " + result);
+7 * 5 = 35
```
-#### Syntax Revision
+4. Write an expression to calculate the result of `12 - 3 / 2 + 4 * 8`: `12 - 3 / 2 + 4 * 8`
+5. Print the expression and result in the format `12 - 3 / 2 + 4 * 8 = 41` using `System.out.println()`
```
-//Numeric and string literals
-System.out.println("5 * 3");
+jshell> result = 12 - 3 / 2 + 4 * 8;
+result ==> 41
-//Expressions
-System.out.println(5 * 3);
-
-//Operators
-//The * operator is used to multiply 5 and 3.
+jshell> System.out.println("12 - 3 / 2 + 4 * 8 = " + result);
+12 - 3 / 2 + 4 * 8 = 41
+```
-//Operands
-//The operands in this code are 5 and 3.
+6. Exit JShell using `/exit` command
-//Method calls
-System.out.println();
+```
+jshell> /exit
+| Goodbye
```
+#### Exercise 2: Simple Arithmetic with Printing using JShell 2
+1. Launch JShell
+2. Write an expression to calculate the result of `25 % 7`
+3. Print the expression and result in the format `25 % 7 = 4`
+4. Write an expression to calculate the result of `(6 + 8) / 2 * 3`
+5. Print the expression and result in the format `(6 + 8) / 2 * 3 = 18`
+6. Exit JShell using `/exit` command
-### Step 09: Solutions to PE-02
+##### Solution 2
-#### Exercise 1
+1. Launch JShell
+2. Write an expression to calculate the result of `25 % 7`: `25 % 7`
+3. Print the expression and result in the format `25 % 7 = 4` using `System.out.println()`
-Create a program in JShell that displays the sum of 2 and 3.
+```
+jshell> int result = 25 % 7;
+result ==> 4
-**Solution:**
+jshell> System.out.println("25 % 7 = " + result);
+25 % 7 = 4
+```
+4. Write an expression to calculate the result of `(6 + 8) / 2 * 3`: `(6 + 8) / 2 * 3`
+5. Print the expression and result in the format `(6 + 8) / 2 * 3 = 18` using `System.out.println()`
```
-jshell> int sum = 2 + 3;
-sum ==> 5
-jshell> System.out.println("The sum of 2 and 3 is: " + sum);
-The sum of 2 and 3 is: 5
-```
-
-#### Exercise 2
+jshell> result = (6 + 8) / 2 * 3;
+result ==> 18
-Create a program in JShell that converts a temperature from Celsius to Fahrenheit. The formula for converting Celsius to Fahrenheit is F = (C * 1.8) + 32.
+jshell> System.out.println("(6 + 8) / 2 * 3 = " + result);
+(6 + 8) / 2 * 3 = 18
+```
-**Solution:**
+6. Exit JShell using `/exit` command
```
-jshell> double celsius = 20.0;
-celsius ==> 20.0
-jshell> double fahrenheit = (celsius * 1.8) + 32;
-fahrenheit ==> 68.0
-jshell> System.out.println(celsius + " degrees Celsius is equal to " + fahrenheit + " degrees Fahrenheit.");
-20.0 degrees Celsius is equal to 68.0 degrees Fahrenheit.
+jshell> /exit
+| Goodbye
```
From 60ccc327fbb61e2cb6ebc9b40ada1afda8c12463 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sat, 25 Mar 2023 21:56:41 +0530
Subject: [PATCH 056/178] .
---
CODECHALLENGE.md | 63 ++++++++++++------------------------------------
1 file changed, 15 insertions(+), 48 deletions(-)
diff --git a/CODECHALLENGE.md b/CODECHALLENGE.md
index 6de802c0..e32a7bdd 100644
--- a/CODECHALLENGE.md
+++ b/CODECHALLENGE.md
@@ -407,41 +407,24 @@ jshell> /exit
+
#### Exercise 1: Simple Arithmetic with Printing using JShell 1
1. Launch JShell
-2. Write an expression to calculate the result of `7 * 5`
-3. Print the expression and result in the format `7 * 5 = 35`
-4. Write an expression to calculate the result of `12 - 3 / 2 + 4 * 8`
-5. Print the expression and result in the format `12 - 3 / 2 + 4 * 8 = 41`
-6. Exit JShell using `/exit` command
+2. Write an expression to print "Welcome to Java 9!" using `System.out.println()`
+3. Exit JShell using `/exit` command
##### Solution 1
1. Launch JShell
-2. Write an expression to calculate the result of `7 * 5`: `7 * 5`
-3. Print the expression and result in the format `7 * 5 = 35` using `System.out.println()`
+2. Write an expression to print "Welcome to Java 9!" using `System.out.println()`
```
-jshell> int result = 7 * 5;
-result ==> 35
-
-jshell> System.out.println("7 * 5 = " + result);
-7 * 5 = 35
+jshell> System.out.println("Welcome to Java 9!");
+Welcome to Java 9!
```
-4. Write an expression to calculate the result of `12 - 3 / 2 + 4 * 8`: `12 - 3 / 2 + 4 * 8`
-5. Print the expression and result in the format `12 - 3 / 2 + 4 * 8 = 41` using `System.out.println()`
-
-```
-jshell> result = 12 - 3 / 2 + 4 * 8;
-result ==> 41
-
-jshell> System.out.println("12 - 3 / 2 + 4 * 8 = " + result);
-12 - 3 / 2 + 4 * 8 = 41
-```
-
-6. Exit JShell using `/exit` command
+3. Exit JShell using `/exit` command
```
jshell> /exit
@@ -451,38 +434,22 @@ jshell> /exit
#### Exercise 2: Simple Arithmetic with Printing using JShell 2
1. Launch JShell
-2. Write an expression to calculate the result of `25 % 7`
-3. Print the expression and result in the format `25 % 7 = 4`
-4. Write an expression to calculate the result of `(6 + 8) / 2 * 3`
-5. Print the expression and result in the format `(6 + 8) / 2 * 3 = 18`
-6. Exit JShell using `/exit` command
+2. Write an expression to calculate the result of `20 % 3 + 5 - 2 * 4`
+3. Print the result using `System.out.println()`
+4. Exit JShell using `/exit` command
##### Solution 2
1. Launch JShell
-2. Write an expression to calculate the result of `25 % 7`: `25 % 7`
-3. Print the expression and result in the format `25 % 7 = 4` using `System.out.println()`
-
-```
-jshell> int result = 25 % 7;
-result ==> 4
-
-jshell> System.out.println("25 % 7 = " + result);
-25 % 7 = 4
-```
-
-4. Write an expression to calculate the result of `(6 + 8) / 2 * 3`: `(6 + 8) / 2 * 3`
-5. Print the expression and result in the format `(6 + 8) / 2 * 3 = 18` using `System.out.println()`
+2. Write an expression to calculate the result of `20 % 3 + 5 - 2 * 4`: `20 % 3 + 5 - 2 * 4`
+3. Print the result using `System.out.println()`
```
-jshell> result = (6 + 8) / 2 * 3;
-result ==> 18
-
-jshell> System.out.println("(6 + 8) / 2 * 3 = " + result);
-(6 + 8) / 2 * 3 = 18
+jshell> System.out.println(20 % 3 + 5 - 2 * 4);
+1
```
-6. Exit JShell using `/exit` command
+4. Exit JShell using `/exit` command
```
jshell> /exit
From 9c96c613f87f66426bb5adf3503d8e8ae7d01467 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sat, 25 Mar 2023 22:05:13 +0530
Subject: [PATCH 057/178] .
---
CODECHALLENGE.md | 71 ++++++++++++++++++++++++++++--------------------
1 file changed, 41 insertions(+), 30 deletions(-)
diff --git a/CODECHALLENGE.md b/CODECHALLENGE.md
index e32a7bdd..357bde70 100644
--- a/CODECHALLENGE.md
+++ b/CODECHALLENGE.md
@@ -459,59 +459,70 @@ jshell> /exit
### Step 10: Whitespace, Case sensitiveness and Escape Characters
-#### Exercise 1: Whitespace Counter
-
-Write a program that takes a string input and counts the number of whitespace characters in it. Use JShell to test your program with the following inputs:
-
-Input 1:
+#### Exercise 1: Simple Arithmetic with Printing using JShell 1
-`"The quick brown fox jumps over the lazy dog."`
+1. Launch JShell
+2. Write an expression to print the string "hello, world!" in all lowercase using `System.out.println()`
+3. Exit JShell using `/exit` command
-Expected Output 1:
+##### Solution 1
-`8`
+1. Launch JShell
+2. Write an expression to print the string "hello, world!" in all lowercase using `System.out.println()`
-Input 2:
+```
+jshell> System.out.println("hello, world!");
+hello, world!
+```
-`"Java Programming is Fun!"`
+3. Exit JShell using `/exit` command
-Expected Output 2:
+```
+jshell> /exit
+| Goodbye
+```
-`6`
+#### Exercise 2: Simple Arithmetic with Printing using JShell 2
-##### Solution:
+1. Launch JShell
+2. Write an expression to print the string "Hi there!" using `System.out.println()`
+3. Write an expression to print the string "Good\tmorning" using `System.out.println()`
+4. Write an expression to print the string "See you\ntomorrow!" using `System.out.println()`
+5. Exit JShell using `/exit` command
+### Solution 2
+1. Launch JShell
+2. Write an expression to print the string "Hi there!" using `System.out.println()`
```
-int whitespaceCount = 0;
-String input = "The quick brown fox jumps over the lazy dog.";
-for (int i = 0; i < input.length(); i++) {
- if (Character.isWhitespace(input.charAt(i))) {
- whitespaceCount++;
- }
-}
-System.out.println(whitespaceCount);
+jshell> System.out.println("Hi there!");
+Hi there!
```
-#### Exercise 2: Escape Sequence Example
+3. Write an expression to print the string "Good\tmorning" using `System.out.println()`
-Write a program that uses escape sequences to print the following message exactly as shown below:
-
-
-`Java is a "programming" language.`
+```
+jshell> System.out.println("Good\tmorning");
+Good morning
+```
-Use JShell to test your program.
+4. Write an expression to print the string "See you\ntomorrow!" using `System.out.println()`
-##### Solution:
+```
+jshell> System.out.println("See you\ntomorrow!");
+See you
+tomorrow!
+```
+5. Exit JShell using `/exit` command
```
-System.out.println("Java is a \"programming\" language.");
+jshell> /exit
+| Goodbye
```
-
### Step 11: More On Method Calls
From 851991c47a414ea4bf36d8d21a89e4bb99ecc705 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sat, 25 Mar 2023 22:13:36 +0530
Subject: [PATCH 058/178] .
---
CODECHALLENGE.md | 67 +++++++++++++++++++++++++-----------------------
1 file changed, 35 insertions(+), 32 deletions(-)
diff --git a/CODECHALLENGE.md b/CODECHALLENGE.md
index 357bde70..67b67be9 100644
--- a/CODECHALLENGE.md
+++ b/CODECHALLENGE.md
@@ -526,56 +526,59 @@ jshell> /exit
### Step 11: More On Method Calls
-#### Exercise 1: JShell Math Practice
-Create a program using JShell that does the following:
+#### Problem 1
-1. Generates a random integer between 1 and 10 inclusive using the Math.random() method.
-2. Prints out the random integer.
-3. Calculates the square root of the random integer using the Math.sqrt() method.
-4. Prints out the square root.
+1. Launch JShell
+2. Write an expression to generate and print a random number between 1 and 100 using `Math.random()` and `System.out.println()`
+3. Exit JShell using `/exit` command
-##### Solution:
+##### Solution 1
-```
-jshell> int randomNum = (int)(Math.random() * 10 + 1)
-randomNum ==> 6
+1. Launch JShell
+2. Write an expression to generate and print a random number between 1 and 100 using `Math.random()` and `System.out.println()`
-jshell> double sqrtNum = Math.sqrt(randomNum)
-sqrtNum ==> 2.449489742783178
+```
+jshell> System.out.println((int)(Math.random() * 100) + 1);
+87
+```
-jshell> System.out.println("Random integer: " + randomNum);
-Random integer: 6
+3. Exit JShell using `/exit` command
-jshell> System.out.println("Square root of random integer: " + sqrtNum);
-Square root of random integer: 2.449489742783178
+```
+jshell> /exit
+| Goodbye
```
-#### Exercise 2: Max of Three Numbers
+#### Problem 2
-Create a program using JShell that finds the maximum of three numbers using the Math.max() method.
+1. Launch JShell
+2. Write an expression to print the minimum value between 100 and 199 using `Math.min()` and `System.out.println()`
+3. Write an expression to print the maximum value between 299 and 555 using `Math.max()` and `System.out.println()`
+4. Exit JShell using `/exit` command
-1. Declare three integer variables and assign them values.
-2. Call the Math.max() method with the three variables as parameters.
-3. Print out the result.
+##### Solution 2
-##### Solution:
+1. Launch JShell
+2. Write an expression to print the minimum value between 100 and 199 using `Math.min()` and `System.out.println()`
```
-jshell> int num1 = 10;
-num1 ==> 10
+jshell> System.out.println(Math.min(100, 199));
+100
+```
-jshell> int num2 = 15;
-num2 ==> 15
+3. Write an expression to print the maximum value between 299 and 555 using `Math.max()` and `System.out.println()`
-jshell> int num3 = 8;
-num3 ==> 8
+```
+jshell> System.out.println(Math.max(299, 555));
+555
+```
-jshell> int maxNum = Math.max(Math.max(num1, num2), num3);
-maxNum ==> 15
+4. Exit JShell using `/exit` command
-jshell> System.out.println("Maximum of " + num1 + ", " + num2 + ", and " + num3 + " is: " + maxNum);
-Maximum of 10, 15, and 8 is: 15
+```
+jshell> /exit
+| Goodbye
```
From 92ad6d4fde477526e2d7455d3af338c7705b7d75 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sat, 25 Mar 2023 23:01:49 +0530
Subject: [PATCH 059/178] .
---
CODECHALLENGE.md | 80 ++++++++++++++++++++++++++++--------------------
1 file changed, 46 insertions(+), 34 deletions(-)
diff --git a/CODECHALLENGE.md b/CODECHALLENGE.md
index 67b67be9..643ede21 100644
--- a/CODECHALLENGE.md
+++ b/CODECHALLENGE.md
@@ -586,60 +586,72 @@ jshell> /exit
### Step 12: More Formatted Output
-#### Exercise 1:
-Create a Java program using JShell to print the following multiplication table on the console:
-1 * 1 = 1 1 * 2 = 2 1 * 3 = 3 ... 1 * 10 = 10
+#### Exercise 1: Simple Arithmetic with Formatted Output using JShell
-##### Solution 1:
+
+1. Launch JShell
+2. Write an expression to calculate the result of `7 * 5`
+3. Print the expression and result in the format `7 * 5 = 35` using `System.out.printf()`
+4. Write an expression to calculate the result of `12 - 3 / 2 + 4 * 8`
+5. Print the expression and result in the format `12 - 3 / 2 + 4 * 8 = 41` using `System.out.printf()`
+6. Exit JShell using `/exit` command
+
+##### Solution 1
+
+1. Launch JShell
+2. Write an expression to calculate the result of `7 * 5`: `7 * 5`
+3. Print the expression and result in the format `7 * 5 = 35` using `System.out.printf()`
```
-// Using JShell to print multiplication table for 1
-for (int i = 1; i <= 10; i++) {
- System.out.printf("1 * %d = %d%n", i, 1 * i);
-}
+jshell> System.out.printf("7 * 5 = %d%n", 7 * 5);
+7 * 5 = 35
```
-Output:
+
+4. Write an expression to calculate the result of `12 - 3 / 2 + 4 * 8`: `12 - 3 / 2 + 4 * 8`
+5. Print the expression and result in the format `12 - 3 / 2 + 4 * 8 = 41` using `System.out.printf()`
+
+```
+jshell> System.out.printf("12 - 3 / 2 + 4 * 8 = %d%n", 12 - 3 / 2 + 4 * 8);
+12 - 3 / 2 + 4 * 8 = 41
+```
+
+6. Exit JShell using `/exit` command
```
-1 * 1 = 1
-1 * 2 = 2
-1 * 3 = 3
-1 * 4 = 4
-1 * 5 = 5
-1 * 6 = 6
-1 * 7 = 7
-1 * 8 = 8
-1 * 9 = 9
-1 * 10 = 10
+jshell> /exit
+| Goodbye
```
-Explanation: The for loop iterates from 1 to 10, and for each iteration, it uses the printf method to print the multiplication table for 1. The `%d` format specifier is used to print the value of the loop variable `i`, and `%n` is used to print a newline character.
+#### Exercise 2: Simple Arithmetic with Formatted Output using JShell
-#### Exercise 2:
-Create a Java program using JShell to print the following output on the console:
+1. Launch JShell
+2. Write an expression to calculate the result of `25 % 7`
+3. Print the expression and result in the format `25 % 7 = 4` using `System.out.printf()`
+4. Write an expression to calculate the result of `(6 + 8) / 2 * 3`
+5. Print the expression and result in the format `(6 + 8) / 2 * 3 = 18` using `System.out.printf()`
+6. Exit JShell using `/exit` command
-3.5 + 2.8 + 1.9 = 8.2
+##### Solution 2
-##### Solution 2:
+1. Launch JShell
+2. Write an expression to calculate the result of `25 % 7`: `25 % 7`
+3. Print the expression and result in the format `25 % 7 = 4` using `System.out.printf()`
```
-// Using JShell to print the sum of three decimal numbers
-double a = 3.5;
-double b = 2.8;
-double c = 1.9;
-double sum = a + b + c;
-System.out.printf("%.1f + %.1f + %.1f = %.1f%n", a, b, c, sum);
+jshell> System.out.printf("25 %% 7 = %d%n", 25 % 7);
+25 % 7 = 4
```
-Output:
+4. Write an expression to calculate the result of `(6 + 8) / 2 * 3`: `(6 + 8) / 2 * 3`
+5. Print the expression and result in the format `(6 + 8) / 2 * 3 = 18` using `System.out.printf()`
```
-3.5 + 2.8 + 1.9 = 8.2
+jshell> System.out.printf("(6 + 8) / 2 * 3 = %d%n", (6 + 8) / 2 * 3);
+(6 + 8) / 2 * 3 = 18
```
-Explanation: The program declares three double variables `a`, `b`, and `c`, and initializes them with the values 3.5, 2.8, and 1.9 respectively. It then calculates the sum of these variables and stores it in the `sum` variable. Finally, it uses the printf method to print the output with one decimal point using the `%f` format specifier and the `%.1f` modifier. `%n` is used to print a newline character.
-
+6. Exit JShell using `/exit` command
### Step 13: Introducing Variables
From 9c241445673e8a650d788050204381c19328a9df Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sat, 25 Mar 2023 23:03:50 +0530
Subject: [PATCH 060/178] .
---
CODECHALLENGE.md | 8 ++------
1 file changed, 2 insertions(+), 6 deletions(-)
diff --git a/CODECHALLENGE.md b/CODECHALLENGE.md
index 643ede21..c756949d 100644
--- a/CODECHALLENGE.md
+++ b/CODECHALLENGE.md
@@ -707,7 +707,7 @@ In this exercise, you will use JShell to create a multiplication table using var
2. Define an integer variable named "i" and assign it a value of 1.
3. Print out the multiplication table for the number 5 using the "i" variable.
4. Change the value of the "i" variable to 2 and print out the corresponding multiplication table.
-5. Repeat step 4 for the values of "i" from 3 to 10.
+5. Repeat step 4 for the values of "i" from 3 to 5.
##### Solution:
@@ -737,7 +737,7 @@ jshell> System.out.printf("%d * %d = %d\n", 5, i, 5*i)
5 * 2 = 10
```
-5. Repeat step 4 for the values of "i" from 3 to 10.
+5. Repeat step 4 for the values of "i" from 3 to 5.
```
jshell> i = 3
@@ -754,10 +754,6 @@ jshell> i = 5
i ==> 5
jshell> System.out.printf("%d * %d = %d\n", 5, i, 5*i)
5 * 5 = 25
-
-jshell> i = 6
-i ==> 6
-jshell> System.out.printf("%d * %d = %d
```
From cae00fa511bef5cc171b57e937fdbeb6c9fa550d Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sat, 25 Mar 2023 23:08:00 +0530
Subject: [PATCH 061/178] .
---
CODECHALLENGE.md | 57 ++++++++++++++++++++++++++----------------------
1 file changed, 31 insertions(+), 26 deletions(-)
diff --git a/CODECHALLENGE.md b/CODECHALLENGE.md
index c756949d..29661496 100644
--- a/CODECHALLENGE.md
+++ b/CODECHALLENGE.md
@@ -782,39 +782,44 @@ myNum ==> 15
15
```
-#### Exercise 2: Looping with JShell
-1. Use a for loop to print the numbers from 1 to 10.
-2. Create a new variable called `sum` and initialize it to 0.
-3. Use a for loop to add the numbers from 1 to 10 to `sum`.
-4. Print the value of `sum`.
+#### Exercise 2: Printing the Sum using Formatted Output in JShell
-##### Solution to Exercise 2:
+1. Launch JShell
+2. Define three integer variables `a`, `b`, and `c`, and assign them the values `3`, `6`, and `9`, respectively.
+3. Print the sum of `a`, `b`, and `c` using `System.out.printf()`. The output should be in the format `a + b + c = sum`.
+4. Exit JShell using the `/exit` command.
+
+##### Solution
+
+1. Launch JShell
+2. Define three integer variables `a`, `b`, and `c`, and assign them the values `3`, `6`, and `9`, respectively.
```
-jshell> for (int i = 1; i <= 10; i++) {
- ...> System.out.println(i);
- ...> }
-1
-2
-3
-4
-5
-6
-7
-8
-9
-10
+jshell> int a = 3
+a ==> 3
-jshell> int sum = 0;
-sum ==> 0
+jshell> int b = 6
+b ==> 6
-jshell> for (int i = 1; i <= 10; i++) {
- ...> sum += i;
- ...> }
+jshell> int c = 9
+c ==> 9
+```
-jshell> System.out.println(sum);
-55
+3. Print the sum of `a`, `b`, and `c` using `System.out.printf()`. The output should be in the format `a + b + c = sum`.
+
+```
+jshell> System.out.printf("%d + %d + %d = %d%n", a, b, c, a + b + c);
+3 + 6 + 9 = 18
+```
+
+Note that the `%d` is a format specifier for integer values. The `%n` is a platform-independent newline character.
+
+4. Exit JShell using the `/exit` command.
+
+```
+jshell> /exit
+| Goodbye
```
From a84c1448b2833a75fe2787ba22399d48cd065986 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sat, 25 Mar 2023 23:10:30 +0530
Subject: [PATCH 062/178] .
---
CODECHALLENGE.md | 33 ---------------------------------
1 file changed, 33 deletions(-)
diff --git a/CODECHALLENGE.md b/CODECHALLENGE.md
index 29661496..032ccf9c 100644
--- a/CODECHALLENGE.md
+++ b/CODECHALLENGE.md
@@ -823,39 +823,6 @@ jshell> /exit
```
-### Step 15: Using Variables
-
-#### Java Coding Exercise 1
-
-Write a Java program using JShell to declare an integer variable called "age" and assign it a value of 25. Then, print the value of "age" on the console.
-
-##### Solution:
-
-```
-jshell> int age = 25;
-age ==> 25
-
-jshell> System.out.println(age);
-25
-```
-
-#### Java Coding Exercise 2
-
-Write a Java program using JShell to declare two variables, "name" and "age". Assign your name to the variable "name" and your age to the variable "age". Then, print the values of both variables on the console in the following format: "My name is [name] and I am [age] years old."
-
-##### Solution:
-
-```
-jshell> String name = "John Doe";
-name ==> "John Doe"
-
-jshell> int age = 30;
-age ==> 30
-
-jshell> System.out.println("My name is " + name + " and I am " + age + " years old.");
-My name is John Doe and I am 30 years old.
-```
-
### Step 16: Variables: Behind-The-Scenes
From 05862d77427f58acda961e45c03a40d299a074ee Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sun, 26 Mar 2023 07:52:07 +0530
Subject: [PATCH 063/178] .
---
CODECHALLENGE.md | 99 +++++++++++++++++++++++-------------------------
1 file changed, 47 insertions(+), 52 deletions(-)
diff --git a/CODECHALLENGE.md b/CODECHALLENGE.md
index 032ccf9c..8111ccff 100644
--- a/CODECHALLENGE.md
+++ b/CODECHALLENGE.md
@@ -909,81 +909,76 @@ student_name ==> null
### Step 18: Introducing Primitive Types
-#### Exercise 1: Using JShell to Perform Arithmetic Operations on Primitive Types
-**Problem:**
+#### Exercise 1: Printing Primitive Types using Formatted Output in JShell
-In this exercise, you will use JShell to perform arithmetic operations on various primitive types in Java. Perform the following operations and observe the results:
+1. Launch JShell
+2. Define a double variable `pi` and assign it the value `3.14159`.
+3. Print the value of `pi` using `System.out.printf()`. The output should be in the format `pi = 3.14`.
+4. Exit JShell using the `/exit` command.
-1. Add two `int` values.
-2. Multiply two `float` values.
-3. Divide a `double` value by an `int` value.
-4. Find the remainder when a `long` value is divided by an `int` value.
+##### Solution 1
-**Solution:**
+1. Launch JShell
+
+2. Define a double variable `pi` and assign it the value `3.14159`.
+
-Open JShell and execute the following commands:
+```
+jshell> double pi = 3.14159
+pi ==> 3.14159
+```
+3. Print the value of `pi` using `System.out.printf()`. The output should be in the format `pi = 3.14`.
+
+```
+jshell> System.out.printf("pi = %.2f%n", pi);
+pi = 3.14
```
-int a = 15;
-int b = 25;
-int sum = a + b;
-System.out.println("The sum of a and b is: " + sum);
-float c = 3.5f;
-float d = 2.0f;
-float product = c * d;
-System.out.println("The product of c and d is: " + product);
+Note that the `.2f` in the format string specifies the number of decimal places to be printed.
-double e = 30.0;
-int f = 4;
-double division = e / f;
-System.out.println("The result of dividing e by f is: " + division);
+4. Exit JShell using the `/exit` command.
-long g = 10000000000L;
-int h = 7;
-long remainder = g % h;
-System.out.println("The remainder when g is divided by h is: " + remainder);
+```
+jshell> /exit
+| Goodbye
```
-#### Exercise 2: Comparing Primitive Types in JShell
+#### Exercise 2: Printing Primitive Types using Formatted Output in JShell
-**Problem:**
+1. Launch JShell
+2. Define a boolean variable `isRainy` and assign it the value `true`.
+3. Print the value of `isRainy` using `System.out.printf()`. The output should be in the format `It is raining: true`.
+4. Exit JShell using the `/exit` command.
-In this exercise, you will use JShell to compare various primitive types in Java. Compare the following pairs of values and determine if they are equal:
+##### Solution 2
-1. Two `int` values.
-2. Two `float` values.
-3. Two `double` values.
-4. Two `char` values.
+1. Launch JShell
+
+2. Define a boolean variable `isRainy` and assign it the value `true`.
+
-**Solution:**
+```
+jshell> boolean isRainy = true
+isRainy ==> true
+```
-Open JShell and execute the following commands:
+3. Print the value of `isRainy` using `System.out.printf()`. The output should be in the format `It is raining: true`.
```
-int i1 = 42;
-int i2 = 42;
-boolean intsEqual = (i1 == i2);
-System.out.println("Are i1 and i2 equal? " + intsEqual);
+jshell> System.out.printf("It is raining: %b%n", isRainy);
+It is raining: true
+```
-float f1 = 3.14f;
-float f2 = 3.14f;
-boolean floatsEqual = (f1 == f2);
-System.out.println("Are f1 and f2 equal? " + floatsEqual);
+Note that the `%b` in the format string specifies the boolean value to be printed.
-double d1 = 25.678;
-double d2 = 25.678;
-boolean doublesEqual = (d1 == d2);
-System.out.println("Are d1 and d2 equal? " + doublesEqual);
+4. Exit JShell using the `/exit` command.
-char c1 = 'A';
-char c2 = 'A';
-boolean charsEqual = (c1 == c2);
-System.out.println("Are c1 and c2 equal? " + charsEqual);
```
-
-These exercises will help you gain hands-on experience with primitive types and their operations in Java using JShell.
+jshell> /exit
+| Goodbye
+```
### Step 19: Choosing A Data Type
From dcca7eeba952bd22985dfa5e4441b3f8bfab8163 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sun, 26 Mar 2023 07:58:07 +0530
Subject: [PATCH 064/178] .
---
CODECHALLENGE.md | 106 ++++++++++++++++++++++++++++++++++-------------
1 file changed, 77 insertions(+), 29 deletions(-)
diff --git a/CODECHALLENGE.md b/CODECHALLENGE.md
index 8111ccff..c7cbb007 100644
--- a/CODECHALLENGE.md
+++ b/CODECHALLENGE.md
@@ -984,55 +984,103 @@ jshell> /exit
### Step 19: Choosing A Data Type
-#### Exercise 1: Calculating average temperature
+#### Exercise: Choosing A Data Type using JShell
-**Problem:**
+1. Launch JShell.
+2. Write a statement to store the number of seconds in a day.
+3. Declare and initialize a variable to store the value of pi, accurate to 3 decimal places.
+4. Write a statement to store the temperature of the human body in degrees Celsius.
+5. Declare and initialize a variable to store the average height of an adult male in meters.
+6. Exit JShell using the `/exit` command.
-Write a program in JShell to calculate the average temperature of a week. Store the daily temperatures in an array, and then calculate and display the average temperature.
+##### Solution 1
-**Solution:**
+1. Launch JShell.
+
+2. Write a statement to store the number of seconds in a day.
+
```
-// Initialize the array with daily temperatures (in Celsius)
-double[] dailyTemperatures = {20.5, 22.3, 18.9, 19.6, 21.4, 23.7, 20.1};
+jshell> int secondsInDay = 86400;
+secondsInDay ==> 86400
+```
-// Calculate the sum of temperatures
-double sumTemperatures = 0;
-for (int i = 0; i < dailyTemperatures.length; i++) {
- sumTemperatures += dailyTemperatures[i];
-}
+3. Declare and initialize a variable to store the value of pi, accurate to 3 decimal places.
-// Calculate the average temperature
-double averageTemperature = sumTemperatures / dailyTemperatures.length;
+```
+jshell> double pi = 3.141;
+pi ==> 3.141
+```
-// Display the average temperature
-System.out.println("The average temperature for the week is: " + averageTemperature);
+4. Write a statement to store the temperature of the human body in degrees Celsius.
+
+```
+jshell> float bodyTemperature = 37.0f;
+bodyTemperature ==> 37.0
```
-#### Exercise 2: Determining leap years
+5. Declare and initialize a variable to store the average height of an adult male in meters.
-**Problem:**
+```
+jshell> double avgMaleHeight = 1.75;
+avgMaleHeight ==> 1.75
+```
-Write a program in JShell to determine if a given year is a leap year or not. A leap year is a year that is exactly divisible by 4, except for years that are exactly divisible by 100. However, years that are exactly divisible by 400 are also considered leap years.
+6. Exit JShell using the `/exit` command.
-**Solution:**
+```
+jshell> /exit
+| Goodbye
+```
+
+##### Problem 2
+
+1. Launch JShell.
+2. Write a statement to store the current year.
+3. Declare and initialize a variable to store the mass of the earth in kilograms.
+4. Write a statement to store the first letter of your first name.
+5. Declare and initialize a variable to store whether a person is eligible to vote.
+6. Exit JShell using the `/exit` command.
+##### Solution 2
+
+1. Launch JShell.
+
+2. Write a statement to store the current year.
+
+
+```
+jshell> short currentYear = 2023;
+currentYear ==> 2023
```
-// Define a year to check if it's a leap year
-int year = 2024;
-// Determine if the year is a leap year
-boolean isLeapYear = (year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0);
+3. Declare and initialize a variable to store the mass of the earth in kilograms.
-// Display the result
-if (isLeapYear) {
- System.out.println(year + " is a leap year.");
-} else {
- System.out.println(year + " is not a leap year.");
-}
+```
+jshell> long earthMass = 5972000000000000000000000L;
+earthMass ==> 5972000000000000000000000
```
+4. Write a statement to store the first letter of your first name.
+```
+jshell> char firstLetter = 'J';
+firstLetter ==> 'J'
+```
+
+5. Declare and initialize a variable to store whether a person is eligible to vote.
+
+```
+jshell> boolean isEligibleToVote = true;
+isEligibleToVote ==> true
+```
+
+6. Exit JShell using the `/exit` command.
+
+```
+jshell> /exit
+| Goodbye
+```
### Step 20: The Assignment Operator =
From c9b8fa30a0cb973ab15565ca59351552fefe3177 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sun, 26 Mar 2023 07:58:50 +0530
Subject: [PATCH 065/178] .
---
CODECHALLENGE.md | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/CODECHALLENGE.md b/CODECHALLENGE.md
index c7cbb007..e7652d9e 100644
--- a/CODECHALLENGE.md
+++ b/CODECHALLENGE.md
@@ -984,7 +984,7 @@ jshell> /exit
### Step 19: Choosing A Data Type
-#### Exercise: Choosing A Data Type using JShell
+#### Exercise 1: Choosing A Data Type using JShell
1. Launch JShell.
2. Write a statement to store the number of seconds in a day.
@@ -1033,7 +1033,7 @@ jshell> /exit
| Goodbye
```
-##### Problem 2
+#### Exercise 2: Choosing A Data Type using JShell
1. Launch JShell.
2. Write a statement to store the current year.
From 3cf98f371eaeb2242b1913e0ccde7f784e11ff34 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sun, 26 Mar 2023 08:07:12 +0530
Subject: [PATCH 066/178] .
---
CODECHALLENGE.md | 79 ++++++++++++++++++++++++++++++------------------
1 file changed, 49 insertions(+), 30 deletions(-)
diff --git a/CODECHALLENGE.md b/CODECHALLENGE.md
index e7652d9e..3340d269 100644
--- a/CODECHALLENGE.md
+++ b/CODECHALLENGE.md
@@ -1088,55 +1088,74 @@ jshell> /exit
-#### Exercise 1: Increment and Decrement Counter
-**Problem**
+#### Exercise 1: Increment and Decrement Counter
-Write a Java program using JShell to demonstrate the use of increment and decrement operations on a counter variable `counter`. Follow these steps:
+Write a Java program using JShell to demonstrate the use of increment and decrement operations on a counter variable `count`. Follow these steps:
-1. Initialize `counter` with 0.
-2. Increment `counter` by 5.
-3. Decrement `counter` by 2.
+1. Initialize `count` with 10.
+2. Increment `count` by 2 using the `++` operator.
+3. Decrement `count` by 3 using the `--` operator.
+4. Add 5 to `count` using the `+=` operator.
+5. Subtract 2 from `count` using the `-=` operator.
-**Solution**
+Solution
```
-jshell> int counter = 0;
-counter ==> 0
+jshell> int count = 10;
+count ==> 10
+
+jshell> count++;
+count ==> 11
+
+jshell> count--;
+count ==> 10
-jshell> counter = counter + 5;
-counter ==> 5
+jshell> count += 5;
+count ==> 15
-jshell> counter = counter - 2;
-counter ==> 3
+jshell> count -= 2;
+count ==> 13
-jshell> counter;
-counter ==> 3
+jshell> count;
+count ==> 13
```
-#### Exercise 2: Calculate the power of a number using increments
+Explanation
+
+We first initialize `count` with the value 10. We then increment it by 2 using the `++` operator, which results in `count` being equal to 11. We then decrement it by 3 using the `--` operator, which results in `count` being equal to 10 again.
-**Problem**
+Next, we add 5 to `count` using the `+=` operator, which results in `count` being equal to 15. Finally, we subtract 2 from `count` using the `-=` operator, which results in `count` being equal to 13.
-Write a Java program using JShell to calculate the power of a number `base` raised to an exponent `exponent`. Do this using increments and a loop.
+We print the value of `count` using the JShell prompt at the end, which confirms that the above operations were successful.
-**Solution**
+
+#### Exercise 2: Arithmetic Operations on a Variable Problem
+
+Write a Java program using JShell to perform arithmetic operations on a variable num. Follow these steps:
+
+1. Initialize num with 5.
+2. Multiply num by 3.
+3. Divide num by 2.
+4. Calculate the remainder of num when divided by 4.
+
+##### Solution
```
-jshell> int base = 2;
-base ==> 2
+jshell> int num = 5;
+num ==> 5
-jshell> int exponent = 3;
-exponent ==> 3
+jshell> num *= 3;
+num ==> 15
-jshell> int result = 1;
-result ==> 1
+jshell> num /= 2;
+num ==> 7
-jshell> for (int i = 0; i < exponent; i++) {
- ...> result = result * base;
- ...> }
-jshell> result;
-result ==> 8
+jshell> num %= 4;
+num ==> 3
+
+jshell> num;
+num ==> 3
```
From 59e35d8aee6d5c5896454a63ac08cdb77626351c Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sun, 26 Mar 2023 08:19:04 +0530
Subject: [PATCH 067/178] .
---
CODECHALLENGE.md | 72 ++++++++++++++++++++++++++++++++++++------------
1 file changed, 55 insertions(+), 17 deletions(-)
diff --git a/CODECHALLENGE.md b/CODECHALLENGE.md
index 3340d269..1fb70a09 100644
--- a/CODECHALLENGE.md
+++ b/CODECHALLENGE.md
@@ -1310,37 +1310,75 @@ int num2 = 9
-#### Exercise 1: Check if a Number is Even
+#### Exercise 1: Introducing Conditionals - the if
-**Problem**: Write a Java program using JShell that checks if a given number is even or odd. If the number is even, print "The number is even", otherwise print "The number is odd".
+1. Launch JShell
+2. Set the variable `age` to `20`: `int age = 20;`
+3. Use an `if` statement to print out `"You are eligible to vote"` if `age` is greater than or equal to `18`
+4. Use another `if` statement to print out `"You are not eligible to vote"` if `age` is less than `18`
+5. Exit JShell using `/exit` command
-**Solution**:
+##### Solution 1
+1. Launch JShell
+2. Set the variable `age` to `20`: `int age = 20;`
+3. Use an `if` statement to print out `"You are eligible to vote"` if `age` is greater than or equal to `18`:
+
+```
+jshell> if(age >= 18)
+ System.out.println("You are eligible to vote");
+You are eligible to vote
```
-int number = 10;
-if (number % 2 == 0) {
- System.out.println("The number is even");
-} else {
- System.out.println("The number is odd");
-}
-```
+4. Use another `if` statement to print out `"You are not eligible to vote"` if `age` is less than `18`:
+
+```
+jshell> if(age < 18)
+ System.out.println("You are not eligible to vote");
+```
+
+5. Exit JShell using `/exit` command:
+
+```
+jshell> /exit
+| Goodbye
+```
-#### Exercise 2: Compare Two Numbers
+#### Exercise 2: Introducing Conditionals - the if
-**Problem**: Write a Java program using JShell that takes two integer values as input and compares them. If the first number is greater than the second number, print "The first number is greater than the second number".
+1. Launch JShell
+2. Set the variable `price1` to `10.50`: `double price1 = 10.50;`
+3. Set the variable `price2` to `9.99`: `double price2 = 9.99;`
+4. Use an `if` statement to print out `"Price 1 is greater than Price 2"` if `price1` is greater than `price2`
+5. Use another `if` statement to print out `"Price 2 is greater than Price 1"` if `price2` is greater than `price1`
+6. Exit JShell using `/exit` command
-**Solution**:
+##### Solution 2
+
+1. Launch JShell
+2. Set the variable `price1` to `10.50`: `double price1 = 10.50;`
+3. Set the variable `price2` to `9.99`: `double price2 = 9.99;`
+4. Use an `if` statement to print out `"Price 1 is greater than Price 2"` if `price1` is greater than `price2`:
```
-int num1 = 15;
-int num2 = 7;
+jshell> if(price1 > price2)
+ System.out.println("Price 1 is greater than Price 2");
+Price 1 is greater than Price 2
+```
+
+5. Use another `if` statement to print out `"Price 2 is greater than Price 1"` if `price2` is greater than `price1`:
-if (num1 > num2) {
- System.out.println("The first number is greater than the second number");
+```
+jshell> if(price2 > price1)
+ System.out.println("Price 2 is greater than Price 1");
```
+6. Exit JShell using `/exit` command:
+```
+jshell> /exit
+| Goodbye
+```
### Step 24: Programming Exercise PE-04
From 0932244f5ffa290b37da6c8af0d0b2e42d761f82 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sun, 26 Mar 2023 08:21:03 +0530
Subject: [PATCH 068/178] .
---
CODECHALLENGE.md | 15 ++++++++++++---
1 file changed, 12 insertions(+), 3 deletions(-)
diff --git a/CODECHALLENGE.md b/CODECHALLENGE.md
index 1fb70a09..634d9ca8 100644
--- a/CODECHALLENGE.md
+++ b/CODECHALLENGE.md
@@ -1321,7 +1321,10 @@ int num2 = 9
##### Solution 1
1. Launch JShell
-2. Set the variable `age` to `20`: `int age = 20;`
+2. Set the variable `age` to `20`:
+```
+int age = 20;
+````
3. Use an `if` statement to print out `"You are eligible to vote"` if `age` is greater than or equal to `18`:
```
@@ -1356,8 +1359,14 @@ jshell> /exit
##### Solution 2
1. Launch JShell
-2. Set the variable `price1` to `10.50`: `double price1 = 10.50;`
-3. Set the variable `price2` to `9.99`: `double price2 = 9.99;`
+2. Set the variable `price1` to `10.50`:
+```
+double price1 = 10.50;
+```
+3. Set the variable `price2` to `9.99`:
+```
+double price2 = 9.99;
+```
4. Use an `if` statement to print out `"Price 1 is greater than Price 2"` if `price1` is greater than `price2`:
```
From 828f6b660b53bb8d3113121a470e20d6b97a6b7a Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sun, 26 Mar 2023 09:05:45 +0530
Subject: [PATCH 069/178] .
---
CODECHALLENGE.md | 36 ++++++++++++++++++++++++++----------
1 file changed, 26 insertions(+), 10 deletions(-)
diff --git a/CODECHALLENGE.md b/CODECHALLENGE.md
index 634d9ca8..e95c389c 100644
--- a/CODECHALLENGE.md
+++ b/CODECHALLENGE.md
@@ -1614,24 +1614,40 @@ System.out.println("The factorial of " + n + " is: " + factorial);
### Step 30: Puzzling You With `for`
+
#### Exercise 1
-**Problem:** Write a Java code snippet in JShell to find the sum of all even numbers between 1 and 10 (inclusive).
+1. Launch JShell
+2. Write a for loop that counts from 1 to 5 using two variables `i` and `j`, with `i` starting at 1 and incrementing by 1, and `j` starting at 5 and decrementing by 1.
+3. Within the for loop, print the values of `i` and `j` on each iteration using `System.out.printf()` with the format string "i = %d, j = %d\n".
+4. Exit JShell using the `/exit` command.
-**Solution:**
+##### Solution 1
-```
-jshell> int sum = 0;
-sum ==> 0
+1. Launch JShell
+2. Write a for loop that counts from 1 to 5 using two variables `i` and `j`, with `i` starting at 1 and incrementing by 1, and `j` starting at 5 and decrementing by 1.
-jshell> for (int i = 2; i <= 10; i += 2) {
- ...> sum += i;
+```
+jshell> for (int i = 1, j = 5; i <= 5; i++, j--) {
+ ...> System.out.printf("i = %d, j = %d\n", i, j);
...> }
-
-jshell> sum
-sum ==> 30
```
+3. Within the for loop, print the values of `i` and `j` on each iteration using `System.out.printf()` with the format string "i = %d, j = %d\n".
+4. Exit JShell using the `/exit` command.
+
+```
+i = 1, j = 5
+i = 2, j = 4
+i = 3, j = 3
+i = 4, j = 2
+i = 5, j = 1
+| Expression value is: void
+| assigned to temporary variable $1 of type void
+```
+
+
+
### Exercise 2
**Problem:** Write a Java code snippet in JShell to print the multiplication table of 5.
From 8ff106b6cd9049c896c6d58a30a4788904d77f27 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sun, 26 Mar 2023 09:20:25 +0530
Subject: [PATCH 070/178] .
---
.../CODECHALLENGE.md | 0
.../QUIZ.md | 0
2 files changed, 0 insertions(+), 0 deletions(-)
rename CODECHALLENGE.md => 01-IntroductionToJavaProgrammingWithJShell-MultiplicationTable/CODECHALLENGE.md (100%)
rename QUIZ.md => 01-IntroductionToJavaProgrammingWithJShell-MultiplicationTable/QUIZ.md (100%)
diff --git a/CODECHALLENGE.md b/01-IntroductionToJavaProgrammingWithJShell-MultiplicationTable/CODECHALLENGE.md
similarity index 100%
rename from CODECHALLENGE.md
rename to 01-IntroductionToJavaProgrammingWithJShell-MultiplicationTable/CODECHALLENGE.md
diff --git a/QUIZ.md b/01-IntroductionToJavaProgrammingWithJShell-MultiplicationTable/QUIZ.md
similarity index 100%
rename from QUIZ.md
rename to 01-IntroductionToJavaProgrammingWithJShell-MultiplicationTable/QUIZ.md
From 3d2464f7e282063f06fab3aea00260239fc8fa76 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sun, 26 Mar 2023 09:22:15 +0530
Subject: [PATCH 071/178] .
---
README.md | 329 ------------------------------------------------------
1 file changed, 329 deletions(-)
diff --git a/README.md b/README.md
index d2f7e444..9ac941c4 100644
--- a/README.md
+++ b/README.md
@@ -123,46 +123,6 @@ In this step, we:
* Stated our first programming challenge, *PMT-Challenge*
* Identified basic Java concepts to learn, to solve this challenge
-#### Quiz:
-
-Question 1: What is the aim of the PMT-Challenge?
-a) To solve a mathematical equation
-b) To read out a multiplication table
-c) To learn basic Java concepts
-
-Answer: b) To read out a multiplication table
-
-Question 2: What are some basic Java concepts that will be introduced in the PMT-Challenge?
-a) Numbers and alphabets
-b) Loops and conditionals
-c) Colors and shapes
-
-Answer: b) Loops and conditionals
-
-Question 3: Which of the following is NOT a basic Java concept introduced in the PMT-Challenge?
-a) Variables
-b) Methods
-c) Booleans
-Answer: c) Booleans
-
-#### Hands-on Exercise:
-
-Write a Java program to compute the multiplication table for 7, with entries from 1 to 12. Display this table in the following format:
-```
-7 * 1 = 7
-7 * 2 = 14
-7 * 3 = 21
-7 * 4 = 28
-7 * 5 = 35
-7 * 6 = 42
-7 * 7 = 49
-7 * 8 = 56
-7 * 9 = 63
-7 * 10 = 70
-7 * 11 = 77
-7 * 12 = 84
-```
-
### Step 02: Introducing ```JShell```
- - -
@@ -291,36 +251,6 @@ In this step, we learned:
* How to launch ```JShell``` from our terminal, and run a few commands on it
* How to run Java code on the ```JShell``` prompt
-#### Quiz:
-
-What is JShell?
-A. A programming tool
-B. A game
-C. A text editor
-Answer: A
-
-What does REPL stand for?
-A. Read, Evaluate, Print, Loop
-B. Run, Edit, Print, Launch
-C. Record, Edit, Play, Loop
-Answer: A
-
-How do you exit JShell?
-A. /terminate
-B. /exit
-C. /quit
-Answer: B
-
-#### Hands-on exercise:
-
-Exercise: Launch JShell and Evaluate an Expression
-
-Launch JShell on your terminal.
-Type 2+3 at the JShell prompt and press enter.
-Observe the output.
-Type /exit to exit JShell.
-
-
### Step 03: Welcome to Problem Solving
Lets try to break down the *PMT-Challenge* problem to be able to solve it.
@@ -350,50 +280,6 @@ In this step, we:
* Broke down the *PMT-Challenge* problem into sub-problems
-#### Quiz:
-
-Question 1: What is the aim of breaking down a problem into sub-problems?
-a) To make the problem more complicated
-b) To make the problem easier to solve
-c) To avoid solving the problem altogether
-
-Answer: b) To make the problem easier to solve
-
-Question 2: How many times do we need to perform the calculation in the PMT-Challenge?
-a) Five times
-b) Ten times
-c) Fifteen times
-
-Answer: b) Ten times
-
-Question 3: What is the first step to solve the PMT-Challenge according to the draft steps?
-a) Print 5 * 3 = 15
-b) Calculate 5 * 3 and print result as 15
-c) Do this ten times
-
-Answer: b) Calculate 5 * 3 and print result as 15
-
-#### Hands-on Exercise:
-
-Write a Java program to compute the multiplication table for 9, with entries from 1 to 15. Use the draft steps mentioned above to solve the problem. Display this table in the following format:
-```
-9 * 1 = 9
-9 * 2 = 18
-9 * 3 = 27
-9 * 4 = 36
-9 * 5 = 45
-9 * 6 = 54
-9 * 7 = 63
-9 * 8 = 72
-9 * 9 = 81
-9 * 10 = 90
-9 * 11 = 99
-9 * 12 = 108
-9 * 13 = 117
-9 * 14 = 126
-9 * 15 = 135
-```
-
### Step 04: Introducing Expressions
The first part of solving our *PMT-Challenge* is to calculate the product of ```5``` and another number, say ```3```.
@@ -510,31 +396,6 @@ In this step, we:
* Learned how to construct numeric expressions
* Discovered that operators are predefined symbols
* Combined several operators to form larger expressions
-
-
-#### Quiz:
-
-What is an expression in Java programming?
-a) A set of instructions to be executed
-b) A combination of operands and operators that results in a value
-c) A way to define a variable
-Answer: b
-
-Which symbol is used for multiplication in Java programming?
-a) X
-b) *
-c) /
-Answer: b
-
-What does the modulo operator do in Java programming?
-a) Adds two numbers
-b) Subtracts two numbers
-c) Gives the remainder when integer division is performed
-Answer: c
-
-#### Hands-on exercise:
-
-Create a Java program that calculates the product of two numbers and displays the result. Use the multiplication operator (*) to perform the calculation.
### Step 05: Programming Exercise PE-1 (With Solutions)
@@ -565,42 +426,6 @@ $jshell>60 * 60 * 24
$1 ==> 86400
```
-#### Quiz:
-
-Question 1: What is the purpose of Step 05 in this book?
-a) To learn basic math concepts
-b) To practice evaluating Java expressions
-c) To explore advanced Java programming concepts
-
-Answer: b) To practice evaluating Java expressions
-
-Question 2: What is the expression to calculate the number of minutes in a day?
-a) 60 * 24
-b) 60 + 24
-c) 24 * 60 * 60
-
-Answer: a) 60 * 24
-
-Question 3: What is the expression to calculate the number of seconds in a day?
-a) 60 * 60
-b) 60 * 60 * 24
-c) 24 / 60 / 60
-
-Answer: b) 60 * 60 * 24
-
-#### Hands-on Exercise:
-
-Write a Java expression to calculate the number of milliseconds in a day.
-Display the result using System.out.println() method.
-
-Solution:
-1000 (milliseconds in a second) multiplied by 60 (seconds in a minute) multiplied by 60 (minutes in an hour) multiplied by 24 (hours in a day)
-
-```
-long millisecondsInADay = 1000L * 60 * 60 * 24;
-System.out.println("Number of milliseconds in a day: " + millisecondsInADay);
-```
-
### Step 06: Operators
Lets look at a few more examples to understand operators.
@@ -748,38 +573,6 @@ In this step, we:
* Learned that result of operation depends on operand types
* Understood what operator precedence means
* Used parentheses to group parts of an expression
-
-
-
-#### Quiz
-
-What is the result of the expression 5 / 2?
-a) 2
-b) 2.5
-c) Error
-Correct answer: a) 2
-
-Which of the following operators has the highest precedence?
-a) +
-b) *
-c) %
-Correct answer: b) *
-
-Which of the following is the correct way to group the sub-expressions in the expression 5 + 5 * 6?
-a) 5 + (5 * 6)
-b) (5 + 5) * 6
-c) 5 + 5 * 6
-Correct answer: a) 5 + (5 * 6)
-
-#### Hands-on Exercise:
-Write a Java program that takes two integers as input from the user and performs the following operations on them:
-
-* Addition
-* Subtraction
-* Multiplication
-* Division
-
-Make sure to display the results of each operation to the user. Use parentheses to group the sub-expressions in each operation for better readability.
### Step 07: Introducing Console Output
@@ -877,34 +670,6 @@ In this step, we:
* Were introduced to the ```System.out.println()``` method for console output
* Used this utility to print a single *PMT-Challenge* table entry
-#### Quiz
-
-Question 1: What is the syntax for calling the System.out.println() method in Java?
-a) System.out.println
-b) println.System.out
-c) System.out.print
-
-Correct answer: a) System.out.println
-
-Question 2: What is a String literal in Java?
-a) A sequence of characters enclosed within double quotes
-b) A method call used to display text on the console
-c) A variable used to store numeric values
-
-Correct answer: a) A sequence of characters enclosed within double quotes
-
-Question 3: How do you display the text "5 * 2 = 10" on the console in Java?
-a) System.out.println(5 * 2 = 10)
-b) System.out.println("5 * 2 = 10")
-c) System.out.print("5 * 2 = 10")
-
-Correct answer: b) System.out.println("5 * 2 = 10")
-
-#### Hands-on exercise:
-
-Write a Java program that computes the product of two integers, and displays the result in the format "a * b = c", where a and b are the input integers, and c is their product. Use the System.out.println() method to display the result on the console.
-
-
### Step 08: Programming Exercise PE-02
Try and solve the following exercises:
@@ -924,46 +689,6 @@ Try and solve the following exercises:
* Operands
* Method calls
-
-#### Quiz:
-
-Question 1: What is the first exercise in Programming Exercise PE-02?
-a) Print the calculated value of 5 * 3
-b) Print the number of seconds in a day
-c) Print Hello World onto the console
-
-Answer: c) Print Hello World onto the console
-
-Question 2: What do you need to identify in your code when doing a syntax revision for the exercises in Programming Exercise PE-02?
-a) Loops and conditionals
-b) Numeric and string literals, expressions, operators, operands, and method calls
-c) Classes and objects
-
-Answer: b) Numeric and string literals, expressions, operators, operands, and method calls
-
-Question 3: What should be printed when you execute the code for the second exercise in Programming Exercise PE-02?
-a) "5 * 3"
-b) "15"
-c) 5 * 3
-
-Answer: a) "5 * 3"
-
-#### Hands-on Exercise:
-
-Write a Java program to print the following:
-
-- Your name
-- The year you were born
-- The year you will turn 30
-
-Do a syntax revision for your code, and identify the following elements:
-
-- Numeric and string literals
-- Expressions
-- Operators
-- Operands
-- Method calls
-
### Step 09: Solutions to PE-02
#### Solution 1
@@ -1002,34 +727,6 @@ Do a syntax revision for your code, and identify the following elements:
```
-#### Quiz:
-
-Question 1: What is the output of Solution 1?
-a) "5 * 3"
-b) "Hello World"
-c) 15
-
-Answer: b) "Hello World"
-
-Question 2: What is the output of Solution 2?
-a) "15"
-b) "5 * 3"
-c) Syntax Error
-
-Answer: b) "5 * 3"
-
-Question 3: What is the output of Solution 4?
-a) 86400
-b) 5184000
-c) 3600
-
-Answer: a) 86400
-
-#### Hands-on Exercise:
-
-Write a Java program to print the following sentence using the System.out.println() statement:
-- "Java is a programming language."
-
### Step 10: Whitespace, Case sensitiveness and Escape Characters
The term *whitespace* refers to any sequence of continuous space, tab or newline characters.
@@ -1178,32 +875,6 @@ In this step, we:
* Discovered the uses of whitespace characters
* Learned about Java escape sequences
-
-#### Quiz
-What happens when you use whitespace around string literals in Java?
-a) It is ignored by the compiler
-b) It produces a syntax error
-Correct answer: a) It is ignored by the compiler
-
-Is Java case sensitive?
-a) Yes
-b) No
-Correct answer: a) Yes
-
-What is the role of the backslash character in Java?
-a) It is a special symbol used for escape sequences
-b) It is used to indicate a syntax error
-Correct answer: a) It is a special symbol used for escape sequences
-
-#### Hands-on exercise:
-Write a Java program that prints the following output to the console:
-````
-Hello
-World
-````
-
-Hint: You can use the escape sequence "\n" to insert a newline and "\t" to insert a tab.
-
### Step 11: More On Method Calls
Let's look at method calls with a few more examples.
From 6ac4fc806a493120d072fd147719a3fc6ff5861f Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sun, 26 Mar 2023 09:24:07 +0530
Subject: [PATCH 072/178] .
---
.../QUIZ.md | 0
.../CODECHALLENGE.md | 0
2 files changed, 0 insertions(+), 0 deletions(-)
rename {01-IntroductionToJavaProgrammingWithJShell-MultiplicationTable => 01-Quiz}/QUIZ.md (100%)
rename {01-IntroductionToJavaProgrammingWithJShell-MultiplicationTable => 02-CodeChallenge}/CODECHALLENGE.md (100%)
diff --git a/01-IntroductionToJavaProgrammingWithJShell-MultiplicationTable/QUIZ.md b/01-Quiz/QUIZ.md
similarity index 100%
rename from 01-IntroductionToJavaProgrammingWithJShell-MultiplicationTable/QUIZ.md
rename to 01-Quiz/QUIZ.md
diff --git a/01-IntroductionToJavaProgrammingWithJShell-MultiplicationTable/CODECHALLENGE.md b/02-CodeChallenge/CODECHALLENGE.md
similarity index 100%
rename from 01-IntroductionToJavaProgrammingWithJShell-MultiplicationTable/CODECHALLENGE.md
rename to 02-CodeChallenge/CODECHALLENGE.md
From faaf7a5539159d3cc9c0127af89e628faf17e350 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sun, 26 Mar 2023 09:25:16 +0530
Subject: [PATCH 073/178] .
---
...ntroductionToJavaProgrammingWithJShell-MultiplicationTable.md} | 0
1 file changed, 0 insertions(+), 0 deletions(-)
rename 02-CodeChallenge/{CODECHALLENGE.md => 01-IntroductionToJavaProgrammingWithJShell-MultiplicationTable.md} (100%)
diff --git a/02-CodeChallenge/CODECHALLENGE.md b/02-CodeChallenge/01-IntroductionToJavaProgrammingWithJShell-MultiplicationTable.md
similarity index 100%
rename from 02-CodeChallenge/CODECHALLENGE.md
rename to 02-CodeChallenge/01-IntroductionToJavaProgrammingWithJShell-MultiplicationTable.md
From 8fa517ddc47380ba24ec1de871b8a14ed6d076ec Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sun, 26 Mar 2023 13:44:27 +0530
Subject: [PATCH 074/178] .
---
01-Quiz/QUIZ.md | 102 +++++++++++-------------------------------------
1 file changed, 22 insertions(+), 80 deletions(-)
diff --git a/01-Quiz/QUIZ.md b/01-Quiz/QUIZ.md
index 1988933c..1810c73f 100644
--- a/01-Quiz/QUIZ.md
+++ b/01-Quiz/QUIZ.md
@@ -1,94 +1,36 @@
## Java Multiple Choice Quiz
-### Step 01: First Challenge : The Print-Multiplication-Table (PMT-Challenge)
+### Step 02: Introducing JShell
-1. What is the objective of the PMT-Challenge?
-
- a. To write a program that prints out a multiplication table for 10, with entries from 1 to 5.
-
- b. To write a program that prints out a multiplication table for 5, with entries from 1 to 10.
-
- c. To write a program that prints out a multiplication table for 5, with entries from 1 to 5.
-
- **Answer: b**
-
-2. What is JShell?
-
- a. A tool for creating and managing databases in Java.
-
- b. A tool for interactive Java programming, allowing you to experiment with Java code and test snippets of code.
-
- c. A tool for creating and managing user interfaces in Java.
-
- **Answer: b**
-
-3. Which Java concept is used to execute a set of statements repeatedly?
-
- a. Conditionals
-
- b. Methods
-
- c. Loops
-
- **Answer: c**
+JShell is a programming tool, introduced in Java SE 9. JShell is a REPL interface. The term REPL refers to this:
+'R' stands for Read; Read the input Java code
+'E' means Eval; Evaluate the source code
+'P' translates to Print; Print out the result
+'L' indicates Loop; Loop around, and wait for the next input
+How about starting off exploring Java? Are you game?
-#### Exercise 1: PMT Challenge Using For Loop
+----------
-Using JShell, write a program to display the multiplication table for 7, with entries from 1 to 10 using a for loop.
+1. What does JShell stand for? a. JavaShell
+ b. JavaScriptShell
+ c. JupyterShell
-###### Solution
+**Answer: a. JavaShell**
-Launch JShell and enter the following commands:
+----------
+2. What is the purpose of JShell? a. To create graphical user interfaces
+ b. To evaluate and execute Java code and provide immediate results
+ c. To debug Java code
-```
-for(int i = 1; i <= 10; i++) {
- System.out.println("7 * " + i + " = " + (7*i));
-}
-```
+**Answer: b. To evaluate and execute Java code and provide immediate results**
-Output:
+----------
+3. What command can be used to exit JShell? a. /end
+ b. /exit
+ c. /quit
-```
-7 * 1 = 7
-7 * 2 = 14
-7 * 3 = 21
-7 * 4 = 28
-7 * 5 = 35
-7 * 6 = 42
-7 * 7 = 49
-7 * 8 = 56
-7 * 9 = 63
-7 * 10 = 70
-```
-
-#### Exercise 2: PMT Challenge Using While Loop
-
-Using JShell, write a program to display the multiplication table for 3, with entries from 1 to 5 using a while loop.
-
-###### Solution
-
-Launch JShell and enter the following commands:
-
-
-```
-int i = 1;
-while(i <= 5) {
- System.out.println("3 * " + i + " = " + (3*i));
- i++;
-}
-```
-
-Output:
-
-
-```
-3 * 1 = 3
-3 * 2 = 6
-3 * 3 = 9
-3 * 4 = 12
-3 * 5 = 15
-```
+**Answer: b. /exit**
\ No newline at end of file
From 27f81fbe574e842a6547b2861aa4a741439c1f18 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sun, 26 Mar 2023 13:45:05 +0530
Subject: [PATCH 075/178] .
---
01-Quiz/QUIZ.md | 9 ---------
1 file changed, 9 deletions(-)
diff --git a/01-Quiz/QUIZ.md b/01-Quiz/QUIZ.md
index 1810c73f..9223c4fd 100644
--- a/01-Quiz/QUIZ.md
+++ b/01-Quiz/QUIZ.md
@@ -2,15 +2,6 @@
### Step 02: Introducing JShell
-JShell is a programming tool, introduced in Java SE 9. JShell is a REPL interface. The term REPL refers to this:
-
-'R' stands for Read; Read the input Java code
-'E' means Eval; Evaluate the source code
-'P' translates to Print; Print out the result
-'L' indicates Loop; Loop around, and wait for the next input
-
-How about starting off exploring Java? Are you game?
-
----------
1. What does JShell stand for? a. JavaShell
From 586f618f4ef81126d8380d07f7dc0f851ce43fcb Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sun, 26 Mar 2023 13:54:43 +0530
Subject: [PATCH 076/178] .
---
...roductionToJavaProgrammingWithJShell-MultiplicationTable.md} | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
rename 01-Quiz/{QUIZ.md => Q01-IntroductionToJavaProgrammingWithJShell-MultiplicationTable.md} (94%)
diff --git a/01-Quiz/QUIZ.md b/01-Quiz/Q01-IntroductionToJavaProgrammingWithJShell-MultiplicationTable.md
similarity index 94%
rename from 01-Quiz/QUIZ.md
rename to 01-Quiz/Q01-IntroductionToJavaProgrammingWithJShell-MultiplicationTable.md
index 9223c4fd..f7bc884c 100644
--- a/01-Quiz/QUIZ.md
+++ b/01-Quiz/Q01-IntroductionToJavaProgrammingWithJShell-MultiplicationTable.md
@@ -1,6 +1,6 @@
## Java Multiple Choice Quiz
-### Step 02: Introducing JShell
+## Step 02: Introducing JShell
----------
From 35035bed8dc96ccb0e13e58c0af3d10d047f6ddf Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sun, 26 Mar 2023 17:13:28 +0530
Subject: [PATCH 077/178] .
---
...ogrammingWithJShell-MultiplicationTable.md | 633 +++++++++++++++++-
1 file changed, 629 insertions(+), 4 deletions(-)
diff --git a/01-Quiz/Q01-IntroductionToJavaProgrammingWithJShell-MultiplicationTable.md b/01-Quiz/Q01-IntroductionToJavaProgrammingWithJShell-MultiplicationTable.md
index f7bc884c..c43b44b9 100644
--- a/01-Quiz/Q01-IntroductionToJavaProgrammingWithJShell-MultiplicationTable.md
+++ b/01-Quiz/Q01-IntroductionToJavaProgrammingWithJShell-MultiplicationTable.md
@@ -4,7 +4,8 @@
----------
-1. What does JShell stand for? a. JavaShell
+1. What does JShell stand for?
+ a. JavaShell
b. JavaScriptShell
c. JupyterShell
@@ -12,7 +13,8 @@
----------
-2. What is the purpose of JShell? a. To create graphical user interfaces
+2. What is the purpose of JShell?
+ a. To create graphical user interfaces
b. To evaluate and execute Java code and provide immediate results
c. To debug Java code
@@ -20,8 +22,631 @@
----------
-3. What command can be used to exit JShell? a. /end
+3. What command can be used to exit JShell?
+ a. /end
b. /exit
c. /quit
-**Answer: b. /exit**
\ No newline at end of file
+**Answer: b. /exit**
+
+
+## Step 03: Welcome to Problem Solving
+
+
+1. What is the problem solving technique used in this step?
+
+ - a) Reverse Engineering
+ - b) Subdivision
+ - c) Deductive Reasoning
+ - Answer: b) Subdivision
+2. What is the result of 5 * 3?
+
+ - a) 8
+ - b) 10
+ - c) 15
+ - Answer: c) 15
+3. How many times do we repeat the calculation in this step?
+
+ - a) 5 times
+ - b) 10 times
+ - c) 15 times
+ - Answer: b) 10 times
+
+
+
+## Step 04: Introducing Expressions
+
+1. What is the result of 5 * 3?
+
+ - a) 8
+ - b) 10
+ - c) 15
+ - Answer: c) 15
+2. What are the operands in the expression 5 * 3?
+
+ - a) 5, 3
+ - b) 5
+ - c) 3
+ - Answer: a) 5, 3
+3. What is the modulo operator in Java?
+
+ - a) *
+ - b) %
+ - c) +
+ - Answer: b) %
+
+
+## Step 05: Programming Exercise PE-1 (With Solutions)
+
+1. Write an expression to calculate the number of minutes in a day.
+
+ - a) 24 * 60
+ - b) 60 + 24
+ - c) 60 * 24
+ - Answer: c) 60 * 24
+2. Write an expression to calculate the number of seconds in a day.
+
+ - a) 24 * 60 * 60
+ - b) 60 + 60 + 24
+ - c) 60 * 60 * 24
+ - Answer: c) 60 * 60 * 24
+
+
+
+## Step 06: Operators
+
+1. Which of the following is a valid operator in Java?
+
+ - a) **
+ - b) $
+ - c) *
+ - Answer: c) *
+2. What is the result of 5 / 2 in Java?
+
+ - a) 2
+ - b) 2.0
+ - c) 2.5
+ - Answer: a) 2
+3. What is the order of sub-expression evaluation in the expression 5 + 5 * 6?
+
+ - a) 5 + 5, then 10 * 6
+ - b) 5 * 6, then 5 + 30
+ - c) Depends on operand types
+ - Answer: b) 5 * 6, then 5 + 30
+4. How can parentheses be used to group parts of an expression?
+
+ - a) They have no effect on the evaluation of an expression
+ - b) They are used to specify the order of sub-expression evaluation
+ - c) They are used to introduce new operators
+ - Answer: b) They are used to specify the order of sub-expression evaluation
+
+
+## Step 07: Introducing Console Output
+
+1. Which built-in Java method displays text on the console?
+
+ - a) System.out.print()
+ - b) System.out.display()
+ - c) System.out.println()
+ - Answer: c) System.out.println()
+2. What is a String literal in Java?
+
+ - a) A sequence of numbers
+ - b) A piece of text with numeric characters
+ - c) A keyword used for control flow
+ - Answer: b) A piece of text with numeric characters
+3. How do you print the exact text "Hello World" on the console using System.out.println()?
+
+ - a) System.out.println("Hello World")
+ - b) System.out.println(Hello World)
+ - c) System.out.print("Hello World")
+ - Answer: a) System.out.println("Hello World")
+4. Can you pass a mathematical expression like 5 * 3 = 15 as an argument to System.out.println() in Java?
+
+ - a) Yes, it will evaluate the expression and print the result
+ - b) No, it will throw an error
+ - Answer: b) No, it will throw an error
+
+## Step 08: Programming Exercise PE-02
+## Step 09: Solutions to PE-02
+Question 1: What is the output of the following code?
+
+```
+System.out.println("Hello World");
+```
+a) HelloWorld
+b) Hello World
+c) "Hello World"
+
+Answer: b) Hello World
+
+Question 2: What is the output of the following code?
+
+```
+System.out.println("5 * 3");
+```
+a) 5 * 3
+b) 15
+c) "5 * 3"
+
+Answer: a) 5 * 3
+
+Question 3: What is the output of the following code?
+
+```
+System.out.println(5 * 3);
+```
+a) 5 * 3
+b) 15
+c) "15"
+
+
+Answer: b) 15
+
+Question 4: What is the output of the following code?
+
+```
+System.out.println(60 * 60 * 24);
+```
+a) 86400
+b) 86400.0
+c) "86400"
+
+Answer: a) 86400
+
+
+
+## Step 10: Whitespace, Case Sensitiveness and Escape Characters
+
+1. What does whitespace refer to in Java?
+
+- a) Any sequence of continuous digits.
+- b) Any sequence of continuous space, tab or newline characters.
+- c) Any sequence of continuous special symbols.
+
+Answer: b) Any sequence of continuous space, tab or newline characters.
+
+2. Why is it important to use the correct case when calling pre-defined Java elements?
+
+- a) Because Java is case-sensitive, and using the incorrect case will result in an error.
+- b) Because Java is case-insensitive, and using the incorrect case will result in an error.
+- c) Because Java is not case-sensitive, and using the incorrect case will not result in an error.
+
+Answer: a) Because Java is case-sensitive, and using the incorrect case will result in an error.
+
+3. What is the escape sequence for inserting a tab in a string literal?
+
+- a) \n
+- b) \t
+- c) \b
+
+Answer: b) \t
+
+
+## Step 11: More On Method Calls
+
+1. What is the purpose of parentheses in method calls?
+
+ - a) They are optional and can be left out
+ - b) They are used to separate individual parameters with a comma
+ - c) They enclose all the parameters and are a necessary part of the syntax
+ - **Answer: c**
+2. What does the Math.random() method do?
+
+ - a) It prints a random integer between 0 and 1
+ - b) It prints a random real number between 0 and 1
+ - c) It returns the maximum of two given numbers
+ - **Answer: b**
+3. What does the Math.min() method return?
+
+ - a) The maximum of two given numbers
+ - b) The minimum of two given numbers
+ - c) The sum of two given numbers
+ - **Answer: b**
+
+
+## Step 12: More Formatted Output
+
+1. Which method can accept a variable number of arguments?
+- a) System.out.println()
+- b) System.out.printf()
+- c) Math.min()
+
+Answer: b) System.out.printf()
+
+2. Which of the following is a predefined literal used as a format specifier in printf() to format data of type int?
+- a) %f
+- b) %d
+- c) %s
+
+Answer: b) %d
+
+3. What will be the output of the following code?
+
+```
+System.out.printf("%d + %d + %d = %d", 3, 4, 5, 3 + 4 + 5).println();
+```
+
+- a) 3 + 4 + 5 = 12
+- b) 3 4 5 = 12
+- c) 3 + 4 = 7
+
+Answer: a) 3 + 4 + 5 = 12
+
+
+## Step 13: Introducing Variables
+
+1. What is a variable in Java?
+ - a) A method to print calculated values
+ - b) A keyword to reserve memory for data
+ - c) A character to represent symbols in a string
+
+Answer: b)
+
+2. How can we change the value of a variable?
+- a) Using the System.out.printf() method
+- b) By calling a method with a different argument
+- c) By assigning a new value to it using the assignment operator =
+
+Answer: c)
+
+3. How can we use variables to simplify code?
+- a) By defining a new method
+- b) By storing the output of a method in a variable
+- c) By assigning changing values to a variable and using it in a statement
+
+Answer: c)
+
+
+## Step 15: Using Variables Quiz
+
+1. Why is it important to declare variables before using them in a Java program?
+
+ - a) It makes the code look more organized
+ - b) It ensures that the variables have values assigned to them
+ - c) It avoids errors due to uninitialized variables
+
+ Answer: c
+
+2. In Java, every variable must be declared with a __________.
+
+ - a) keyword
+ - b) value
+ - c) type
+
+ Answer: c
+
+3. What happens when you try to store a double value into an integer variable?
+
+ - a) It is allowed without any issues
+ - b) An error is generated as the types are incompatible
+ - c) The value is automatically rounded up to the nearest integer
+
+ Answer: b
+
+
+
+## Step 16: Variables: Behind-The-Scenes
+
+1. What is the process of giving a value to a variable during its declaration called?
+- A) Assignment
+- B) Initialization
+- C) Declaration
+Answer: B
+
+2. What happens when a variable's initial value is another variable previously defined?
+- A) The initial value of the first variable is lost
+- B) The value of the second variable is lost
+- C) The value stored in the first variable's slot is copied to the second variable's slot
+Answer: C
+
+3. Which of the following is not allowed in variable assignment?
+- A) From a literal value to a variable, having compatible types
+- B) From a variable to another variable, of compatible types
+- C) Assignment to a constant literal
+Answer: C
+
+
+# Step 17: Naming Variables
+
+1. Which of the following characters is allowed in a variable name in Java?
+
+- A) #
+- B) $
+- C) %
+- D) !
+
+**Answer: B)** The special character `$` is allowed in a variable name in Java.
+
+2. Which of the following variable names is not allowed in Java?
+
+- A) _score
+- B) 3goals
+- C) yellowCard
+- D) goals3
+
+**Answer: B)** A variable name cannot start with a numerical digit [0-9].
+
+3. Which of the following is a recommended naming convention for variables in Java?
+
+- A) start variable names with uppercase letters
+- B) use long variable names to make your code more expressive
+- C) use CamelCase for variable names with multiple words
+- D) use special characters like ! or % in variable names
+
+**Answer: C)** In Java, it is recommended to use CamelCase when we have multiple words in variable name.
+
+
+
+## Step 18: Java Primitive Types Quiz
+
+1. Which of the following is NOT an integral value primitive type in Java?
+- a) byte
+- b) short
+- c) float
+
+Answer: c) float
+
+2. What is the default type for floating type values in Java with size 64 bits?
+- a) double
+- b) float
+- c) int
+
+Answer: a) double
+
+3. What is the correct way to store a single character symbol in a char variable in Java?
+- a) within double quotes ""
+- b) within parentheses ()
+- c) within single quotes ''
+
+Answer: c) within single quotes ''
+
+
+## Step 19: Choosing A Data Type Quiz
+
+1. Which data type is best for storing the number of goals scored by a team in a football match?
+
+a) Byte
+b) Short
+c) Long
+
+Answer: b) Short
+
+2. Which data type is best for storing the average rainfall in a month?
+
+a) Int
+b) Float
+c) Double
+
+Answer: c) Double
+
+3. Which data type is best for storing the grade of a student in a class?
+
+a) Int
+b) Char
+c) Float
+
+Answer: b) Char
+
+
+
+## Step 20: Assignment Operator Quiz
+
+1. What is the assignment operator in Java?
+
+- a) ==
+- b) =
+- c) +
+
+Answer: b) =
+
+2. What is the output of the following code: `int x = 5; x = x + 3;`
+
+- a) 3
+- b) 8
+- c) 5
+
+Answer: b) 8
+
+3. What is the result of the following code: `int y = 10; y = y - 2; y = y - 3;`
+
+- a) 3
+- b) 10
+- c) 5
+
+Answer: c) 5
+
+
+
+
+## Step 21: Java Operators
+
+1. What is the difference between prefix and postfix versions of increment and decrement operators?
+- a) There is no difference between prefix and postfix versions.
+- b) Prefix version returns the updated value while postfix returns the original value.
+- c) Postfix version returns the updated value while prefix returns the original value.
+
+Answer: b) Prefix version returns the updated value while postfix returns the original value.
+
+2. What is the compound assignment operator used for?
+- a) To assign a new value to a variable.
+- b) To combine the = with a numeric operator.
+- c) To compare two values.
+
+Answer: b) To combine the = with a numeric operator.
+
+3. What does the expression i %= 2 mean?
+- a) Add 2 to the value of i and store the result back into i.
+- b) Divide i by 2, and store the result back into i.
+- c) Divide i by 2, and store the remainder back into i.
+
+Answer: c) Divide i by 2, and store the remainder back into i.
+
+
+
+# Step 23: Introducing Conditionals - the if
+
+1. Which is the correct comparison operator in Java?
+
+- =
+- ==
+
+Answer: ==
+
+2. What is the structure of an if statement in Java?
+
+- if {condition} (statement);
+- if {statement} (condition);
+- if (condition) {statement};
+
+Answer: if (condition) {statement};
+
+3. What is the output of the following code:
+
+```
+int a = 5;
+int b = 10;
+if (a > b) {
+ System.out.println("a is greater than b");
+} else {
+ System.out.println("b is greater than a");
+}
+```
+
+- a is greater than b
+- b is greater than a
+
+Answer: b is greater than a
+
+
+
+
+## Step 26: `if` Statement again
+
+1. What is the output of the following code snippet?
+
+```
+int x = 7;
+if (x < 10) {
+ System.out.println("x is less than 10");
+}
+else {
+ System.out.println("x is greater than or equal to 10");
+}
+```
+
+A. x is less than 10
+B. x is greater than or equal to 10
+C. Compiler Error
+
+Answer: A
+
+2. What happens when we don't use statement blocks with if conditional?
+
+A. The condition statement only controls the execution of the first statement.
+B. The condition statement controls the execution of all the statements.
+C. The code will not compile.
+
+Answer: A
+
+3. What is the benefit of using statement blocks with if conditionals?
+
+A. Improves code readability
+B. Increases the number of statements that can be executed conditionally
+C. Improves program efficiency
+
+Answer: A
+
+
+
+## Step 27: Introducing Loops: The `for` Statement
+
+1. What does a for loop iterate over?
+- a) a fixed number of iterations
+- b) an infinite number of times
+- c) a variable number of times **Answer: c**
+
+2. What is the syntax of a for loop?
+- a) for (initialization; update; condition)
+- b) for (update; condition; initialization)
+- c) for (condition; initialization; update) **Answer: a**
+
+
+
+# Step 28-29
+
+1. What is the output of the following code snippet?
+
+```
+for (int i=0; i<=10; i++) {
+ System.out.printf("%d * %d = %d", 6, i, 6*i).println();
+}
+```
+
+a. Multiplication table of 6
+b. Multiplication table of 10
+c. Multiplication table of 7
+
+**Answer: a. Multiplication table of 6**
+
+2. What is the output of the following code snippet?
+
+```
+for (int i=1; i<=10; i++) {
+ System.out.printf(i*i).println();
+}
+```
+
+a. The squares of integers from 1 to 10
+b. The squares of first 10 even integers
+c. The squares of first 10 odd integers
+
+**Answer: a. The squares of integers from 1 to 10**
+
+3. What is the output of the following code snippet?
+
+```
+for (int i=10; i>0; i--) {
+ System.out.printf(i).println();
+}
+```
+
+a. The integers from 10 to 1
+b. The integers from 1 to 10
+c. The squares of integers from 1 to 10 in reverse order
+
+**Answer: a. The integers from 10 to 1**
+
+
+
+## Step 30: Puzzling You With `for`
+
+#### 1. Which of the following is true about the for loop construct in Java?
+
+- A) All components of the for loop are required.
+- B) Only the condition component of the for loop is optional.
+- C) All components of the for loop are optional.
+
+Answer: C) All components of the for loop are optional.
+
+#### 2. What happens if the condition component of a for loop is left empty?
+
+- A) The loop continues indefinitely until stopped externally.
+- B) The loop exits immediately without executing any statements.
+- C) The loop executes once and exits immediately.
+
+Answer: A) The loop continues indefinitely until stopped externally.
+
+#### 3. What is the output of the following code snippet?
+
+```
+int i = 1;
+for (; i <= 10; i++);
+System.out.println(i);
+```
+
+- A) 1
+- B) 10
+- C) 11
+
+Answer: C) 11
\ No newline at end of file
From 942c26dc3aeb451ab162966ddfd82ac5460d5522 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sun, 26 Mar 2023 17:19:06 +0530
Subject: [PATCH 078/178] .
---
...troductionToJavaProgrammingWithJShell-MultiplicationTable.md | 2 +-
...troductionToJavaProgrammingWithJShell-MultiplicationTable.md | 2 +-
2 files changed, 2 insertions(+), 2 deletions(-)
diff --git a/01-Quiz/Q01-IntroductionToJavaProgrammingWithJShell-MultiplicationTable.md b/01-Quiz/Q01-IntroductionToJavaProgrammingWithJShell-MultiplicationTable.md
index c43b44b9..1e6ba027 100644
--- a/01-Quiz/Q01-IntroductionToJavaProgrammingWithJShell-MultiplicationTable.md
+++ b/01-Quiz/Q01-IntroductionToJavaProgrammingWithJShell-MultiplicationTable.md
@@ -1,4 +1,4 @@
-## Java Multiple Choice Quiz
+## Introduction to Programming with Print-Multiplication-Table - MCQ
## Step 02: Introducing JShell
diff --git a/02-CodeChallenge/01-IntroductionToJavaProgrammingWithJShell-MultiplicationTable.md b/02-CodeChallenge/01-IntroductionToJavaProgrammingWithJShell-MultiplicationTable.md
index e95c389c..b37db216 100644
--- a/02-CodeChallenge/01-IntroductionToJavaProgrammingWithJShell-MultiplicationTable.md
+++ b/02-CodeChallenge/01-IntroductionToJavaProgrammingWithJShell-MultiplicationTable.md
@@ -1,4 +1,4 @@
-## Java Code Challenge
+## Introduction to Programming with Print-Multiplication-Table
### Step 02: Introducing JShell
From 7f188b85b1ac1568cc8861c719b71367bf0fcc94 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Tue, 28 Mar 2023 10:25:41 +0530
Subject: [PATCH 079/178] .
---
...troductionToMethods-MultiplicationTable.md | 69 +++++++++++++++++++
1 file changed, 69 insertions(+)
create mode 100644 02-CodeChallenge/02-IntroductionToMethods-MultiplicationTable.md
diff --git a/02-CodeChallenge/02-IntroductionToMethods-MultiplicationTable.md b/02-CodeChallenge/02-IntroductionToMethods-MultiplicationTable.md
new file mode 100644
index 00000000..b20099aa
--- /dev/null
+++ b/02-CodeChallenge/02-IntroductionToMethods-MultiplicationTable.md
@@ -0,0 +1,69 @@
+### Step 01 : Defining A Simple Method
+### Step 02: Exercise-Set PE-01
+
+### Exercise 1
+
+1. Launch JShell
+2. Define a method named `printHello` that prints the string "Hello" to the console.
+3. Call the `printHello` method.
+4. Exit JShell using `/exit` command.
+
+#### Solution 1
+
+1. Launch JShell
+
+2. Define a method named `printHello` that prints the string "Hello" to the console:
+
+```
+jshell> void printHello() {
+ ...> System.out.println("Hello");
+ ...> }
+```
+
+3. Call the `printHello` method:
+
+```
+jshell> printHello();
+Hello
+```
+
+4. Exit JShell using `/exit` command:
+```
+jshell> /exit
+```
+
+### Exercise 2
+
+1. Launch JShell
+2. Define a method named `printNumbers` that prints the numbers 1 to 5 to the console, each on a new line.
+3. Call the `printNumbers` method.
+4. Exit JShell using `/exit` command.
+
+### Solution 2
+
+1. Launch JShell
+
+2. Define a method named `printNumbers` that prints the numbers 1 to 5 to the console, each on a new line:
+
+```
+jshell> void printNumbers() {
+ ...> for (int i = 1; i <= 5; i++) {
+ ...> System.out.println(i);
+ ...> }
+ ...> }
+ ```
+
+3. Call the `printNumbers` method:
+```
+jshell> printNumbers();
+1
+2
+3
+4
+5
+```
+
+4. Exit JShell using `/exit` command:
+```
+jshell> /exit
+```
\ No newline at end of file
From 58cbb7f02f77af3638405446bff22540f35d505f Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Tue, 28 Mar 2023 10:32:24 +0530
Subject: [PATCH 080/178] .
---
...troductionToMethods-MultiplicationTable.md | 114 ++++++++++++++++++
1 file changed, 114 insertions(+)
diff --git a/02-CodeChallenge/02-IntroductionToMethods-MultiplicationTable.md b/02-CodeChallenge/02-IntroductionToMethods-MultiplicationTable.md
index b20099aa..84049ad6 100644
--- a/02-CodeChallenge/02-IntroductionToMethods-MultiplicationTable.md
+++ b/02-CodeChallenge/02-IntroductionToMethods-MultiplicationTable.md
@@ -66,4 +66,118 @@ jshell> printNumbers();
4. Exit JShell using `/exit` command:
```
jshell> /exit
+```
+
+
+
+
+
+
+
+
+
+#### Exercise 1: Editing a Method Definition in JShell
+
+1. Launch JShell.
+2. Define a method called `printMessage` that prints the message "Hello, World!" to the console.
+3. Call the `printMessage` method to verify that it works.
+4. Modify the `printMessage` method so that it prints a different message.
+5. Call the `printMessage` method again to verify that it now prints the new message.
+6. Exit JShell using the `/exit` command.
+
+##### Solution
+
+1. Launch JShell.
+
+```
+jshell>
+```
+
+2. Define a method called `printMessage` that prints the message "Hello, World!" to the console.
+
+```
+jshell> void printMessage() {
+ ...> System.out.println("Hello, World!");
+ ...> }
+ ```
+
+3. Call the `printMessage` method to verify that it works.
+
+```
+jshell> printMessage();
+Hello, World!
+```
+
+4. Modify the `printMessage` method so that it prints a different message.
+
+```
+jshell> void printMessage() {
+ ...> System.out.println("Goodbye, World!");
+ ...> }
+ ```
+
+5. Call the `printMessage` method again to verify that it now prints the new message.
+
+```
+jshell> printMessage();
+Goodbye, World!
+```
+
+6. Exit JShell using the `/exit` command.
+
+```
+jshell> /exit
+| Goodbye
+```
+
+### Step 03: Editing A Method Definition (Jshell Tips)
+
+
+#### Exercise 2
+
+1. Launch JShell
+2. Define a method called `greet` that prints the message `"Welcome to JShell!"` to the console.
+3. Call the `greet` method.
+4. Define a method called `printName` that prints your name to the console.
+5. Call the `printName` method.
+6. Exit JShell using the `/exit` command.
+
+##### Solution
+
+1. Launch JShell.
+2. Define a method called `greet` that prints the message `"Welcome to JShell!"` to the console.
+
+```
+jshell> void greet() {
+ ...> System.out.println("Welcome to JShell!");
+ ...> }
+ ```
+
+3. Call the `greet` method.
+
+```
+jshell> greet();
+Welcome to JShell!
+```
+
+4. Define a method called `printName` that prints your name to the console.
+
+```
+jshell> void printName() {
+ ...> System.out.println("My name is Deb.");
+ ...> }
+ ```
+
+5. Call the `printName` method.
+
+```
+jshell> printName();
+My name is Deb.
+```
+
+6. Exit JShell using the `/exit` command.
+
+```
+jshell> /exit
+| Goodbye
```
\ No newline at end of file
From 8d1d3990b542717da72bf97bdd4f31384df2331e Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Tue, 28 Mar 2023 10:33:41 +0530
Subject: [PATCH 081/178] .
---
.../02-IntroductionToMethods-MultiplicationTable.md | 3 +--
1 file changed, 1 insertion(+), 2 deletions(-)
diff --git a/02-CodeChallenge/02-IntroductionToMethods-MultiplicationTable.md b/02-CodeChallenge/02-IntroductionToMethods-MultiplicationTable.md
index 84049ad6..f0e65eb4 100644
--- a/02-CodeChallenge/02-IntroductionToMethods-MultiplicationTable.md
+++ b/02-CodeChallenge/02-IntroductionToMethods-MultiplicationTable.md
@@ -70,7 +70,7 @@ jshell> /exit
-
+### Step 03: Editing A Method Definition (Jshell Tips)
@@ -130,7 +130,6 @@ jshell> /exit
| Goodbye
```
-### Step 03: Editing A Method Definition (Jshell Tips)
#### Exercise 2
From 7aa5189e35571b5c3b885a4fe0c8a9e9ce1ca552 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Tue, 28 Mar 2023 10:38:31 +0530
Subject: [PATCH 082/178] .
---
...troductionToMethods-MultiplicationTable.md | 39 ++++++++++++-------
1 file changed, 24 insertions(+), 15 deletions(-)
diff --git a/02-CodeChallenge/02-IntroductionToMethods-MultiplicationTable.md b/02-CodeChallenge/02-IntroductionToMethods-MultiplicationTable.md
index f0e65eb4..ceccbc2a 100644
--- a/02-CodeChallenge/02-IntroductionToMethods-MultiplicationTable.md
+++ b/02-CodeChallenge/02-IntroductionToMethods-MultiplicationTable.md
@@ -132,23 +132,26 @@ jshell> /exit
-#### Exercise 2
-1. Launch JShell
-2. Define a method called `greet` that prints the message `"Welcome to JShell!"` to the console.
+#### Exercise: Editing A Method Definition in JShell
+
+1. Launch JShell.
+2. Define a method called `greet` that prints the message "Welcome to JShell!" to the console.
3. Call the `greet` method.
-4. Define a method called `printName` that prints your name to the console.
-5. Call the `printName` method.
+4. Edit the `greet` method to print "Hello, JShell!" to the console instead.
+5. Call the `greet` method again to verify that it has been updated.
6. Exit JShell using the `/exit` command.
##### Solution
1. Launch JShell.
-2. Define a method called `greet` that prints the message `"Welcome to JShell!"` to the console.
+
+2. Define a method called `greet` that prints the message "Welcome to JShell!" to the console.
+
```
jshell> void greet() {
- ...> System.out.println("Welcome to JShell!");
+ ...> System.out.println("Welcome to JShell!");
...> }
```
@@ -159,19 +162,25 @@ jshell> greet();
Welcome to JShell!
```
-4. Define a method called `printName` that prints your name to the console.
+4. Edit the `greet` method to print "Hello, JShell!" to the console instead.
```
-jshell> void printName() {
- ...> System.out.println("My name is Deb.");
- ...> }
- ```
+jshell> /edit greet
+```
-5. Call the `printName` method.
+This will open the method definition in an external editor. Replace the line that prints "Welcome to JShell!" with the following line:
```
-jshell> printName();
-My name is Deb.
+System.out.println("Hello, JShell!");
+```
+
+Save the changes and close the editor.
+
+5. Call the `greet` method again to verify that it has been updated.
+
+```
+jshell> greet();
+Hello, JShell!
```
6. Exit JShell using the `/exit` command.
From 4b62fb6ebfcb7d63730c4a203f9908c1960559da Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Tue, 28 Mar 2023 10:38:43 +0530
Subject: [PATCH 083/178] .
---
.../02-IntroductionToMethods-MultiplicationTable.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/02-CodeChallenge/02-IntroductionToMethods-MultiplicationTable.md b/02-CodeChallenge/02-IntroductionToMethods-MultiplicationTable.md
index ceccbc2a..f316cd39 100644
--- a/02-CodeChallenge/02-IntroductionToMethods-MultiplicationTable.md
+++ b/02-CodeChallenge/02-IntroductionToMethods-MultiplicationTable.md
@@ -133,7 +133,7 @@ jshell> /exit
-#### Exercise: Editing A Method Definition in JShell
+#### Exercise 2: Editing A Method Definition in JShell
1. Launch JShell.
2. Define a method called `greet` that prints the message "Welcome to JShell!" to the console.
From d149c3ad55eab27a9bc25f139255f3db4fff9620 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Tue, 28 Mar 2023 11:09:41 +0530
Subject: [PATCH 084/178] .
---
...troductionToMethods-MultiplicationTable.md | 251 +++++++++++++++++-
1 file changed, 250 insertions(+), 1 deletion(-)
diff --git a/02-CodeChallenge/02-IntroductionToMethods-MultiplicationTable.md b/02-CodeChallenge/02-IntroductionToMethods-MultiplicationTable.md
index f316cd39..17d22b22 100644
--- a/02-CodeChallenge/02-IntroductionToMethods-MultiplicationTable.md
+++ b/02-CodeChallenge/02-IntroductionToMethods-MultiplicationTable.md
@@ -188,4 +188,253 @@ Hello, JShell!
```
jshell> /exit
| Goodbye
-```
\ No newline at end of file
+```
+
+
+
+### Step 04: Methods with Arguments
+### Step 05: Exercise Set PE-02 (With Solutions)
+
+
+
+#### Exercise 1: Creating and Calling a Method with a Single Argument
+
+1. Launch JShell.
+2. Define a method called `printTwice` that takes in a `String` parameter and prints it twice to the console, with a space in between.
+3. Call the `printTwice` method with the argument `"Hello"`.
+4. Call the `printTwice` method with the argument `"Java"`.
+5. Exit JShell using the `/exit` command.
+
+##### Solution
+
+1. Launch JShell.
+
+2. Define the `printTwice` method with a `String` parameter:
+
+ ```
+ jshell> void printTwice(String message) {
+ ...> System.out.println(message + " " + message);
+ ...> }
+ ```
+
+3. Call the `printTwice` method with the argument `"Hello"`:
+
+```
+jshell> printTwice("Hello");
+ Hello Hello
+```
+
+4. Call the `printTwice` method with the argument `"Java"`:
+
+ ```
+ jshell> printTwice("Java");
+ Java Java
+```
+
+5. Exit JShell using the `/exit` command:
+
+```
+ jshell> /exit
+ | Goodbye
+```
+
+
+#### Exercise 2: Simple Method with an Integer Parameter
+
+1. Launch JShell.
+2. Define a method called `doubleNumber` that takes an `int` parameter called `num`. The method should print the result of doubling `num` to the console using `System.out.println()`.
+3. Call the `doubleNumber` method with the argument `5`.
+4. Call the `doubleNumber` method with the argument `-3`.
+5. Exit JShell using the `/exit` command.
+
+##### Solution
+
+1. Launch JShell.
+2. Define a method called `doubleNumber` that takes an `int` parameter called `num`. The method should print the result of doubling `num` to the console using `System.out.println()`:
+
+```
+jshell> void doubleNumber(int num) {
+ ...> System.out.println("Double of " + num + " is " + (num * 2));
+ ...> }
+ ```
+
+3. Call the `doubleNumber` method with the argument `5`:
+
+```
+jshell> doubleNumber(5);
+Double of 5 is 10
+```
+
+4. Call the `doubleNumber` method with the argument `-3`:
+
+```
+jshell> doubleNumber(-3);
+Double of -3 is -6
+```
+
+5. Exit JShell using the `/exit` command:
+
+```
+jshell> /exit
+| Goodbye
+```
+
+
+### Step 07: _PMT-Challenge_ Revisited (And Some Puzzles)
+
+#### Exercise 1: Printing a Multiplication Table with a Method in JShell
+
+1. Launch JShell.
+2. Define a method called `printMultiplicationTable` that takes an `int` parameter called `number`. The method should print the multiplication table of the given number up to 10. Each line of the table should be printed in the format `number * i = result`, where `i` is the number being multiplied by `number`, and `result` is the product of the multiplication.
+3. Call the `printMultiplicationTable` method with the argument `5`.
+4. Call the `printMultiplicationTable` method with the argument `9`.
+5. Exit JShell using the `/exit` command.
+
+##### Solution
+
+1. Launch JShell.
+2. Define a method called `printMultiplicationTable` that takes an `int` parameter called `number`. The method should print the multiplication table of the given number up to 10. Each line of the table should be printed in the format `number * i = result`, where `i` is the number being multiplied by `number`, and `result` is the product of the multiplication.
+
+```
+jshell> void printMultiplicationTable(int number) {
+ ...> for (int i = 1; i <= 10; i++) {
+ ...> System.out.printf("%d * %d = %d\n", number, i, number * i);
+ ...> }
+ ...> }
+ ```
+
+3. Call the `printMultiplicationTable` method with the argument `5`.
+
+```
+jshell> printMultiplicationTable(5);
+5 * 1 = 5
+5 * 2 = 10
+5 * 3 = 15
+5 * 4 = 20
+5 * 5 = 25
+5 * 6 = 30
+5 * 7 = 35
+5 * 8 = 40
+5 * 9 = 45
+5 * 10 = 50
+```
+
+4. Call the `printMultiplicationTable` method with the argument `9`.
+
+```
+jshell> printMultiplicationTable(9);
+9 * 1 = 9
+9 * 2 = 18
+9 * 3 = 27
+9 * 4 = 36
+9 * 5 = 45
+9 * 6 = 54
+9 * 7 = 63
+9 * 8 = 72
+9 * 9 = 81
+9 * 10 = 90
+```
+
+5. Exit JShell using the `/exit` command.
+
+```
+jshell> /exit
+| Goodbye
+```
+
+
+#### Exercise 2: Printing Even Numbers using a Method with a Parameter
+
+1. Launch JShell.
+2. Define a method called `printEvenNumber` that takes an integer parameter.
+3. In the method, use a for loop to iterate from 1 to the parameter value.
+4. Within the loop, use an `if` statement to check if the current number is even.
+5. If the number is even, print it to the console using `System.out.println()`.
+6. Call the `printEvenNumber` method with the argument `10`.
+7. Call the `printEvenNumber` method again with the argument `20`.
+8. Exit JShell using the `/exit` command.
+
+#### Solution
+
+1. Launch JShell.
+
+```
+$ jshell
+| Welcome to JShell -- Version 11.0.10
+| For an introduction type: /help intro
+```
+
+2. Define a method called `printEvenNumber` that takes an integer parameter.
+
+```
+jshell> void printEvenNumber(int number) {
+ ...> }
+ ```
+
+3. In the method, use a for loop to iterate from 1 to the parameter value.
+
+```
+jshell> void printEvenNumber(int number) {
+ ...> for (int i = 1; i <= number; i++) {
+ ...> }
+ ...> }
+ ```
+
+4. Within the loop, use an `if` statement to check if the current number is even.
+
+```
+jshell> void printEvenNumber(int number) {
+ ...> for (int i = 1; i <= number; i++) {
+ ...> if (i % 2 == 0) {
+ ...> }
+ ...> }
+ ...> }
+ ```
+
+5. If the number is even, print it to the console using `System.out.println()`.
+
+```
+jshell> void printEvenNumber(int number) {
+ ...> for (int i = 1; i <= number; i++) {
+ ...> if (i % 2 == 0) {
+ ...> System.out.println(i);
+ ...> }
+ ...> }
+ ...> }
+ ```
+
+6. Call the `printEvenNumber` method with an integer parameter `10`.
+
+```
+jshell> printEvenNumber(10);
+2
+4
+6
+8
+10
+```
+
+7. Call the `printEvenNumber` method again with a different integer parameter `20`.
+
+```
+jshell> printEvenNumber(20);
+2
+4
+6
+8
+10
+12
+14
+16
+18
+20
+```
+
+8. Exit JShell using the `/exit` command.
+
+```
+jshell> /exit
+| Goodbye
+```
+
+
From b4cd7cdee065e228e8fad8efaf0136123e6715f5 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Tue, 28 Mar 2023 11:17:37 +0530
Subject: [PATCH 085/178] .
---
...troductionToMethods-MultiplicationTable.md | 120 ++++++++++++++++++
1 file changed, 120 insertions(+)
diff --git a/02-CodeChallenge/02-IntroductionToMethods-MultiplicationTable.md b/02-CodeChallenge/02-IntroductionToMethods-MultiplicationTable.md
index 17d22b22..6f2034de 100644
--- a/02-CodeChallenge/02-IntroductionToMethods-MultiplicationTable.md
+++ b/02-CodeChallenge/02-IntroductionToMethods-MultiplicationTable.md
@@ -438,3 +438,123 @@ jshell> /exit
```
+### Step 08: Methods With Arguments, And Overloading
+
+#### Exercise 1: Method Overloading
+
+1. Launch JShell
+2. Create a Java method called `printNumber` that takes an integer argument and prints it to the console.
+3. Overload the `printNumber` method with another method that takes a double argument and prints it to the console.
+4. Overload the `printNumber` method with another method that takes a string argument and prints it to the console.
+5. Call each of the `printNumber` methods with an appropriate argument.
+6. Exit JShell using the `/exit` command.
+
+##### Solution
+
+1. Launch JShell.
+2. Create a Java method called `printNumber` that takes an integer argument and prints it to the console:
+
+```
+jshell> void printNumber(int num) {
+ ...> System.out.println("The number is: " + num);
+ ...> }
+ ```
+
+3. Overload the `printNumber` method with another method that takes a double argument and prints it to the console:
+
+```
+jshell> void printNumber(double num) {
+ ...> System.out.println("The number is: " + num);
+ ...> }
+ ```
+
+4. Overload the `printNumber` method with another method that takes a string argument and prints it to the console:
+
+```
+jshell> void printNumber(String str) {
+ ...> System.out.println("The string is: " + str);
+ ...> }
+ ```
+
+5. Call each of the `printNumber` methods with an appropriate argument:
+
+```
+jshell> printNumber(10);
+The number is: 10
+
+jshell> printNumber(10.5);
+The number is: 10.5
+
+jshell> printNumber("Hello World");
+The string is: Hello World
+```
+
+6. Exit JShell using the `/exit` command:
+
+```
+jshell> /exit
+| Goodbye
+```
+
+#### Exercise: 2
+
+1. Launch JShell
+2. Define a method called `printHelloWorld()` that prints the message "Hello, World!" to the console.
+3. Define an overloaded method called `printHelloWorld(int number)` that prints the message "Hello, World!" to the console `number` times.
+4. Call the `printHelloWorld()` method.
+5. Call the `printHelloWorld(int number)` method with `number` equal to 3.
+6. Exit JShell using the `/exit` command.
+
+##### Solution:
+
+1. Launch JShell
+2. Define a method called `printHelloWorld()` that prints the message "Hello, World!" to the console.
+
+```
+void printHelloWorld() {
+ System.out.println("Hello, World!");
+}
+```
+
+3. Define an overloaded method called `printHelloWorld(int number)` that prints the message "Hello, World!" to the console `number` times.
+
+```
+void printHelloWorld(int number) {
+ for (int i = 0; i < number; i++) {
+ System.out.println("Hello, World!");
+ }
+}
+```
+
+4. Call the `printHelloWorld()` method.
+
+```
+printHelloWorld();
+```
+
+Output:
+
+```
+Hello, World!
+```
+
+5. Call the `printHelloWorld(int number)` method with `number` equal to 3.
+
+```
+printHelloWorld(3);
+```
+
+Output:
+
+```
+Hello, World!
+Hello, World!
+Hello, World!
+```
+
+6. Exit JShell using the `/exit` command.
+
+```
+/exit
+| Goodbye
+```
\ No newline at end of file
From fe2723ba797d40fd76e805096e265064467e50eb Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Tue, 28 Mar 2023 11:27:47 +0530
Subject: [PATCH 086/178] .
---
...troductionToMethods-MultiplicationTable.md | 84 ++++++++++++++++++-
1 file changed, 83 insertions(+), 1 deletion(-)
diff --git a/02-CodeChallenge/02-IntroductionToMethods-MultiplicationTable.md b/02-CodeChallenge/02-IntroductionToMethods-MultiplicationTable.md
index 6f2034de..227c5d29 100644
--- a/02-CodeChallenge/02-IntroductionToMethods-MultiplicationTable.md
+++ b/02-CodeChallenge/02-IntroductionToMethods-MultiplicationTable.md
@@ -557,4 +557,86 @@ Hello, World!
```
/exit
| Goodbye
-```
\ No newline at end of file
+```
+
+
+
+### Step 09: Methods With Multiple Arguments
+
+#### Exercise 1: Methods with Multiple Arguments in JShell
+
+1. Launch JShell.
+2. Define a method called `calculateSum` that takes in two `int` arguments and calculates and prints their sum.
+3. Define another method called `calculateAverage` that takes in three `double` arguments and calculates and prints their average.
+4. Call the `calculateSum` method with two `int` arguments.
+5. Call the `calculateAverage` method with three `double` arguments.
+6. Exit JShell using the `/exit` command.
+
+##### Solution
+
+1. Launch JShell.
+
+2. Define a method called `calculateSum` that takes in two `int` arguments and calculates and prints their sum.
+
+
+```
+jshell> void calculateSum(int num1, int num2) {
+ ...> int sum = num1 + num2;
+ ...> System.out.println("The sum of " + num1 + " and " + num2 + " is " + sum);
+ ...> }
+ ```
+
+3. Define another method called `calculateAverage` that takes in three `double` arguments and calculates and prints their average.
+
+```
+jshell> void calculateAverage(double num1, double num2, double num3) {
+ ...> double avg = (num1 + num2 + num3) / 3.0;
+ ...> System.out.println("The average of " + num1 + ", " + num2 + ", and " + num3 + " is " + avg);
+ ...> }
+ ```
+
+4. Call the `calculateSum` method with two `int` arguments.
+
+```
+jshell> calculateSum(5, 7);
+The sum of 5 and 7 is 12
+```
+
+5. Call the `calculateAverage` method with three `double` arguments.
+
+```
+jshell> calculateAverage(3.5, 6.8, 9.1);
+The average of 3.5, 6.8, and 9.1 is 6.466666666666666
+```
+
+6. Exit JShell using the `/exit` command.
+
+```
+jshell> /exit
+| Goodbye
+```
+
+
+#### Exercise 2
+
+Problem: Write a method called `printMessage` that takes a string message and an integer count as parameters, and prints the message count times to the console. Then, call the `printMessage` method with a string message of your choice and an integer count of your choice.
+
+Solution:
+
+```
+1. Launch JShell
+2. Define a method called `printMessage` that takes a string message and an integer count as parameters, and prints the message count times to the console:
+ jshell> void printMessage(String message, int count) {
+ for (int i = 1; i <= count; i++) {
+ System.out.println(message);
+ }
+ }
+3. Call the `printMessage` method with a string message of your choice and an integer count of your choice:
+ jshell> printMessage("Hello, world!", 3)
+ Hello, world!
+ Hello, world!
+ Hello, world!
+4. Exit JShell using the `/exit` command.
+```
+
+Note: In this example, the `printMessage` method takes two parameters - a string message and an integer count. Inside the method, we use a for loop to print the message count times to the console. Finally, we call the `printMessage` method with the string message "Hello, world!" and the integer count 3.
\ No newline at end of file
From 81df5f5d9b930de5eba0043e6868cc8f3eda379b Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Tue, 28 Mar 2023 11:36:21 +0530
Subject: [PATCH 087/178] .
---
...troductionToMethods-MultiplicationTable.md | 64 ++++++++++++++++++-
1 file changed, 63 insertions(+), 1 deletion(-)
diff --git a/02-CodeChallenge/02-IntroductionToMethods-MultiplicationTable.md b/02-CodeChallenge/02-IntroductionToMethods-MultiplicationTable.md
index 227c5d29..60f3876e 100644
--- a/02-CodeChallenge/02-IntroductionToMethods-MultiplicationTable.md
+++ b/02-CodeChallenge/02-IntroductionToMethods-MultiplicationTable.md
@@ -639,4 +639,66 @@ Solution:
4. Exit JShell using the `/exit` command.
```
-Note: In this example, the `printMessage` method takes two parameters - a string message and an integer count. Inside the method, we use a for loop to print the message count times to the console. Finally, we call the `printMessage` method with the string message "Hello, world!" and the integer count 3.
\ No newline at end of file
+Note: In this example, the `printMessage` method takes two parameters - a string message and an integer count. Inside the method, we use a for loop to print the message count times to the console. Finally, we call the `printMessage` method with the string message "Hello, world!" and the integer count 3.
+
+
+
+### Step 10: Returning From A Method
+
+#### Exercise 1
+
+Write a method called `calculateSum` that takes two integer parameters and returns their sum. Then, call the `calculateSum` method with two integer arguments of your choice and print the result to the console.
+
+Solution:
+
+1. Launch JShell.
+2. Define a method called `calculateSum` that takes two integer parameters and returns their sum:
+
+```
+jshell> int calculateSum(int a, int b) {
+ return a + b;
+ }
+```
+
+3. Call the `calculateSum` method with two integer arguments of your choice and print the result to the console:
+
+```
+jshell> int result = calculateSum(5, 7);
+ System.out.println(result);
+```
+ Output: `12`
+4. Exit JShell using the `/exit` command.
+
+Note: In this example, we define a method called `calculateSum` that takes two integer parameters `a` and `b`. Inside the method, we return the sum of `a` and `b`. Finally, we call the `calculateSum` method with two integer arguments `5` and `7` and store the result in a variable named `result`. Then we print the `result` variable to the console using the `System.out.println()` method.
+
+
+
+#### Exercise 2
+
+Write a method called `sumNumbers` that takes an integer `n` as a parameter and returns the sum of the first `n` natural numbers.
+
+Solution:
+
+1. Launch JShell.
+2. Define a method called `sumNumbers` that takes an integer `n` as a parameter and returns the sum of the first `n` natural numbers:
+
+```
+jshell> int sumNumbers(int n) {
+ int sum = 0;
+ for (int i = 1; i <= n; i++) {
+ sum += i;
+ }
+ return sum;
+ }
+```
+
+3. Call the `sumNumbers` method with an integer `n` of your choice:
+
+```
+jshell> sumNumbers(10)
+ $1 ==> 55
+```
+
+4. Exit JShell using the `/exit` command.
+
+Note: In this example, the `sumNumbers` method takes an integer `n` as a parameter and returns the sum of the first `n` natural numbers using a for loop. We call the `sumNumbers` method with an integer `n` of 10 and it returns the sum of the first 10 natural numbers, which is 55.
\ No newline at end of file
From ba759dab1648aff2de2164af84b4d6b311030f27 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Wed, 29 Mar 2023 11:16:20 +0530
Subject: [PATCH 088/178] .
---
...troductionToMethods-MultiplicationTable.md | 61 +------------------
1 file changed, 1 insertion(+), 60 deletions(-)
diff --git a/02-CodeChallenge/02-IntroductionToMethods-MultiplicationTable.md b/02-CodeChallenge/02-IntroductionToMethods-MultiplicationTable.md
index 60f3876e..7de4b1de 100644
--- a/02-CodeChallenge/02-IntroductionToMethods-MultiplicationTable.md
+++ b/02-CodeChallenge/02-IntroductionToMethods-MultiplicationTable.md
@@ -74,66 +74,7 @@ jshell> /exit
-
-
-#### Exercise 1: Editing a Method Definition in JShell
-
-1. Launch JShell.
-2. Define a method called `printMessage` that prints the message "Hello, World!" to the console.
-3. Call the `printMessage` method to verify that it works.
-4. Modify the `printMessage` method so that it prints a different message.
-5. Call the `printMessage` method again to verify that it now prints the new message.
-6. Exit JShell using the `/exit` command.
-
-##### Solution
-
-1. Launch JShell.
-
-```
-jshell>
-```
-
-2. Define a method called `printMessage` that prints the message "Hello, World!" to the console.
-
-```
-jshell> void printMessage() {
- ...> System.out.println("Hello, World!");
- ...> }
- ```
-
-3. Call the `printMessage` method to verify that it works.
-
-```
-jshell> printMessage();
-Hello, World!
-```
-
-4. Modify the `printMessage` method so that it prints a different message.
-
-```
-jshell> void printMessage() {
- ...> System.out.println("Goodbye, World!");
- ...> }
- ```
-
-5. Call the `printMessage` method again to verify that it now prints the new message.
-
-```
-jshell> printMessage();
-Goodbye, World!
-```
-
-6. Exit JShell using the `/exit` command.
-
-```
-jshell> /exit
-| Goodbye
-```
-
-
-
-
-#### Exercise 2: Editing A Method Definition in JShell
+#### Exercise 1: Editing A Method Definition in JShell
1. Launch JShell.
2. Define a method called `greet` that prints the message "Welcome to JShell!" to the console.
From 82440b01d294c285ccc15d62c866df639aab352f Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Wed, 29 Mar 2023 11:26:32 +0530
Subject: [PATCH 089/178] .
---
...troductionToMethods-MultiplicationTable.md | 85 ++++++++-----------
1 file changed, 35 insertions(+), 50 deletions(-)
diff --git a/02-CodeChallenge/02-IntroductionToMethods-MultiplicationTable.md b/02-CodeChallenge/02-IntroductionToMethods-MultiplicationTable.md
index 7de4b1de..6d21eb42 100644
--- a/02-CodeChallenge/02-IntroductionToMethods-MultiplicationTable.md
+++ b/02-CodeChallenge/02-IntroductionToMethods-MultiplicationTable.md
@@ -223,65 +223,50 @@ jshell> /exit
### Step 07: _PMT-Challenge_ Revisited (And Some Puzzles)
+
#### Exercise 1: Printing a Multiplication Table with a Method in JShell
-1. Launch JShell.
-2. Define a method called `printMultiplicationTable` that takes an `int` parameter called `number`. The method should print the multiplication table of the given number up to 10. Each line of the table should be printed in the format `number * i = result`, where `i` is the number being multiplied by `number`, and `result` is the product of the multiplication.
-3. Call the `printMultiplicationTable` method with the argument `5`.
-4. Call the `printMultiplicationTable` method with the argument `9`.
-5. Exit JShell using the `/exit` command.
+Write a void method called `printMultiplicationTable` that takes an integer `number` as a parameter and prints the multiplication table of that number up to 15. Call the `printMultiplicationTable` method with a number of your choice.
-##### Solution
+##### Solution:
1. Launch JShell.
-2. Define a method called `printMultiplicationTable` that takes an `int` parameter called `number`. The method should print the multiplication table of the given number up to 10. Each line of the table should be printed in the format `number * i = result`, where `i` is the number being multiplied by `number`, and `result` is the product of the multiplication.
-
+
+2. Define a void method called `printMultiplicationTable` that takes an integer `number` as a parameter and prints the multiplication table of that number up to 15:
+
```
-jshell> void printMultiplicationTable(int number) {
- ...> for (int i = 1; i <= 10; i++) {
- ...> System.out.printf("%d * %d = %d\n", number, i, number * i);
- ...> }
- ...> }
- ```
-
-3. Call the `printMultiplicationTable` method with the argument `5`.
-
+void printMultiplicationTable(int number) {
+ for (int i = 1; i <= 15; i++) {
+ System.out.println(number + " x " + i + " = " + (number * i));
+ }
+ }
```
-jshell> printMultiplicationTable(5);
-5 * 1 = 5
-5 * 2 = 10
-5 * 3 = 15
-5 * 4 = 20
-5 * 5 = 25
-5 * 6 = 30
-5 * 7 = 35
-5 * 8 = 40
-5 * 9 = 45
-5 * 10 = 50
-```
-
-4. Call the `printMultiplicationTable` method with the argument `9`.
-
-```
-jshell> printMultiplicationTable(9);
-9 * 1 = 9
-9 * 2 = 18
-9 * 3 = 27
-9 * 4 = 36
-9 * 5 = 45
-9 * 6 = 54
-9 * 7 = 63
-9 * 8 = 72
-9 * 9 = 81
-9 * 10 = 90
+
+3. Call the `printMultiplicationTable` method with a number of your choice:
+
```
+jshell> printMultiplicationTable(5);
+ 5 x 1 = 5
+ 5 x 2 = 10
+ 5 x 3 = 15
+ 5 x 4 = 20
+ 5 x 5 = 25
+ 5 x 6 = 30
+ 5 x 7 = 35
+ 5 x 8 = 40
+ 5 x 9 = 45
+ 5 x 10 = 50
+ 5 x 11 = 55
+ 5 x 12 = 60
+ 5 x 13 = 65
+ 5 x 14 = 70
+ 5 x 15 = 75
+ ```
+
+4. Exit JShell using the `/exit` command.
+
-5. Exit JShell using the `/exit` command.
-
-```
-jshell> /exit
-| Goodbye
-```
+Note: In this example, the `printMultiplicationTable` method takes an integer `number` as a parameter and prints the multiplication table of that number up to 15 using a for loop. We call the `printMultiplicationTable` method with the integer value of 5.
#### Exercise 2: Printing Even Numbers using a Method with a Parameter
From 780e781447d4a99c53c1a6f0318252d73e3ac418 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Fri, 31 Mar 2023 11:52:56 +0530
Subject: [PATCH 090/178] Create 03-IntroductionToJavaPlatform.md
---
02-CodeChallenge/03-IntroductionToJavaPlatform.md | 1 +
1 file changed, 1 insertion(+)
create mode 100644 02-CodeChallenge/03-IntroductionToJavaPlatform.md
diff --git a/02-CodeChallenge/03-IntroductionToJavaPlatform.md b/02-CodeChallenge/03-IntroductionToJavaPlatform.md
new file mode 100644
index 00000000..8b137891
--- /dev/null
+++ b/02-CodeChallenge/03-IntroductionToJavaPlatform.md
@@ -0,0 +1 @@
+
From 2a1b5bec65a89aa27325ff133ef0d2cc336496fb Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Fri, 31 Mar 2023 12:24:00 +0530
Subject: [PATCH 091/178] .
---
.../03-IntroductionToJavaPlatform.md | 73 +++++++++++++++++++
...-IntroductionToEclipse-FirstJavaProject.md | 0
2 files changed, 73 insertions(+)
create mode 100644 02-CodeChallenge/04-IntroductionToEclipse-FirstJavaProject.md
diff --git a/02-CodeChallenge/03-IntroductionToJavaPlatform.md b/02-CodeChallenge/03-IntroductionToJavaPlatform.md
index 8b137891..b5f3e0d2 100644
--- a/02-CodeChallenge/03-IntroductionToJavaPlatform.md
+++ b/02-CodeChallenge/03-IntroductionToJavaPlatform.md
@@ -1 +1,74 @@
+### Exercise 1 Print Hello World
+#### Instructions
+In this exercise, you are required to write a Java program that prints the message "Hello World" to the console. Your program should contain a `**main**` method that prints this message using the `**System.out.println()**` statement.
+
+Before attempting this exercise, learners should have a basic understanding of Java programming concepts, including syntax and the use of the `**System.out.println()**` statement. Learners should also be familiar with setting up and running Java programs using a command line interface or an integrated development environment (IDE).
+
+#### Hints
+- Use the `**System.out.println()**` statement to print the message "Hello World"
+
+- Remember to use quotation marks to indicate that the text is a string
+
+#### Solution Explanation
+Here is an example of a possible solution:
+
+
+```
+public class Exercise {
+ public static void main(String[] args) {
+ System.out.println("Hello World");
+ }
+}
+```
+
+The code above creates a class called `**Exercise**` with a `**main**` method that prints the string "Hello World" to the console using the `**System.out.println()**` statement.
+
+The key concept used in this solution is the `**System.out.println()**` statement, which is used to print text to the console. In this case, we pass the string "Hello World" as an argument to the statement to print the message to the console.
+
+When learners run the program, they should see the message "Hello World" printed to the console.
+
+#### Student File
+**Exercise.java**
+```
+public class Exercise {
+
+}
+```
+
+#### Solution File
+**Exercise.java**
+```
+public class Exercise {
+ public static void main(String[] args) {
+ System.out.println("Hello World");
+ }
+}
+```
+
+#### Evaluation File
+**Evaluate.java**
+```
+import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+
+public class Evaluate {
+
+ @Test
+ public void testExerciseOutput() {
+ // Redirect output to a ByteArrayOutputStream
+ ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
+ PrintStream printStream = new PrintStream(outputStream);
+ System.setOut(printStream);
+
+ // Call the main method of the Exercise class
+ Exercise.main(null);
+
+ // Verify that the output contains the message "Hello World"
+ String output = outputStream.toString();
+ assertEquals("Hello World\n", output);
+ }
+}
+```
diff --git a/02-CodeChallenge/04-IntroductionToEclipse-FirstJavaProject.md b/02-CodeChallenge/04-IntroductionToEclipse-FirstJavaProject.md
new file mode 100644
index 00000000..e69de29b
From ef0533fa9201a8ba673bf27b3d5cc00c055cc8d3 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Fri, 31 Mar 2023 12:42:19 +0530
Subject: [PATCH 092/178] .
---
.../03-IntroductionToJavaPlatform.md | 109 ++++++++++++++++++
1 file changed, 109 insertions(+)
diff --git a/02-CodeChallenge/03-IntroductionToJavaPlatform.md b/02-CodeChallenge/03-IntroductionToJavaPlatform.md
index b5f3e0d2..1bc85d2d 100644
--- a/02-CodeChallenge/03-IntroductionToJavaPlatform.md
+++ b/02-CodeChallenge/03-IntroductionToJavaPlatform.md
@@ -72,3 +72,112 @@ public class Evaluate {
}
}
```
+
+
+
+### Exercise 2: Printing a Message with the Exercise Class
+
+#### Instructions
+
+**Task**
+
+Your task is to create a Java class called `**Exercise**` that includes a method called `**exerciseComplete**` which prints the message "I have completed the exercise" to the console. You will also need to create a `**main**` method that creates an instance of the `**Exercise**` class and calls the `**exerciseComplete**` method on this instance. The purpose of this exercise is to help you gain experience in creating classes, methods, and console output in Java.
+
+**Steps**
+
+Follow these steps to complete the exercise:
+
+1. Open your preferred text editor or IDE and create a new file named `**Exercise.java**`.
+
+2. Inside the `**Exercise**` class, create a method called `**exerciseComplete**` that takes no arguments and returns void.
+
+3. Inside the `**exerciseComplete**` method, use the `**System.out.println()**` statement to print the message "I have completed the exercise" to the console.
+
+4. Inside the `**Exercise**` class, create a `**main**` method that takes no arguments and returns void.
+
+5. Inside the `**main**` method, create a new instance of the `**Exercise**` class using the `**new**` keyword and store it in a variable.
+
+6. Call the `**exerciseComplete**` method on the instance of the `**Exercise**` class using the dot notation.
+
+7. Run the code and ensure that the message "I have completed the exercise" is printed to the console.
+
+#### Hints
+Create a file named `**Exercise.java**` with the following instructions:
+
+1. Create a class called `**Exercise**`.
+
+2. Inside the class, create a method called `**exerciseComplete**` that prints the message "I have completed the exercise" to the console using the `**System.out.println()**` statement.
+
+3. Inside the class, create a `**main**` method that creates a new instance of the `**Exercise**` class and calls the `**exerciseComplete**` method on this instance.
+
+4. Save the file and run the program to ensure that the message "I have completed the exercise" is printed to the console.
+
+#### Solution Explanation
+
+The goal of this exercise is to create a Java class called `**Exercise**` that includes a method called `**exerciseComplete**` that prints the message "I have completed the exercise" to the console, and a `**main**` method that creates an instance of the `**Exercise**` class and calls the `**exerciseComplete**` method on this instance. Here's an implementation of the solution:
+
+```
+public class Exercise {
+ public void exerciseComplete() {
+ System.out.println("I have completed the exercise");
+ }
+
+ public static void main(String[] args) {
+ Exercise myExercise = new Exercise();
+ myExercise.exerciseComplete();
+ }
+}
+```
+
+The `**Exercise**` class defines a method called `**exerciseComplete**` that prints the message "I have completed the exercise" to the console using the `**System.out.println()**` statement. The class also defines a `**main**` method that creates a new instance of the `**Exercise**` class using the `**new**` keyword and stores it in a variable called `**myExercise**`. Finally, the `**main**` method calls the `**exerciseComplete**` method on the `**myExercise**` instance using the dot notation.
+
+#### Student File
+**Exercise.java**
+```
+public class Exercise {
+
+}
+```
+
+#### Solution File
+**Exercise.java**
+```
+public class Exercise {
+ void exerciseComplete() {
+ System.out.println("I have completed the exercise");
+ }
+
+ public static void main(String[] args) {
+ Exercise myExercise = new Exercise();
+ myExercise.exerciseComplete();
+ }
+}
+
+```
+
+#### Evaluation File
+**Evaluate.java**
+```
+import static org.junit.jupiter.api.Assertions.*;
+import org.junit.jupiter.api.Test;
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+
+public class Evaluate {
+ @Test
+ public void testExerciseOutput() {
+ // Redirect output to a ByteArrayOutputStream
+ ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
+ PrintStream printStream = new PrintStream(outputStream);
+ System.setOut(printStream);
+
+ // Create an instance of the Exercise class and call the exerciseComplete method
+ Exercise exercise = new Exercise();
+ exercise.exerciseComplete();
+
+ // Verify that the output contains the message "I have completed the exercise"
+ String output = outputStream.toString();
+ assertEquals("I have completed the exercise\n", output);
+ }
+}
+```
From 28854b3c582d762b762eef901ef5ba99c60fb510 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sat, 1 Apr 2023 21:54:48 +0530
Subject: [PATCH 093/178] .
---
...-IntroductionToEclipse-FirstJavaProject.md | 181 ++++++++++++++++++
1 file changed, 181 insertions(+)
diff --git a/02-CodeChallenge/04-IntroductionToEclipse-FirstJavaProject.md b/02-CodeChallenge/04-IntroductionToEclipse-FirstJavaProject.md
index e69de29b..df747d37 100644
--- a/02-CodeChallenge/04-IntroductionToEclipse-FirstJavaProject.md
+++ b/02-CodeChallenge/04-IntroductionToEclipse-FirstJavaProject.md
@@ -0,0 +1,181 @@
+### Exercise 2: Factorial Calculator : Implement a Factorial Calculator in Java
+
+#### Instructions
+
+
+**Task:**
+
+Complete the missing parts of the `FactorialCalculator` class.
+
+Implement the `print(int number)` and `print(int from, int to)` methods to print the factorial of the given number and the factorials of numbers in the given range, respectively.
+
+Use the provided `calculateFactorial` method to calculate factorials.
+
+**Steps:**
+
+1. Implement the `print(int number)` method:
+ - Use `System.out.printf()` to print the formatted output.
+ - Call `calculateFactorial(number)` to get the factorial of the given number.
+2. Implement the `print(int from, int to)` method:
+ - Use a for loop to iterate through the range of numbers from `from` to `to`.
+ - Call the `print(number)` method for each number in the range.
+
+#### Hints
+
+1. For the `print(int number)` method, you can use `System.out.printf()` to print the formatted output. Use `calculateFactorial(number)` to get the factorial.
+
+2. For the `print(int from, int to)` method, use a for loop to iterate through the range of numbers and call `print(number)` method for each number in the range.
+
+#### Solution Explanation
+
+The solution implements the missing methods in the `FactorialCalculator` class.
+
+1. In the `print(int number)` method, we use `System.out.printf()` to print the formatted output with the factorial of the given number calculated using `calculateFactorial(number)`.
+
+```
+public static void print(int number) {
+ System.out.printf("Factorial of %d is: %d", number, calculateFactorial(number)).println();
+}
+```
+
+2. In the `print(int from, int to)` method, we use a for loop to iterate through the range of numbers and call the `print(number)` method for each number in the range.
+
+```
+public static void print(int from, int to) {
+ for (int i = from; i <= to; i++) {
+ System.out.printf("Factorial of %d is: %d", i, calculateFactorial(i)).println();
+ }
+}
+```
+
+With these methods implemented, the `FactorialCalculator` class is complete and ready to be used in the `main` method to print factorials of individual numbers and ranges.
+
+
+#### Student File
+**FactorialCalculatorRunner.java**
+```
+public class FactorialCalculatorRunner {
+
+ public static class FactorialCalculator {
+ public static void print() {
+ for (int i = 1; i <= 10; i++) {
+ System.out.printf("Factorial of %d is: %d", i, calculateFactorial(i)).println();
+ }
+ }
+
+ public static void print(int number) {
+ // Complete the code
+ }
+
+ public static void print(int from, int to) {
+ // Complete the code
+ }
+
+ private static long calculateFactorial(int number) {
+ long factorial = 1;
+ for (int i = 1; i <= number; i++) {
+ factorial *= i;
+ }
+ return factorial;
+ }
+ }
+
+ public static void main(String[] args) {
+ FactorialCalculator factorialCalculator= new FactorialCalculator();
+ factorialCalculator.print();
+ factorialCalculator.print(8);
+ factorialCalculator.print(3, 6);
+ }
+}
+
+
+```
+
+
+#### Solution File
+**FactorialCalculatorRunner.java**
+```
+public class FactorialCalculatorRunner {
+
+ public static class FactorialCalculator {
+ public static void print() {
+ for (int i = 1; i <= 10; i++) {
+ System.out.printf("Factorial of %d is: %d", i, calculateFactorial(i)).println();
+ }
+ }
+
+ public static void print(int number) {
+ System.out.printf("Factorial of %d is: %d", number, calculateFactorial(number)).println();
+ }
+
+ public static void print(int from, int to) {
+ for (int i = from; i <= to; i++) {
+ System.out.printf("Factorial of %d is: %d", i, calculateFactorial(i)).println();
+ }
+ }
+
+ private static long calculateFactorial(int number) {
+ long factorial = 1;
+ for (int i = 1; i <= number; i++) {
+ factorial *= i;
+ }
+ return factorial;
+ }
+ }
+
+ public static void main(String[] args) {
+ FactorialCalculator factorialCalculator= new FactorialCalculator();
+ factorialCalculator.print();
+ factorialCalculator.print(8);
+ factorialCalculator.print(3, 6);
+ }
+}
+```
+
+
+
+#### Evaluation File
+**Evaluate.java**
+```
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+
+public class Evaluate {
+ @Test
+ public void testMainMethod() {
+ PrintStream originalOut = System.out;
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ System.setOut(new PrintStream(baos));
+
+ FactorialCalculatorRunner.main(null);
+
+ System.setOut(originalOut);
+ String capturedOutput = baos.toString();
+
+ String lineSeparator = System.lineSeparator();
+ String expectedOutput = "Factorial of 1 is: 1" + lineSeparator +
+ "Factorial of 2 is: 2" + lineSeparator +
+ "Factorial of 3 is: 6" + lineSeparator +
+ "Factorial of 4 is: 24" + lineSeparator +
+ "Factorial of 5 is: 120" + lineSeparator +
+ "Factorial of 6 is: 720" + lineSeparator +
+ "Factorial of 7 is: 5040" + lineSeparator +
+ "Factorial of 8 is: 40320" + lineSeparator +
+ "Factorial of 9 is: 362880" + lineSeparator +
+ "Factorial of 10 is: 3628800" + lineSeparator +
+ "Factorial of 8 is: 40320" + lineSeparator +
+ "Factorial of 3 is: 6" + lineSeparator +
+ "Factorial of 4 is: 24" + lineSeparator +
+ "Factorial of 5 is: 120" + lineSeparator +
+ "Factorial of 6 is: 720" + lineSeparator;
+
+ assertEquals(expectedOutput, capturedOutput);
+ }
+}
+
+
+```
From f7c1d9ea351ce7f7c7ef74db4cf9611fd19e0c76 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sat, 1 Apr 2023 22:01:52 +0530
Subject: [PATCH 094/178] .
---
02-CodeChallenge/04-IntroductionToEclipse-FirstJavaProject.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/02-CodeChallenge/04-IntroductionToEclipse-FirstJavaProject.md b/02-CodeChallenge/04-IntroductionToEclipse-FirstJavaProject.md
index df747d37..a593d340 100644
--- a/02-CodeChallenge/04-IntroductionToEclipse-FirstJavaProject.md
+++ b/02-CodeChallenge/04-IntroductionToEclipse-FirstJavaProject.md
@@ -1,4 +1,4 @@
-### Exercise 2: Factorial Calculator : Implement a Factorial Calculator in Java
+### Exercise 1: Factorial Calculator : Implement a Factorial Calculator in Java
#### Instructions
From 944c1fcf611fe10265233108366ad105e337d7e1 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sat, 1 Apr 2023 22:36:10 +0530
Subject: [PATCH 095/178] .
---
...-IntroductionToEclipse-FirstJavaProject.md | 209 ++++++++++++++++++
1 file changed, 209 insertions(+)
diff --git a/02-CodeChallenge/04-IntroductionToEclipse-FirstJavaProject.md b/02-CodeChallenge/04-IntroductionToEclipse-FirstJavaProject.md
index a593d340..8ecb1b21 100644
--- a/02-CodeChallenge/04-IntroductionToEclipse-FirstJavaProject.md
+++ b/02-CodeChallenge/04-IntroductionToEclipse-FirstJavaProject.md
@@ -179,3 +179,212 @@ public class Evaluate {
```
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+### Exercise 2: Even Number Printer Calculator
+
+#### Instructions
+
+
+**Task:**
+
+Complete the missing parts of the `EvenNumberPrinter` class to implement the following methods:
+
+1. `printEvenNumbers()`: Prints all even numbers from 1 to 10.
+2. `printEvenNumbers(int number)`: Prints all even numbers from 1 to `number`.
+3. `printEvenNumbers(int from, int to)`: Prints all even numbers in the range `from` to `to` (inclusive).
+
+**Steps:**
+
+1. Implement the `printEvenNumbers()` method:
+ - Call the `printEvenNumbers(int from, int to)` method with `from` as 1 and `to` as 10.
+2. Implement the `printEvenNumbers(int number)` method:
+ - Call the `printEvenNumbers(int from, int to)` method with `from` as 1 and `to` as `number`.
+3. Implement the `printEvenNumbers(int from, int to)` method:
+ - Use a for loop to iterate through the range of numbers from `from` to `to` (inclusive).
+ - Check if the current number is even using the modulo operator (`i % 2 == 0`).
+ - If the current number is even, print it using `System.out.println(i)`.
+
+#### Hints
+
+
+1. Use a `for` loop to iterate through the given range of numbers.
+2. Use the modulo operator (`%`) to check if a number is even (i.e., if `number % 2 == 0`).
+3. Use `System.out.println()` to print the even numbers in each method.
+
+#### Solution Explanation
+
+The solution implements the `EvenNumberPrinter` class with three methods for printing even numbers.
+
+1. `printEvenNumbers()`: This method prints even numbers from 1 to 10 by calling the `printEvenNumbers(int from, int to)` method with arguments 1 and 10.
+
+```
+public static void printEvenNumbers() {
+ printEvenNumbers(1, 10);
+}
+```
+
+2. `printEvenNumbers(int number)`: This method prints even numbers from 1 to the given number by calling the `printEvenNumbers(int from, int to)` method with arguments 1 and `number`.
+
+```
+public static void printEvenNumbers(int number) {
+ printEvenNumbers(1, number);
+}
+```
+
+3. `printEvenNumbers(int from, int to)`: This method iterates through the range `from` to `to` using a `for` loop and prints the even numbers using the `System.out.println()` method.
+
+```
+public static void printEvenNumbers(int from, int to) {
+ for (int i = from; i <= to; i++) {
+ if (i % 2 == 0) {
+ System.out.println(i);
+ }
+ }
+}
+```
+
+The main method calls these three methods to demonstrate their functionality:
+
+```
+public static void main(String[] args) {
+ EvenNumberPrinter evenNumberPrinter = new EvenNumberPrinter();
+ evenNumberPrinter.printEvenNumbers();
+ evenNumberPrinter.printEvenNumbers(8);
+ evenNumberPrinter.printEvenNumbers(3, 12);
+}
+```
+
+
+#### Student File
+**EvenNumberPrinterRunner.java**
+```
+public class EvenNumberPrinterRunner {
+
+ public static class EvenNumberPrinter {
+ public static void printEvenNumbers() {
+ // Complete the code
+ }
+
+ public static void printEvenNumbers(int number) {
+ // Complete the code
+ }
+
+ public static void printEvenNumbers(int from, int to) {
+ // Complete the code
+ }
+ }
+
+ public static void main(String[] args) {
+ EvenNumberPrinter evenNumberPrinter = new EvenNumberPrinter();
+ evenNumberPrinter.printEvenNumbers();
+ evenNumberPrinter.printEvenNumbers(8);
+ evenNumberPrinter.printEvenNumbers(3, 12);
+ }
+}
+
+
+
+```
+
+
+#### Solution File
+**EvenNumberPrinterRunner.java**
+```
+public class EvenNumberPrinterRunner {
+
+ public static class EvenNumberPrinter {
+ public static void printEvenNumbers() {
+ printEvenNumbers(1, 10);
+ }
+
+ public static void printEvenNumbers(int number) {
+ printEvenNumbers(1, number);
+ }
+
+ public static void printEvenNumbers(int from, int to) {
+ for (int i = from; i <= to; i++) {
+ if (i % 2 == 0) {
+ System.out.println(i);
+ }
+ }
+ }
+ }
+
+ public static void main(String[] args) {
+ EvenNumberPrinter evenNumberPrinter = new EvenNumberPrinter();
+ evenNumberPrinter.printEvenNumbers();
+ evenNumberPrinter.printEvenNumbers(8);
+ evenNumberPrinter.printEvenNumbers(3, 12);
+ }
+}
+
+```
+
+
+
+#### Evaluation File
+**Evaluate.java**
+```
+import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+
+public class Evaluate {
+
+ @Test
+ public void testEvenNumbersMethods() {
+ PrintStream originalOut = System.out;
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ System.setOut(new PrintStream(baos));
+
+ EvenNumberPrinterRunner.EvenNumberPrinter.printEvenNumbers();
+ EvenNumberPrinterRunner.EvenNumberPrinter.printEvenNumbers(8);
+ EvenNumberPrinterRunner.EvenNumberPrinter.printEvenNumbers(3, 12);
+
+ System.setOut(originalOut);
+ String capturedOutput = baos.toString();
+
+ String lineSeparator = System.lineSeparator();
+ String expectedOutput = "2" + lineSeparator +
+ "4" + lineSeparator +
+ "6" + lineSeparator +
+ "8" + lineSeparator +
+ "10" + lineSeparator +
+ "2" + lineSeparator +
+ "4" + lineSeparator +
+ "6" + lineSeparator +
+ "8" + lineSeparator +
+ "4" + lineSeparator +
+ "6" + lineSeparator +
+ "8" + lineSeparator +
+ "10" + lineSeparator +
+ "12" + lineSeparator;
+
+ assertEquals(expectedOutput, capturedOutput);
+ }
+}
+
+
+```
From f4da97f5d369dcb2baa3aefd41670315dfa42b70 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sun, 2 Apr 2023 12:49:32 +0530
Subject: [PATCH 096/178] .
---
...-IntroductionToObjectOrientedProgrammin.md | 305 ++++++++++++++++++
1 file changed, 305 insertions(+)
create mode 100644 02-CodeChallenge/05-IntroductionToObjectOrientedProgrammin.md
diff --git a/02-CodeChallenge/05-IntroductionToObjectOrientedProgrammin.md b/02-CodeChallenge/05-IntroductionToObjectOrientedProgrammin.md
new file mode 100644
index 00000000..7f7905f1
--- /dev/null
+++ b/02-CodeChallenge/05-IntroductionToObjectOrientedProgrammin.md
@@ -0,0 +1,305 @@
+
+## Exercise 1: Implementing Encapsulation Techniques in the VideoGame Class
+
+
+
+### Instructions
+
+#### Task 1: Implement VideoGame class attributes
+
+1. In the given `VideoGameRunner` class, add the following attributes to the `VideoGame` class:
+ - `title` of type `String`
+ - `numberOfCopies` of type `int`
+
+#### Task 2: Implement methods for VideoGame class
+
+1. Implement the following methods for the `VideoGame` class:
+ - `setTitle(String gameTitle)`: Sets the title of the video game.
+ - `getTitle()`: Returns the title of the video game.
+ - `setNumberOfCopies(int numberOfCopies)`: Sets the number of copies if the provided number is greater than or equal to 0.
+ - `getNumberOfCopies()`: Returns the number of copies.
+ - `increaseCopies(int howMuch)`: Increases the number of copies by the given amount.
+ - `decreaseCopies(int howMuch)`: Decreases the number of copies by the given amount but ensures that the number of copies does not go below 0.
+
+
+#### Task 3: Test the VideoGame class in the main method
+
+1. In the `main` method of the `VideoGameRunner` class, create three instances of the `VideoGame` class and set their titles as follows:
+
+ - Create an instance named `rdr2` and set its title to "Red Dead Redemption 2".
+ - Create an instance named `tw3` and set its title to "The Witcher 3".
+ - Create an instance named `botw` and set its title to "Breath of the Wild".
+2. Print the titles of the three video game instances (`rdr2`, `tw3`, and `botw`).
+
+3. Increase the number of copies for each video game instance as follows:
+
+ - Increase the number of copies for `rdr2` by 12.
+ - Increase the number of copies for `tw3` by 18.
+ - Increase the number of copies for `botw` by 24.
+4. Decrease the number of copies for each video game instance as follows:
+
+ - Decrease the number of copies for `rdr2` by 6.
+ - Decrease the number of copies for `tw3` by 12.
+ - Decrease the number of copies for `botw` by 18.
+5. Print the number of copies for each video game instance (`rdr2`, `tw3`, and `botw`).
+
+
+
+### Hints
+
+#### Task 1: Implement VideoGame class attributes
+
+**Hint 1:** To add attributes to a class, declare them within the class using the appropriate data type.
+
+**Hint 2:** You need to add two attributes: a `String` for the `title` and an `int` for the `numberOfCopies`.
+
+#### Task 2: Implement methods for VideoGame class
+
+**Hint 1:** To create a method, use the following syntax: `access_modifier return_type methodName(parameters) { /* method body */ }`.
+
+**Hint 2:** For example, the `setTitle` method should have a `void` return type and a single `String` parameter.
+
+**Hint 3:** To set the number of copies only if the provided number is greater than or equal to 0, use an `if` statement in the `setNumberOfCopies` method.
+
+**Hint 4:** The `increaseCopies` and `decreaseCopies` methods should use the `setNumberOfCopies` method to update the `numberOfCopies` attribute.
+
+#### Task 3: Test the VideoGame class in the main method
+
+**Hint 1:** To create an instance of a class, use the `new` keyword followed by the class name and parentheses.
+
+**Hint 2:** To call a method on an instance of a class, use the dot (.) operator followed by the method name and its arguments.
+
+**Hint 3:** Use `System.out.println()` to print the titles and number of copies for each video game instance.
+
+
+### Solution Explanation
+
+
+The given problem code is incomplete and needs to be modified to include the necessary attributes and methods in the `VideoGame` class. Below is the step-by-step explanation of the solution code.
+
+#### Task 1: Implement VideoGame class attributes
+
+We start by adding the required attributes `title` and `numberOfCopies` to the `VideoGame` class.
+
+```
+private String title;
+private int numberOfCopies;
+```
+
+#### Task 2: Implement methods for VideoGame class
+
+Next, we implement the required methods for the `VideoGame` class.
+
+1. Set and get methods for `title` attribute:
+
+```
+public void setTitle(String gameTitle) {
+ title = gameTitle;
+}
+
+public String getTitle() {
+ return title;
+}
+```
+
+2. Set and get methods for `numberOfCopies` attribute with a condition to ensure the number of copies is non-negative:
+
+```
+public void setNumberOfCopies(int numberOfCopies) {
+ if (numberOfCopies >= 0) {
+ this.numberOfCopies = numberOfCopies;
+ }
+}
+
+public int getNumberOfCopies() {
+ return numberOfCopies;
+}
+```
+
+3. Methods to increase and decrease the number of copies:
+
+```
+public void increaseCopies(int howMuch) {
+ setNumberOfCopies(numberOfCopies + howMuch);
+}
+
+public void decreaseCopies(int howMuch) {
+ setNumberOfCopies(numberOfCopies - howMuch);
+}
+```
+
+#### Task 3: Test the VideoGame class in the main method
+
+Finally, we test the `VideoGame` class in the `main` method by creating instances, setting titles, increasing and decreasing the number of copies, and printing their titles and number of copies.
+
+```
+public static void main(String[] args) {
+ VideoGame rdr2 = new VideoGame();
+ rdr2.setTitle("Red Dead Redemption 2");
+ VideoGame tw3 = new VideoGame();
+ tw3.setTitle("The Witcher 3");
+ VideoGame botw = new VideoGame();
+ botw.setTitle("Breath of the Wild");
+
+ System.out.println(rdr2.getTitle());
+ System.out.println(tw3.getTitle());
+ System.out.println(botw.getTitle());
+
+ rdr2.increaseCopies(12);
+ tw3.increaseCopies(18);
+ botw.increaseCopies(24);
+ rdr2.decreaseCopies(6);
+ tw3.decreaseCopies(12);
+ botw.decreaseCopies(18);
+
+ System.out.println(rdr2.getNumberOfCopies());
+ System.out.println(tw3.getNumberOfCopies());
+ System.out.println(botw.getNumberOfCopies());
+}
+```
+
+This solution code demonstrates the proper implementation of encapsulation techniques and completes the `VideoGame` class as required by the problem statement.
+
+### Student File
+
+**VideoGameRunner.java**
+
+```
+
+public class VideoGameRunner {
+
+ static class VideoGame {
+
+ }
+
+ public static void main(String[] args) {
+ // VideoGame rdr2 = new VideoGame();
+ // rdr2.setTitle("Red Dead Redemption 2");
+ }
+}
+
+```
+
+
+
+
+### Solution File
+
+**VideoGameRunner.java**
+
+```
+public class VideoGameRunner {
+
+ static class VideoGame {
+ private String title;
+ private int numberOfCopies;
+
+ public void setTitle(String gameTitle) {
+ title = gameTitle;
+ }
+
+ public String getTitle() {
+ return title;
+ }
+
+ public void setNumberOfCopies(int numberOfCopies) {
+ if (numberOfCopies >= 0) {
+ this.numberOfCopies = numberOfCopies;
+ }
+ }
+
+ public int getNumberOfCopies() {
+ return numberOfCopies;
+ }
+
+ public void increaseCopies(int howMuch) {
+ setNumberOfCopies(numberOfCopies + howMuch);
+ }
+
+ public void decreaseCopies(int howMuch) {
+ setNumberOfCopies(numberOfCopies - howMuch);
+ }
+ }
+
+ public static void main(String[] args) {
+ VideoGame rdr2 = new VideoGame();
+ rdr2.setTitle("Red Dead Redemption 2");
+ VideoGame tw3 = new VideoGame();
+ tw3.setTitle("The Witcher 3");
+ VideoGame botw = new VideoGame();
+ botw.setTitle("Breath of the Wild");
+
+ System.out.println(rdr2.getTitle());
+ System.out.println(tw3.getTitle());
+ System.out.println(botw.getTitle());
+
+ rdr2.increaseCopies(12);
+ tw3.increaseCopies(18);
+ botw.increaseCopies(24);
+ rdr2.decreaseCopies(6);
+ tw3.decreaseCopies(12);
+ botw.decreaseCopies(18);
+
+ System.out.println(rdr2.getNumberOfCopies());
+ System.out.println(tw3.getNumberOfCopies());
+ System.out.println(botw.getNumberOfCopies());
+ }
+}
+
+```
+
+
+### Evaluation File
+
+**Evaluate.java**
+
+```
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.util.logging.Logger;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+public class Evaluate {
+
+ private VideoGameRunner.VideoGame videoGame;
+ private static final Logger LOGGER = Logger.getLogger(Evaluate.class.getName());
+
+ @BeforeEach
+ public void setUp() {
+ videoGame = new VideoGameRunner.VideoGame();
+ }
+
+ @Test
+ public void testSetTitleAndGetTitle() {
+ LOGGER.info("Running testSetTitleAndGetTitle...");
+ videoGame.setTitle("Test Game");
+ assertEquals("Test Game", videoGame.getTitle());
+ }
+
+ @Test
+ public void testSetNumberOfCopiesAndGetNumberOfCopies() {
+ LOGGER.info("Running testSetNumberOfCopiesAndGetNumberOfCopies...");
+ videoGame.setNumberOfCopies(10);
+ assertEquals(10, videoGame.getNumberOfCopies());
+ }
+
+ @Test
+ public void testIncreaseCopies() {
+ LOGGER.info("Running testIncreaseCopies...");
+ videoGame.setNumberOfCopies(5);
+ videoGame.increaseCopies(5);
+ assertEquals(10, videoGame.getNumberOfCopies());
+ }
+
+ @Test
+ public void testDecreaseCopies() {
+ LOGGER.info("Running testDecreaseCopies...");
+ videoGame.setNumberOfCopies(10);
+ videoGame.decreaseCopies(5);
+ assertEquals(5, videoGame.getNumberOfCopies());
+ }
+}
+```
\ No newline at end of file
From d221fc4f59eb390872c853e5202a3d5034e7a02a Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sun, 2 Apr 2023 13:33:45 +0530
Subject: [PATCH 097/178] Update 05-IntroductionToObjectOrientedProgrammin.md
---
.../05-IntroductionToObjectOrientedProgrammin.md | 5 +++--
1 file changed, 3 insertions(+), 2 deletions(-)
diff --git a/02-CodeChallenge/05-IntroductionToObjectOrientedProgrammin.md b/02-CodeChallenge/05-IntroductionToObjectOrientedProgrammin.md
index 7f7905f1..14b54432 100644
--- a/02-CodeChallenge/05-IntroductionToObjectOrientedProgrammin.md
+++ b/02-CodeChallenge/05-IntroductionToObjectOrientedProgrammin.md
@@ -169,12 +169,13 @@ This solution code demonstrates the proper implementation of encapsulation techn
public class VideoGameRunner {
static class VideoGame {
-
+ // Complete the code
}
public static void main(String[] args) {
// VideoGame rdr2 = new VideoGame();
// rdr2.setTitle("Red Dead Redemption 2");
+ // Complete the code
}
}
@@ -302,4 +303,4 @@ public class Evaluate {
assertEquals(5, videoGame.getNumberOfCopies());
}
}
-```
\ No newline at end of file
+```
From 050714b7fd45b941c48007f72898e1e6112343df Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sun, 2 Apr 2023 18:46:13 +0530
Subject: [PATCH 098/178] .
---
...-IntroductionToObjectOrientedProgrammin.md | 393 ++++++++++++++++++
1 file changed, 393 insertions(+)
diff --git a/02-CodeChallenge/05-IntroductionToObjectOrientedProgrammin.md b/02-CodeChallenge/05-IntroductionToObjectOrientedProgrammin.md
index 14b54432..6f67066d 100644
--- a/02-CodeChallenge/05-IntroductionToObjectOrientedProgrammin.md
+++ b/02-CodeChallenge/05-IntroductionToObjectOrientedProgrammin.md
@@ -304,3 +304,396 @@ public class Evaluate {
}
}
```
+
+
+
+
+
+
+## Exercise 2: Implementing Vehicle Engine Control and Speed Tracking
+
+
+
+### Instructions
+
+
+#### Objective
+
+In this exercise, you are asked to complete the implementation of a simple `Vehicle` class and a `VehicleRunner` class that demonstrates its usage.
+
+#### Instructions
+
+1. Complete the implementation of the `Vehicle` class inside the `VehicleRunner` class. The `Vehicle` class should have the following properties:
+
+ - `speed`: An integer representing the speed of the vehicle.
+ - `type`: A string representing the type of the vehicle, e.g., "Car", "Truck", "Bike".
+2. Implement two constructors for the `Vehicle` class:
+
+ - A constructor that takes two parameters: `speed` and `type`. The `speed` should be set only if the value is greater than 0. Otherwise, the default speed should be 10. The `type` should always be set.
+ - A default constructor that sets the `speed` to 10 and the `type` to "Bike".
+3. Implement the following methods for the `Vehicle` class:
+
+ - `startEngine()`: This method should print "Engine started!".
+ - `stopEngine()`: This method should print "Engine stopped!" and set the `speed` to 0.
+ - `getSpeed()`: This method should return the current `speed` of the vehicle.
+ - `getType()`: This method should return the current `type` of the vehicle.
+4. In the `main()` method of the `VehicleRunner` class, create three `Vehicle` instances with different speed and type values:
+
+ - `car`: Speed 30, Type "Car".
+ - `truck`: Speed 20, Type "Truck".
+ - `bike`: Default constructor.
+5. Start the engine of all three vehicles and print their initial speed and type.
+
+6. Stop the engine of all three vehicles and print their final speed.
+
+
+#### Example
+
+Below is an example of the incomplete code provided to the student:
+
+```
+public class VehicleRunner {
+ public static class Vehicle {
+ // Write your code
+ }
+
+ public static void main(String[] args) {
+ // Vehicle car = new Vehicle(30, "Car");
+ // Write your code
+ }
+}
+```
+
+After completing the exercise, the output should look like this:
+```
+Engine started!
+Engine started!
+Engine started!
+Earlier Car Speed is : 30, Type: Car
+Earlier Truck Speed is : 20, Type: Truck
+Earlier Bike Speed is : 10, Type: Bike
+Engine stopped!
+Engine stopped!
+Engine stopped!
+Stopped Car Speed is : 0
+Stopped Truck Speed is : 0
+Stopped Bike Speed is : 0
+```
+
+
+### Hints
+
+
+Here are some hints for completing the given incomplete exercise code:
+
+1. Inside the `Vehicle` class, you need to declare two instance variables:
+
+ - `speed` of type `int`
+ - `type` of type `String`
+2. Create a constructor for the `Vehicle` class that takes two parameters:
+
+ - `int speed`
+ - `String type` Inside the constructor, initialize the instance variables with the given parameters.
+3. Create a default constructor for the `Vehicle` class. In this constructor, set default values for the instance variables:
+
+ - Set `speed` to `10`
+ - Set `type` to `"Bike"`
+4. Add a method `startEngine()` to the `Vehicle` class that prints "Engine started!" when called.
+
+5. Add a method `stopEngine()` to the `Vehicle` class that prints "Engine stopped!" when called and sets the `speed` of the vehicle to `0`.
+
+6. Create getter methods for the `speed` and `type` instance variables in the `Vehicle` class:
+
+ - `public int getSpeed()`
+ - `public String getType()`
+7. In the `main` method of the `VehicleRunner` class, create three instances of the `Vehicle` class:
+
+ - `Vehicle car = new Vehicle(30, "Car");`
+ - `Vehicle truck = new Vehicle(20, "Truck");`
+ - `Vehicle bike = new Vehicle();`
+8. Start the engine of each vehicle by calling the `startEngine()` method on each instance.
+
+9. Print the initial speed and type of each vehicle by calling the `getSpeed()` and `getType()` methods.
+
+10. Stop the engine of each vehicle by calling the `stopEngine()` method on each instance.
+
+11. Print the final speed of each vehicle after stopping the engine by calling the `getSpeed()` method.
+
+
+### Solution Explanation
+
+
+
+In this exercise, we're asked to complete the given incomplete `VehicleRunner` class by implementing the `Vehicle` class, its methods, and then creating instances of the `Vehicle` class in the `main` method. Here's the step-by-step explanation of the solution:
+
+### Implementing the Vehicle class
+
+1. First, we declare two instance variables for the `Vehicle` class:
+ - `speed` of type `int`
+ - `type` of type `String`
+
+```
+private int speed;
+private String type;
+```
+
+2. Next, we create a constructor for the `Vehicle` class that takes two parameters:
+ - `int speed`
+ - `String type` Inside the constructor, we initialize the instance variables with the given parameters.
+
+```
+public Vehicle(int speed, String type) {
+ if (speed > 0) {
+ this.speed = speed;
+ }
+ this.type = type;
+}
+```
+
+3. We then create a default constructor for the `Vehicle` class. In this constructor, we set default values for the instance variables:
+ - Set `speed` to `10`
+ - Set `type` to `"Bike"`
+
+```
+public Vehicle() {
+ this.speed = 10;
+ this.type = "Bike";
+}
+```
+
+4. We add a method `startEngine()` to the `Vehicle` class that prints "Engine started!" when called.
+
+```
+public void startEngine() {
+ System.out.println("Engine started!");
+}
+```
+
+5. We add another method `stopEngine()` to the `Vehicle` class that prints "Engine stopped!" when called and sets the `speed` of the vehicle to `0`.
+
+```
+public void stopEngine() {
+ System.out.println("Engine stopped!");
+ this.speed = 0;
+}
+```
+
+6. We create getter methods for the `speed` and `type` instance variables in the `Vehicle` class:
+ - `public int getSpeed()`
+ - `public String getType()`
+
+```
+public int getSpeed() {
+ return speed;
+}
+
+public String getType() {
+ return type;
+}
+```
+
+### Creating instances and calling methods in the main method
+
+7. In the `main` method of the `VehicleRunner` class, we create three instances of the `Vehicle` class:
+
+```
+Vehicle car = new Vehicle(30, "Car");
+Vehicle truck = new Vehicle(20, "Truck");
+Vehicle bike = new Vehicle();
+```
+
+8. We start the engine of each vehicle by calling the `startEngine()` method on each instance:
+
+```
+car.startEngine();
+truck.startEngine();
+bike.startEngine();
+```
+
+9. We print the initial speed and type of each vehicle by calling the `getSpeed()` and `getType()` methods:
+
+```
+System.out.println("Earlier Car Speed is : " + car.getSpeed() + ", Type: " + car.getType());
+System.out.println("Earlier Truck Speed is : " + truck.getSpeed() + ", Type: " + truck.getType());
+System.out.println("Earlier Bike Speed is : " + bike.getSpeed() + ", Type: " + bike.getType());
+```
+
+10. We stop the engine of each vehicle by calling the `stopEngine()` method on each instance:
+
+```
+car.stopEngine();
+truck.stopEngine();
+bike.stopEngine();
+```
+
+11. Finally, we print the final speed of each vehicle after stopping the engine by calling the `getSpeed()` method:
+
+```
+System.out.println("Stopped Car Speed is : " + car.getSpeed());
+System.out.println("Stopped Truck Speed is : " + truck.getSpeed());
+System.out.println("Stopped Bike Speed is : " + bike.getSpeed());
+```
+
+With this, we have successfully completed the implementation of the `VehicleRunner` class and its inner `Vehicle` class.
+
+### Student File
+
+**VehicleRunner.java**
+
+```
+
+public class VehicleRunner {
+ public static class Vehicle {
+ // Write your code
+ }
+
+ public static void main(String[] args) {
+ // Vehicle car = new Vehicle(30, "Car");
+ // Write your code
+ }
+
+
+}
+```
+
+
+
+
+### Solution File
+
+**VehicleRunner.java**
+
+```
+public class VehicleRunner {
+ public static class Vehicle {
+ private int speed;
+ private String type;
+
+ public Vehicle(int speed, String type) {
+ if (speed > 0) {
+ this.speed = speed;
+ }
+ this.type = type;
+ }
+
+ public Vehicle() {
+ this.speed = 10;
+ this.type = "Bike";
+ }
+
+ public void startEngine() {
+ System.out.println("Engine started!");
+ }
+
+ public void stopEngine() {
+ System.out.println("Engine stopped!");
+ this.speed = 0;
+ }
+
+ public int getSpeed() {
+ return speed;
+ }
+
+ public String getType() {
+ return type;
+ }
+ }
+
+ public static void main(String[] args) {
+ Vehicle car = new Vehicle(30, "Car");
+ Vehicle truck = new Vehicle(20, "Truck");
+ Vehicle bike = new Vehicle();
+
+ car.startEngine();
+ truck.startEngine();
+ bike.startEngine();
+
+ System.out.println("Earlier Car Speed is : " + car.getSpeed() + ", Type: " + car.getType());
+ System.out.println("Earlier Truck Speed is : " + truck.getSpeed() + ", Type: " + truck.getType());
+ System.out.println("Earlier Bike Speed is : " + bike.getSpeed() + ", Type: " + bike.getType());
+
+ car.stopEngine();
+ truck.stopEngine();
+ bike.stopEngine();
+
+ System.out.println("Stopped Car Speed is : " + car.getSpeed());
+ System.out.println("Stopped Truck Speed is : " + truck.getSpeed());
+ System.out.println("Stopped Bike Speed is : " + bike.getSpeed());
+ }
+
+
+}
+
+```
+
+
+### Evaluation File
+
+**Evaluate.java**
+
+```
+
+import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.*;
+
+public class Evaluate {
+ @Test
+ public void testStartEngine() {
+ VehicleRunner.Vehicle car = new VehicleRunner.Vehicle(30, "Car");
+ VehicleRunner.Vehicle truck = new VehicleRunner.Vehicle(20, "Truck");
+ VehicleRunner.Vehicle bike = new VehicleRunner.Vehicle();
+
+ car.startEngine();
+ truck.startEngine();
+ bike.startEngine();
+
+ System.out.println("Car Speed after starting engine: " + car.getSpeed());
+ System.out.println("Truck Speed after starting engine: " + truck.getSpeed());
+ System.out.println("Bike Speed after starting engine: " + bike.getSpeed());
+
+ assertEquals(30, car.getSpeed());
+ assertEquals(20, truck.getSpeed());
+ assertEquals(10, bike.getSpeed());
+ }
+
+ @Test
+ public void testStopEngine() {
+ VehicleRunner.Vehicle car = new VehicleRunner.Vehicle(30, "Car");
+ VehicleRunner.Vehicle truck = new VehicleRunner.Vehicle(20, "Truck");
+ VehicleRunner.Vehicle bike = new VehicleRunner.Vehicle();
+
+ car.startEngine();
+ truck.startEngine();
+ bike.startEngine();
+
+ car.stopEngine();
+ truck.stopEngine();
+ bike.stopEngine();
+
+ System.out.println("Car Speed after stopping engine: " + car.getSpeed());
+ System.out.println("Truck Speed after stopping engine: " + truck.getSpeed());
+ System.out.println("Bike Speed after stopping engine: " + bike.getSpeed());
+
+ assertEquals(0, car.getSpeed());
+ assertEquals(0, truck.getSpeed());
+ assertEquals(0, bike.getSpeed());
+ }
+
+ @Test
+ public void testGetType() {
+ VehicleRunner.Vehicle car = new VehicleRunner.Vehicle(30, "Car");
+ VehicleRunner.Vehicle truck = new VehicleRunner.Vehicle(20, "Truck");
+ VehicleRunner.Vehicle bike = new VehicleRunner.Vehicle();
+
+ System.out.println("Car type: " + car.getType());
+ System.out.println("Truck type: " + truck.getType());
+ System.out.println("Bike type: " + bike.getType());
+
+ assertEquals("Car", car.getType());
+ assertEquals("Truck", truck.getType());
+ assertEquals("Bike", bike.getType());
+ }
+}
+
+
+```
\ No newline at end of file
From f6b8f3f2018d95991b4c06bd21613d4ce1eaab07 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sun, 2 Apr 2023 18:55:28 +0530
Subject: [PATCH 099/178] .
---
...-IntroductionToObjectOrientedProgrammin.md | 42 ++++++++++++++-----
1 file changed, 32 insertions(+), 10 deletions(-)
diff --git a/02-CodeChallenge/05-IntroductionToObjectOrientedProgrammin.md b/02-CodeChallenge/05-IntroductionToObjectOrientedProgrammin.md
index 6f67066d..57e32c5c 100644
--- a/02-CodeChallenge/05-IntroductionToObjectOrientedProgrammin.md
+++ b/02-CodeChallenge/05-IntroductionToObjectOrientedProgrammin.md
@@ -270,39 +270,61 @@ public class Evaluate {
@BeforeEach
public void setUp() {
+ LOGGER.info("Setting up a new VideoGame instance for the tests...");
videoGame = new VideoGameRunner.VideoGame();
}
@Test
public void testSetTitleAndGetTitle() {
LOGGER.info("Running testSetTitleAndGetTitle...");
- videoGame.setTitle("Test Game");
- assertEquals("Test Game", videoGame.getTitle());
+ String testTitle = "Test Game";
+ LOGGER.info("Setting title to: " + testTitle);
+ videoGame.setTitle(testTitle);
+ LOGGER.info("Getting the title and checking if it matches the expected value...");
+ assertEquals(testTitle, videoGame.getTitle());
+ LOGGER.info("testSetTitleAndGetTitle passed.");
}
@Test
public void testSetNumberOfCopiesAndGetNumberOfCopies() {
LOGGER.info("Running testSetNumberOfCopiesAndGetNumberOfCopies...");
- videoGame.setNumberOfCopies(10);
- assertEquals(10, videoGame.getNumberOfCopies());
+ int testCopies = 10;
+ LOGGER.info("Setting number of copies to: " + testCopies);
+ videoGame.setNumberOfCopies(testCopies);
+ LOGGER.info("Getting the number of copies and checking if it matches the expected value...");
+ assertEquals(testCopies, videoGame.getNumberOfCopies());
+ LOGGER.info("testSetNumberOfCopiesAndGetNumberOfCopies passed.");
}
@Test
public void testIncreaseCopies() {
LOGGER.info("Running testIncreaseCopies...");
- videoGame.setNumberOfCopies(5);
- videoGame.increaseCopies(5);
- assertEquals(10, videoGame.getNumberOfCopies());
+ int initialCopies = 5;
+ int increaseCopiesBy = 5;
+ LOGGER.info("Setting initial number of copies to: " + initialCopies);
+ videoGame.setNumberOfCopies(initialCopies);
+ LOGGER.info("Increasing number of copies by: " + increaseCopiesBy);
+ videoGame.increaseCopies(increaseCopiesBy);
+ LOGGER.info("Getting the number of copies and checking if it matches the expected value...");
+ assertEquals(initialCopies + increaseCopiesBy, videoGame.getNumberOfCopies());
+ LOGGER.info("testIncreaseCopies passed.");
}
@Test
public void testDecreaseCopies() {
LOGGER.info("Running testDecreaseCopies...");
- videoGame.setNumberOfCopies(10);
- videoGame.decreaseCopies(5);
- assertEquals(5, videoGame.getNumberOfCopies());
+ int initialCopies = 10;
+ int decreaseCopiesBy = 5;
+ LOGGER.info("Setting initial number of copies to: " + initialCopies);
+ videoGame.setNumberOfCopies(initialCopies);
+ LOGGER.info("Decreasing number of copies by: " + decreaseCopiesBy);
+ videoGame.decreaseCopies(decreaseCopiesBy);
+ LOGGER.info("Getting the number of copies and checking if it matches the expected value...");
+ assertEquals(initialCopies - decreaseCopiesBy, videoGame.getNumberOfCopies());
+ LOGGER.info("testDecreaseCopies passed.");
}
}
+
```
From 9e99b5bc36cebde23e284eddb516a2069da22ed5 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Tue, 4 Apr 2023 11:13:58 +0530
Subject: [PATCH 100/178] .
---
...troductionToMethods-MultiplicationTable.md | 43 +++++++++++++++++++
1 file changed, 43 insertions(+)
create mode 100644 01-Quiz/Q02-IntroductionToMethods-MultiplicationTable.md
diff --git a/01-Quiz/Q02-IntroductionToMethods-MultiplicationTable.md b/01-Quiz/Q02-IntroductionToMethods-MultiplicationTable.md
new file mode 100644
index 00000000..d6457767
--- /dev/null
+++ b/01-Quiz/Q02-IntroductionToMethods-MultiplicationTable.md
@@ -0,0 +1,43 @@
+## Step 1,2
+
+
+### Question 1
+
+What does the `void` keyword indicate in a method definition?
+
+A) The method returns an integer value B) The method does not return any value C) The method returns a boolean value
+
+**Answer:** B) The method does not return any value
+
+### Question 2
+
+What is the correct way to call a method named `sayHelloWorldTwice`?
+
+A) sayHelloWorldTwice B) sayHelloWorldTwice() C) sayHelloWorldTwice();
+
+**Answer:** B) sayHelloWorldTwice()
+
+### Question 3
+
+Which of the following statements is true about method definitions and method calls?
+
+A) Defining a method automatically executes its statement body B) Defining a method and invoking it are the same thing C) Defining and invoking methods are two different steps
+
+**Answer:** C) Defining and invoking methods are two different steps
+
+
+### Question 4
+
+What is the correct syntax for defining a method that prints "Hello World"?
+
+A) void printHelloWorld() { System.out.println("Hello World"); } B) printHelloWorld() { System.out.println("Hello World"); } C) void printHelloWorld { System.out.println("Hello World"); }
+
+**Answer:** A) void printHelloWorld() { System.out.println("Hello World"); }
+
+### Question 5
+
+Which of these method names follows the same naming rules as variable names?
+
+A) 1stMethod B) method_one C) first-Method
+
+**Answer:** B) method_one
\ No newline at end of file
From 655ede022beb9344e7a72f632db775966e701221 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Tue, 4 Apr 2023 11:28:11 +0530
Subject: [PATCH 101/178] .
---
...troductionToMethods-MultiplicationTable.md | 224 +++++++++++++++++-
1 file changed, 217 insertions(+), 7 deletions(-)
diff --git a/01-Quiz/Q02-IntroductionToMethods-MultiplicationTable.md b/01-Quiz/Q02-IntroductionToMethods-MultiplicationTable.md
index d6457767..8be6910b 100644
--- a/01-Quiz/Q02-IntroductionToMethods-MultiplicationTable.md
+++ b/01-Quiz/Q02-IntroductionToMethods-MultiplicationTable.md
@@ -1,11 +1,12 @@
## Step 1,2
-
### Question 1
What does the `void` keyword indicate in a method definition?
-A) The method returns an integer value B) The method does not return any value C) The method returns a boolean value
+- A) The method returns an integer value
+- B) The method does not return any value
+- C) The method returns a boolean value
**Answer:** B) The method does not return any value
@@ -13,7 +14,9 @@ A) The method returns an integer value B) The method does not return any value C
What is the correct way to call a method named `sayHelloWorldTwice`?
-A) sayHelloWorldTwice B) sayHelloWorldTwice() C) sayHelloWorldTwice();
+- A) sayHelloWorldTwice
+- B) sayHelloWorldTwice()
+- C) sayHelloWorldTwice();
**Answer:** B) sayHelloWorldTwice()
@@ -21,7 +24,9 @@ A) sayHelloWorldTwice B) sayHelloWorldTwice() C) sayHelloWorldTwice();
Which of the following statements is true about method definitions and method calls?
-A) Defining a method automatically executes its statement body B) Defining a method and invoking it are the same thing C) Defining and invoking methods are two different steps
+- A) Defining a method automatically executes its statement body
+- B) Defining a method and invoking it are the same thing
+- C) Defining and invoking methods are two different steps
**Answer:** C) Defining and invoking methods are two different steps
@@ -30,7 +35,9 @@ A) Defining a method automatically executes its statement body B) Defining a met
What is the correct syntax for defining a method that prints "Hello World"?
-A) void printHelloWorld() { System.out.println("Hello World"); } B) printHelloWorld() { System.out.println("Hello World"); } C) void printHelloWorld { System.out.println("Hello World"); }
+- A) void printHelloWorld() { System.out.println("Hello World"); }
+- B) printHelloWorld() { System.out.println("Hello World"); }
+- C) void printHelloWorld { System.out.println("Hello World"); }
**Answer:** A) void printHelloWorld() { System.out.println("Hello World"); }
@@ -38,6 +45,209 @@ A) void printHelloWorld() { System.out.println("Hello World"); } B) printHelloWo
Which of these method names follows the same naming rules as variable names?
-A) 1stMethod B) method_one C) first-Method
+- A) 1stMethod
+- B) method_one
+- C) first-Method
+
+**Answer:** B) method_one
+
+## Step 3
+
+### Question 6
+
+Which command lists the methods defined in the current JShell session?
+
+- A) /methods
+- B) /list
+- C) /edit
+
+**Answer:** A) /methods
+
+### Question 7
+
+What does the /edit command do in JShell?
+
+- A) Lists the code of the specified method
+- B) Allows you to modify the method definition in a separate editor window
+- C) Saves the session method definitions to a file
+
+**Answer:** B) Allows you to modify the method definition in a separate editor window
+
+
+## Step 4, 5
+
+### Question 8
+
+What is the correct syntax for defining a method with an argument?
+
+- A) void methodName(ArgType argName) { method-body }
+- B) methodName(ArgType argName) { method-body }
+- C) methodName(ArgType argName) { method-body; }
+
+**Answer:** A) void methodName(ArgType argName) { method-body }
+
+### Question 9
+
+Which method definition correctly prints all integers from 1 to n (inclusive), where n is an argument?
+
+- A)
+
+```
+void printNumbers(int n) {
+ for (int i = 1; i <= n; i++) {
+ System.out.println(i);
+ }
+}
+```
+
+- B)
+
+```
+void printNumbers(int n) {
+ for (int i = 1; i < n; i++) {
+ System.out.println(i);
+ }
+}
+```
+- C)
+
+```
+void printNumbers(int n) {
+ for (int i = 0; i < n; i++) {
+ System.out.println(i);
+ }
+}
+```
+
+**Answer:** A)
+
+```
+void printNumbers(int n) {
+ for (int i = 1; i <= n; i++) {
+ System.out.println(i);
+ }
+}
+```
+
+### Question 10
+
+What would happen if you try to call the method `sayHelloWorld` with a string argument, when the method is defined to accept an integer argument?
+
+- A) The program will compile and run without any errors
+- B) The program will throw a runtime error
+- C) The program will fail to compile due to incompatible types
+
+**Answer:** C) The program will fail to compile due to incompatible types
+
+## Step 8, 9
+
+### Question 11
+
+What is method overloading in Java?
+
+- A) The ability to have multiple methods with the same name in a class, but with different types of arguments
+- B) The ability to have multiple methods with the same name and the same types of arguments in a class
+- C) The ability to have a single method with an arbitrary number of arguments
+
+**Answer:** A) The ability to have multiple methods with the same name in a class, but with different types of arguments
+
+### Question 12
+
+Consider the following two method definitions:
+
+```
+void printName(String firstName, String lastName) {
+ System.out.println(firstName + " " + lastName);
+}
+
+void printName(String firstName, String middleName, String lastName) {
+ System.out.println(firstName + " " + middleName + " " + lastName);
+}
+```
+
+Which of the following statements are true?
+
+- A) The two methods are overloaded methods
+- B) The two methods have the same name and different number of arguments
+- C) The two methods have the same name and the same types of arguments
+
+**Answer:** A) The two methods are overloaded methods and B) The two methods have the same name and different number of arguments
+
+### Question 13
+
+What will the following code snippet output?
+
+```
+void sum(int a, int b) {
+ System.out.println(a + b);
+}
+
+void sum(int a, int b, int c) {
+ System.out.println(a + b + c);
+}
+
+sum(1, 2);
+sum(1, 2, 3);
+```
+
+- A) The output will be
+
+```
+3
+6
+```
+
+- B) The output will be
+
+```
+3
+5
+```
+
+- C) The code will not compile due to method overloading
+
+**Answer:** A) The output will be
+
+```
+3
+6
+```
+
+### Question 14
+
+Which of the following statements is true about methods with multiple arguments in Java?
+
+- A) A method can only accept up to 2 arguments
+- B) A method can accept any number of arguments, but they must be of the same type
+- C) A method can accept any number of arguments, and they can be of different types
+
+**Answer:** C) A method can accept any number of arguments, and they can be of different types
+
+### Question 15
+
+What is the main purpose of method overloading in Java?
+
+- A) To reduce code duplication by allowing methods with the same name but different arguments
+- B) To allow a method to return different types of values based on the input arguments
+- C) To create multiple methods with the same name and the same number of arguments, but with different implementation
+
+**Answer:** A) To reduce code duplication by allowing methods with the same name but different arguments
+
+
+## Step 10
+
+**Question 16 :** What is the purpose of a return statement in a method?
+
+- A. To end the execution of the method
+- B. To return the result of a computation to the calling code
+- C. To print the output of the method
+
+_Answer: B_
+
+**Question 17 :** What is the benefit of using a return mechanism in a method?
+
+- A. It allows the method to print the result of the computation
+- B. It enables sharing computed results with other code and methods, and improves breaking down a problem into sub-problems
+- C. It simplifies the syntax of the method
-**Answer:** B) method_one
\ No newline at end of file
+_Answer: B_
\ No newline at end of file
From f2b9c194ea14c01d6d4467dffd3a4b9defc38a84 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Tue, 4 Apr 2023 12:03:06 +0530
Subject: [PATCH 102/178] .
---
...-IntroductionToObjectOrientedProgrammin.md | 234 ++++++++++++++++++
1 file changed, 234 insertions(+)
create mode 100644 01-Quiz/Q05-IntroductionToObjectOrientedProgrammin.md
diff --git a/01-Quiz/Q05-IntroductionToObjectOrientedProgrammin.md b/01-Quiz/Q05-IntroductionToObjectOrientedProgrammin.md
new file mode 100644
index 00000000..ffb65ba6
--- /dev/null
+++ b/01-Quiz/Q05-IntroductionToObjectOrientedProgrammin.md
@@ -0,0 +1,234 @@
+## Step 1
+
+**Question 1:** What is a class in Object Oriented Programming?
+
+- A. An instance of an object
+- B. A template for creating objects
+- C. A function to perform actions
+
+_Answer: B_
+
+**Question 2:** What are the two main components of an object in Object Oriented Programming?
+
+- A. State and Behavior
+- B. Template and Instance
+- C. Functions and Variables
+
+_Answer: A_
+
+## Step 4, 5, 6, 7
+
+**Question 3:** Which of the following methods in a class sets the title attribute?
+
+- A. `setTitle(String bookTitle)`
+- B. `getTitle()`
+- C. `setBook(String title)`
+
+_Answer: A_
+
+**Question 4:** In a class representing a vehicle, what is the purpose of the `this` keyword when used within a method?
+
+- A. To access a static variable
+- B. To differentiate between a member variable and a method argument with the same name
+- C. To call a method within the same class
+
+_Answer: B_
+
+**Question 5:** What is the primary purpose of using access modifiers such as `public` and `private` in Object-Oriented Programming?
+
+- A. To make code more readable
+- B. To control what external objects can access within a given object
+- C. To define the scope of a variable
+
+_Answer: B_
+
+**Question 6:** What is the purpose of `private` keyword in Java?
+
+- A. To make a variable or method accessible only within the class
+- B. To make a variable or method accessible outside the class
+- C. To make a variable or method static
+
+_Answer: A_
+
+**Question 7:** What are the methods used to access and modify private member variables in a class?
+
+- A. Public methods
+- B. Getter and Setter methods
+- C. Static methods
+
+_Answer: B_
+
+**Question 8:** What is the main principle that is violated when an object directly accesses the state of another object without using any methods?
+
+- A. Inheritance
+- B. Encapsulation
+- C. Polymorphism
+
+_Answer: B_
+
+**Question 9:** In a Java class, what is the purpose of a getter method?
+
+- A. To modify the value of a private member variable
+- B. To access the value of a private member variable
+- C. To perform a calculation with a private member variable
+
+_Answer: B_
+
+**Question 10:** Which of the following best describes the concept of state in Object-Oriented Programming?
+
+- A. The condition of an object at a given time, represented by member variables
+- B. The actions an object can perform, represented by methods
+- C. The relationship between two objects
+
+_Answer: A_
+
+**Question 11:** What is the primary reason for using a getter method in a Java class?
+
+- A. To ensure that an object's member variables are accessed according to the encapsulation principle
+- B. To define a new method that performs a calculation with an object's member variables
+- C. To initialize an object's member variables with default values
+
+_Answer: A_
+
+**Question 12:** Which of the following correctly defines a getter method for a private member variable `name` in a Java class?
+
+- A.
+
+```
+public String getName() {
+ return name;
+}
+```
+
+- B.
+
+```
+public void getName(String newName) {
+ name = newName;
+}
+```
+
+- C.
+
+```
+public String getName(String name) {
+ return this.name;
+}
+```
+
+_Answer: A_
+
+## Step 8,9
+
+**Question 13:** What is the primary purpose of a getter method?
+
+- A. To modify the value of an object's private member variable
+- B. To allow controlled access to an object's private member variable
+- C. To set a default value for an object's private member variable
+
+_Answer: B_
+
+**Question 14:** Consider the following code snippet. What will be the output?
+
+MotorBike.java
+
+```
+public class MotorBike {
+ private int speed;
+
+ public int getSpeed() {
+ return speed;
+ }
+}
+```
+
+MotorBikeRunner.java
+
+```
+public class MotorBikeRunner {
+ public static void main(String[] args) {
+ MotorBike bike = new MotorBike();
+ System.out.println("Current Bike Speed is : " + bike.getSpeed());
+ }
+}
+```
+
+- A. The code will not compile because the speed variable is not initialized
+- B. The output will be: `Current Bike Speed is : 0`
+- C. The output will be: `Current Bike Speed is : null`
+
+_Answer: B_
+
+**Question 15:** What are the default values for object member variables when they are not explicitly initialized?
+
+- A. `null` for reference types, and the type's minimum value for primitive types
+- B. `null` for reference types, and 0 for primitive types
+- C. The type's maximum value for primitive types, and `null` for reference types
+
+_Answer: B_
+
+## Step 10, 11
+
+#### Question 16
+
+What is one of the advantages of encapsulation in Object-Oriented Programming? - A. Code Reuse
+- B. Code Compression
+- C. Code Simplification
+
+**Answer: A. Code Reuse**
+
+#### Question 17
+
+In the given example, which method is responsible for setting the speed of a MotorBike object while ensuring it is not negative?
+- A. setSpeed()
+- B. increaseSpeed()
+- C. decreaseSpeed()
+
+**Answer: A. setSpeed()**
+
+#### Question 18
+
+How can code duplication be reduced when implementing validation checks for the `increaseSpeed()` and `decreaseSpeed()` methods?
+- A. By using separate validation checks for each method
+- B. By calling the `setSpeed()` method with appropriate parameters inside both methods
+- C. By using a global validation check
+
+**Answer: B. By calling the `setSpeed()` method with appropriate parameters inside both methods**
+
+#### Question 19
+
+What is the purpose of encapsulation in the context of protecting an object's state?
+- A. To prevent other objects from directly accessing the object's state
+- B. To allow other objects to directly access the object's state
+- C. To create a new object with the same state as the original object
+
+**Answer: A. To prevent other objects from directly accessing the object's state**
+
+#### Question 20
+
+In the given example, which method is used to start the MotorBike?
+- A. begin()
+- B. start()
+- C. initiate()
+
+**Answer: B. start()**
+
+## Step 13
+
+**Question 21: What is the purpose of a constructor in a Java class?**
+
+- a) To create an instance of the class with the specified initial state
+- b) To perform calculations on the class variables
+- c) To modify the state of an object after it has been created
+- d) To destroy an object when it is no longer needed
+
+**Answer: a) To create an instance of the class with the specified initial state**
+
+**Question 6: What is a default constructor in Java?**
+
+- a) A constructor that is automatically provided by the compiler if no other constructors are defined
+- b) A constructor with a single argument
+- c) A constructor that takes an unlimited number of arguments
+- d) A constructor that initializes all instance variables to their default values
+
+**Answer: a) A constructor that is automatically provided by the compiler if no other constructors are defined**
\ No newline at end of file
From a61fefb05efa460530f72f6867f5b7a3613bc8ba Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Tue, 4 Apr 2023 12:03:45 +0530
Subject: [PATCH 103/178] Update Q05-IntroductionToObjectOrientedProgrammin.md
---
01-Quiz/Q05-IntroductionToObjectOrientedProgrammin.md | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/01-Quiz/Q05-IntroductionToObjectOrientedProgrammin.md b/01-Quiz/Q05-IntroductionToObjectOrientedProgrammin.md
index ffb65ba6..47d31db7 100644
--- a/01-Quiz/Q05-IntroductionToObjectOrientedProgrammin.md
+++ b/01-Quiz/Q05-IntroductionToObjectOrientedProgrammin.md
@@ -215,7 +215,7 @@ In the given example, which method is used to start the MotorBike?
## Step 13
-**Question 21: What is the purpose of a constructor in a Java class?**
+**Question 22: What is the purpose of a constructor in a Java class?**
- a) To create an instance of the class with the specified initial state
- b) To perform calculations on the class variables
@@ -231,4 +231,4 @@ In the given example, which method is used to start the MotorBike?
- c) A constructor that takes an unlimited number of arguments
- d) A constructor that initializes all instance variables to their default values
-**Answer: a) A constructor that is automatically provided by the compiler if no other constructors are defined**
\ No newline at end of file
+**Answer: a) A constructor that is automatically provided by the compiler if no other constructors are defined**
From 2a7cc0b301b5df6b0457baf385c50b615a21e74f Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Tue, 4 Apr 2023 13:10:29 +0530
Subject: [PATCH 104/178] Update Q05-IntroductionToObjectOrientedProgrammin.md
---
...-IntroductionToObjectOrientedProgrammin.md | 59 +++++++++++++++++++
1 file changed, 59 insertions(+)
diff --git a/01-Quiz/Q05-IntroductionToObjectOrientedProgrammin.md b/01-Quiz/Q05-IntroductionToObjectOrientedProgrammin.md
index 47d31db7..ed60336c 100644
--- a/01-Quiz/Q05-IntroductionToObjectOrientedProgrammin.md
+++ b/01-Quiz/Q05-IntroductionToObjectOrientedProgrammin.md
@@ -232,3 +232,62 @@ In the given example, which method is used to start the MotorBike?
- d) A constructor that initializes all instance variables to their default values
**Answer: a) A constructor that is automatically provided by the compiler if no other constructors are defined**
+
+
+
+## Extra on Step 13
+
+
+**Question 23:** What is a constructor in Java?
+- a) A special method with the same name as the class
+- b) A method that returns a value
+- c) A method that can be called directly
+- d) A method that can only accept zero arguments
+
+**Answer:** A constructor in Java is a special method with the same name as the class, used to initialize objects of that class.
+Answer: a) A special method with the same name as the class
+
+----------
+
+**Question 24:** How is a constructor invoked in Java?
+- a) By calling the method directly
+- b) By using the new keyword while creating an object of the class
+- c) By declaring the constructor as static
+- d) By using the this keyword while creating an object of the class
+
+**Answer:** A constructor in Java is invoked by using the new keyword while creating an object of the class.
+Answer: b) By using the new keyword while creating an object of the class
+
+----------
+
+**Question 25:** Can a constructor accept multiple arguments in Java?
+- a) No, a constructor can only accept zero or one argument
+- b) Yes, a constructor can accept multiple arguments
+- c) Only the default constructor can accept multiple arguments
+- d) It depends on the access modifiers of the constructor
+
+**Answer:** Yes, a constructor can accept multiple arguments in Java.
+Answer: b) Yes, a constructor can accept multiple arguments
+
+
+----------
+
+**Question 26:** What is a default constructor in Java?
+- a) A constructor that accepts no arguments
+- b) A constructor that is defined by the programmer
+- c) A constructor that is generated by the compiler when no constructor is defined
+- d) A constructor that is called automatically when an object is created
+
+**Answer:** A default constructor in Java is a constructor that is generated by the compiler when no constructor is defined explicitly. It accepts no arguments and initializes the instance variables with their default values.
+Answer: c) A constructor that is generated by the compiler when no constructor is defined
+
+----------
+
+**Question 27:** What happens when a class has no constructor defined in Java?- a) The code fails to compile
+b) A default constructor is generated by the compiler
+c) The code compiles and runs without any issues
+d) The class cannot be instantiated
+
+**Answer:** If a class has no constructor defined in Java, the compiler generates a default constructor that accepts no arguments. If the class explicitly defines a constructor, the compiler does not provide a default constructor.
+
+Answer: b) A default constructor is generated by the compiler. However, if a class has a constructor defined by the programmer, the compiler will not add a default constructor unless it is explicitly defined by the programmer.
From aaef9423cdb640a50a306e17ec0b5d0acd91d8f6 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Wed, 5 Apr 2023 11:07:20 +0530
Subject: [PATCH 105/178] .
---
.../06-PrimitiveDataTypesAndAlternatives.md | 0
txt_help.md | 1199 +++++++++++++++++
2 files changed, 1199 insertions(+)
create mode 100644 02-CodeChallenge/06-PrimitiveDataTypesAndAlternatives.md
create mode 100644 txt_help.md
diff --git a/02-CodeChallenge/06-PrimitiveDataTypesAndAlternatives.md b/02-CodeChallenge/06-PrimitiveDataTypesAndAlternatives.md
new file mode 100644
index 00000000..e69de29b
diff --git a/txt_help.md b/txt_help.md
new file mode 100644
index 00000000..7a7d5687
--- /dev/null
+++ b/txt_help.md
@@ -0,0 +1,1199 @@
+## Primitive Data Types
+
+Earlier, we looked at basic Java types (including ```int```, ```double``` and ```boolean```), and got a little familiar with them.
+
+We used literal values, declared variables and formed expressions using them.
+
+Java **primitive types** include:
+* Integer Types
+ * ```byte```
+ * ```short```
+ * ```int```
+ * ```long```
+* Floating-Point Types
+ * ```float```
+ * ```double```
+* Character Type
+ * ```char```
+* Logical Type
+ * ```boolean```
+
+In this section, let's play with each of these types to understand them further.
+
+### Step 01: The Integer Types
+
+Integers are not much of a mystery, are they? They've been part of us since our school days, and we normally prefer them over other numbers (they scare us less!).
+
+Java supports them with ease, and we have coded quite a few examples using them, already.
+
+Java also has a **wrapper class** corresponding to each of them, which make their primitive versions more versatile. The wrapper classes we are talking about are:
+
+* ```Byte```: for ```byte```
+* ```Short```: matching ```short```
+* ```Integer``` corresponding to ```int```
+* ```Long```: about ```long```
+
+Let's see how we can work with them.
+
+##### Snippet-01 : Integer Sizes
+
+Look at all the information these tiny classes hold for you! As they say, **_"fore-warned is fore-armed"_**. Depending on the data (range and size) your program handles, you decide which types to use, to store them.
+
+```java
+
+ jshell> Byte.SIZE
+ $1 ==> 8
+ jshell> Byte.BYTES
+ $2 ==> 1
+ jshell> Byte.MAX_VALUE
+ $3 ==> 127
+ jshell> Byte.MIN_VALUE
+ $4 ==> -128
+ jshell> Short.BYTES
+ $5 ==> 2
+ jshell> Integer.BYTES
+ $6 ==> 4
+ jshell> Long.BYTES
+ $7 ==> 8
+ jshell> Short.MAX_VALUE
+ $8 ==> 32767
+ jshell> Integer.MAX_VALUE
+ $8 ==> 2147483647
+ jshell> int i = 100000;
+ i ==> 100000
+ jshell> long l = 50000000000;
+ | Error:
+ | integer number too large: 50000000000
+ | long l = 50000000000;
+ |_________^
+ jshell> long l = 50000000000l;
+ l ==> 50000000000
+ jshell>
+
+```
+
+#### Integer Type Conversions
+
+Problems will (and should) arise if we attempt to store large data into smaller bins. The compiler warns the programmer about such issues by flagging errors. However, if the programmer is aware of the risks and intends to go ahead, **explicit casts** are her tools to push the code through.
+
+Operations in the other direction (storing a smaller data value in a larger bin), is a piece of cake for the compiler. Such a conversion is called an **implicit cast**.
+
+##### Snippet-02 : Integer Type Conversions
+
+Attempting to store a ```long``` value into an ```int``` variable will give us a compiler error. However, you can use an explicit cast, such as ```i = (int) l;```.
+
+```java
+
+ jshell> int i = 100000;
+ i ==> 100000
+ jshell> long l = 50000000000l;
+ l ==> 50000000000
+ jshell> i = l;
+ | Error :
+ | incompatible types: possible lossy conversion from long to int
+ | i = l;
+ |_____^
+ jshell> i = (int) l;
+ i ==> -1539607552
+ jshell> l = i;
+ l ==> -1539607552
+ jshell>
+
+```
+
+**_The compiler is not responsible for the type-safety of this statement. The onus is on me, the programmer._**
+
+Remember our earlier statement on possible incorrect program behavior? As you can see, a different value got stored in ```i```.
+
+#### Summary
+
+In this step, we:
+
+* Explored the wrapper classes present for the primitive integer types
+* Understood the different capacities and data ranges of these types
+* Examined how to use explicit and implicit casts
+
+### Step 02: Integer Representations, And Other Puzzles
+
+In a decimal system, the allowed digits are ```0``` through ```9```. When a value of ```10``` is encountered, the number of digits increases by 1, and its representation is "```10```".
+
+Those familiar with number systems would know that decimal is not the only system that computers understand.
+
+Other number systems that the Java language supports are **Octal** (Base-8) and **Hexadecimal** (Base-16).
+
+In an Octal system, the allowed digits are ```0``` through ```7```, and a value ```8``` is represented by "```010```". The leading ```0``` is added only to distinguish the octal format from the decimal one.
+
+In a Hexadecimal system, the allowed digits are ```0``` through ```9```, followed by ```a``` through ```f``` (or ```A``` through ```F```). A value of ```16``` is represented by "```0x10```". Here, a leading ```0x``` is added to help the compiler recognize Hexa decimal representation.
+
+Let's see how Java supports these three number systems.
+
+##### Snippet-01 : Storing Octal and Hexadecimal in Integer types
+
+There are no number-system specific integer types in Java! The same ```int``` type is used to store decimal, octal and hexadecimal values.
+
+If we adhere to to number system conventions about valid digits and understand the compiler hints, we get no surprises.
+
+```java
+
+ jshell> int eight = 010;
+ eight ==> 8
+ jshell> int sixteen = 0x10;
+ sixteen ==> 16
+ jshell> int fifteen = 0xf;
+ fifteen ==> 15
+ jshell> int eight = 08;//8 is invalid octal digit
+ | Error:
+ | integer number too large : 08
+ | int eight = 08;
+ |___________^
+ jshell> int big = 0xbbaacc;
+ big ==> 12298956
+ jshell>
+
+```
+
+##### Snippet-02 : More Integer Type-casting
+
+There are two kinds of assignments:
+* Literal-to-variable assignment: With ```short s = 123456;```, the data is clearly out of range (this is known at compile-time). The compiler flags an error.
+* Variable-to-variable assignment: Consider ```sh = in;```. The value stored in ```int in``` at that stage was ```4567```, which is well within the range of the ```short``` type. The compiler chooses not to take chances and flags an error. This can again be preempted with a explicit cast `sh = (short) in`.
+
+
+```java
+
+ jshell> byte b = 128;
+ | Error:
+ | incompatible types: possible lossy conversion from int to byte
+ | byte b = 128;
+ |_________^--^
+ jshell> short s = 123456;
+ | Error:
+ | incompatible types: possible lossy conversion from int to short
+ | short s = 123456;
+ |__________^-------^
+ jshell> short sh = 3456;
+ sh ==> 3456
+ jshell> int in = 4567;
+ in ==> 3456
+ jshell> sh = in;
+ | Error:
+ | incompatible types: possible lossy conversion from int to short
+ | sh = in;
+ |______^
+ jshell> sh = (short) in;
+ sh ==> 4567
+ jshell> int num = sh;
+ num ==> 4567
+ jshell>
+
+```
+
+#### Built-In Operators For Integer Types
+
+We already had a glimpse of arithmetic operators for the integer types:
+* ```+```
+* ```-```
+* ```*```
+* ```/```
+* ```%```
+* ```++``` (both prefix and post-fix increment)
+* ```--``` (both prefix and post-fix increment)
+
+The increment and decrement operators are an interesting case, as they are actually short-hands for multiple statements. When we use their prefix and post-fix versions, we need to look out for side-effects.
+
+##### Snippet-03 : Increment & Decrement Operators
+
+With post-fix increment, such as in ```int j = i++;```, the increment takes place *after* the assignment is done. ```j``` gets the value before increment.
+```java
+
+ jshell> int i = 10;
+ i ==> 10
+ jshell> int j = i++;
+ j ==> 10
+ jshell> i
+ i ==> 11
+```
+
+When prefix increment is involved, as with ```int n = ++m;```, the increment is carried out *before* the assignment. ```n``` gets the value after increment.
+
+```java
+ jshell> int m = 10;
+ m ==> 10
+ jshell> int n = ++m;
+ n ==> 11
+ jshell> m
+ m ==> 11
+```
+
+With post-fix decrement, as with ```int l = k--;```, the decrement occurs *after* the assignment is done. As far as prefix decrement is concerned, such as in ```int q = --p;```, the decrement is performed *before* the assignment.
+
+```java
+ jshell> int k = 10;
+ k ==> 10
+ jshell> int l = k--;
+ l ==> 10
+ jshell> k
+ k ==> 9
+ jshell> int p = 10;
+ p ==> 10
+ jshell> int q = --p;
+ q ==> 9
+ jshell> p
+ p ==> 9
+ jshell>
+
+```
+
+#### Summary:
+
+In this step, we:
+
+* Looked at the number-systems supported in Java for integers
+* Examined how prefix and post-fix versions work for increment and decrement operators
+
+- - -
+### Step 03: Classroom Exercise CE-01 (With Solutions)
+
+#### Exercise Set
+
+1. Create a Java ```class``` ```BiNumber``` that stores a pair of integers, and has the following functionality:
+
+ * Can be created by passing its initial two numbers to store
+ * Must Support Addition and Multiplication operations on the stored integers
+ * An operation to double the values of both numbers
+ * Operations to access each number individually
+
+In short, we must be able to write code like this in the ```main``` method of our runner class:
+
+```java
+
+ BiNumber numbers = new BiNumber(2, 3);
+ System.out.println(numbers.add());
+ System.out.println(numbers.multiply());
+ numbers.double();
+ System.out.println(numbers.getNumber1());
+ System.out.println(numbers.getNumber2());
+
+```
+
+#### Solution to CE-01
+
+**_BiNumber.java_**
+
+```java
+
+ package com.in28minutes.primitive.datatypes;
+
+ public class BiNumber {
+ private int number1;
+ private int number2;
+
+ public BiNumber(int number1, int number2) {
+ this.number1 = number1;
+ this.number2 = number2;
+ }
+
+ public int add() {
+ return number1 + number2;
+ }
+
+ public int multiply() {
+ return number1 * number2;
+ }
+
+ public void doubleValue() {
+ number1 *= 2;
+ number2 *= 2;
+ }
+
+ public int getNumber1() {`
+ return number1;
+ }
+
+ public int getNumber2() {
+ return number2;
+ }
+
+ public void setNumber1(int number1) {
+ this.number1 = number1;
+ }
+
+ public void setNumber2(int number2) {
+ this.number2 = number2;
+ }
+ }
+
+```
+
+**_BiNumberRunner.java_**
+
+```java
+
+ package com.in28minutes.primitive.datatypes;
+
+ public class BiNumberRunner {
+ public static void main(String[] args) {
+ BiNumber numbers = new BiNumber(2, 3);
+ System.out.println(numbers.add());
+ System.out.println(numbers.multiply());
+ numbers.doubleValue();
+ System.out.println(numbers.getNumber1());
+ System.out.println(numbers.getNumber2());
+ }
+ }
+
+```
+
+**_Console Output_**
+
+_5_
+
+_6_
+
+_4_
+
+_6_
+
+### Step 05: Floating-Point Types
+
+You would recall there are two types in Java to support floating-point numbers:
+* ```double```: The default type for floating-point literals, with a capacity of 8 bytes
+* ```float```: A narrower, less precise representation for floating-point data. It has a capacity of 4 bytes.
+
+Let's quickly refresh what we know, with a few code snippets.
+
+##### Snippet-01 : double and float
+
+Default floating point type in Java is `double`. A ```float``` literal must be accompanied with a trailing ```f``` or ```F```.
+
+
+```java
+
+ jshell> float f = 34.5;
+ | Error:
+ | incomaptible types: possible lossy conversion from double to float
+ | float f = 34.5;
+ |_________^---^
+ jshell> float f = 34.5f;
+ f ==> 34.5
+ jshell> float fl = 34.5F;
+ fl ==> 34.5
+ jshell> double d = 34.5678;
+ d ==> 34.5678
+ jshell> float flo = d;
+ | Error:
+ | incomaptible types: possible lossy conversion from double to float
+ | float flo = d;
+ |__________^
+ jshell> float flo = (float) d;
+ flo ==> 34.567
+ jshell>
+
+```
+
+##### Snippet-02 : Operators for type double
+
+You can use operators `++`, `--` and `%` on double.
+
+```java
+
+jshell> double dbl = 34.5678;
+dbl ==> 34.5678
+
+jshell> dbl++
+$3 ==> 34.5678
+
+jshell> dbl
+dbl ==> 35.5678
+
+jshell> dbl--
+dbl ==> 35.5678
+jshell> dbl % 5
+dbl ==> 4.567799999999998
+```
+
+You would need an explicit cast to convert a float to an integer value `int i = (int)f`.
+
+```java
+ jshell> float f = 34.5678f;
+ f ==> 34.5678
+ jshell> int i = f;
+ | Error:
+ | incomaptible types: possible lossy conversion from float to int
+ | int i = f;
+ |_______^
+ jshell> int i = (int)f;
+ i ==> 34
+ jshell> float fl = i;
+ fl ==> 34.0
+ jshell>
+
+```
+#### Summary
+
+In this step, we:
+
+* Saw how we create literals and variables of the floating-point types
+* Understood the differences between ```double``` and ```float```
+
+### Step 06: Introducing BigDecimal
+
+Compact though they are, ```double``` and ```float``` are not very precise representations of floating-point numbers.
+
+In fact, they are not used in computations that require high degrees for accuracy, such as scientific experiments and financial applications. The next example shows you why.
+
+
+```java
+
+ jshell> 34.56789876 + 34.2234
+ $1 ==> 68.79129875999999
+```
+
+The literal expression ```34.56789876 + 34.2234``` should evaluate to ```68.79129876```. Above addition is not really accurate.
+
+This is due to a flaw in floating-point representations, used in the ```double``` and ```float``` types.
+
+The ```BigDecimal``` class was introduced in Java to tide over these problems.
+
+Accuracy of ```BigDecimal``` representation is retained only when ```String``` literals are used to build it.
+
+
+
+```java
+
+ jshell> BigDecimal number1 = new BigDecimal("34.56789876");
+ number1 ==> 34.56789876
+ jshell> BigDecimal number2 = new BigDecimal("34.2234");
+ number2 ==> 34.2234_
+```
+
+A ```BigDecimal``` type can be used to create only **immutable** objects. The values in an *immutable* object cannot be changed after creation.
+
+You can see that the value of number1 is not changed on executing `number1.add(number2)`. To get the result of the sum, we create a new variable `sum`.
+
+```java
+ jshell> number1.add(number2);
+ $2 ==> 68.79129876
+ jshell> number1
+ number1 ==> 34.56789876
+ jshell> BigDecimal sum = number1.add(number2);
+ sum ==> 68.79129876
+```
+
+#### Summary
+
+In this step, we:
+
+* Learned that ```double``` and ```float``` are not very precise data types
+* Were introduced to the ```BigDecimal``` built-in data type
+* Understood that ```BigDecimal``` is immutable
+* Saw that accuracy is best achieved when you construct ```BigDecimal``` data using string literals
+
+### Step 06: BigDecimal Operations
+
+Let's look at a few other operations defined in the ```BigDecimal``` class.
+
+##### Snippet-01: Arithmetic Operations
+
+All BigDecimal operations support only BigDecimal operands.
+
+```java
+
+ jshell> BigDecimal number1 = new BigDecimal("11.5");
+ number1 ==> 34.56789876
+ jshell> BigDecimal number2 = new BigDecimal("23.45678");
+ number2 ==> 23.45678
+ jshell> number1.add(number2);
+ $1 ==> 34.95678
+```
+
+```BigDecimal``` does not jell well with primitive types.
+
+```java
+ jshell> int i = 5;
+ i ==> 5
+ jshell> number1.add(i);
+ | Error:
+ | incompatible types: int cannot be converted to java.math.BigDecimal
+ | number1.add(i);
+ |_____________^
+```
+
+We can add, multiple, divide or subtract `BigDecimal` values.
+
+```java
+ jshell> number1.add(new BigDecimal(i));
+ $2 ==> 16.5
+ jshell> number1.multiply(new BigDecimal(i));
+ $3 ==> 67.5
+ jshell> number1.divide(new BigDecimal(100));
+ $4 ==> 0.115
+ jshell>
+
+```
+
+#### Summary
+
+In this step, we:
+
+* Explored the ```BigDecimal``` methods for doing some basic arithmetic
+* Found that ```BigDecimal``` has constructors accepting most basic Java numeric types
+
+### Step 07: Classroom Exercise CE-02
+
+#### Exercise-Set
+
+Write a Program that does a Simple Interest computation for a Principal amount. Recall that the formula for such a calculation is:
+
+`Total amount (TA) = Principal Amount (PA) + ( PA * Simple Interest (SI) Rate * Duration In Years (N))`
+
+In essence, write a ```SimpleInterestCalculator``` ```class``` that can be used in the following manner:
+
+```java
+
+ SimpleInterestCalculator calculator = new SimpleInterestCalculator("4500.00", "7.5");
+ BigDecimal totalValue = calculator.calculateTotalValue(5); //5 year duration
+ System.out.println(totalValue);
+
+```
+
+#### Solution To CE-02
+
+**_SimpleInterestCalculatorRunner.java_**
+
+```java
+
+ package com.in28minutes.primitive.datatypes;
+ import java.math.BigDecimal;
+
+ public class SimpleInterestCalculatorRunner {
+ public static void main(String[] args) {
+ SimpleInterestCalculator calculator = new SimpleInterestCalculator("4500.00", 7.5");
+ BigDecimal totalValue = calculator.calculateTotalValue(5); //5 year duration
+ System.out.println(totalValue);
+ }
+ }
+
+```
+
+**_SimpleInterestCalculator.java_**
+
+```java
+
+ package com.in28minutes.primitive.datatypes;
+ import java.math.BigDecimal;
+
+ public class SimpleInterestCalculatorRunner {
+ BigDecimal principal;
+ BigDecimal interest;
+
+ public SimpleInterestCalculator(String principal, String interest) {
+ this.principal = new BigDecimal(principal);
+ this.interest = new BigDecimal(interest).divide(new BigDecimal(100));
+ }
+
+ public BigDecimal calculateTotalValue(int noOfYears)
+ //Total Value = Principal + Principal * Interest* Years
+ BigDecimal totalValue = prinipal.add(principal.multiply(interest).multiply(new BigDecimal(noOfYears)));
+ return totalValue;`
+ }
+}
+
+```
+
+**_Console Output:_**
+
+_6187.50000_
+
+#### Tip: The ```import``` Statement
+
+The Java ```import``` statement is Required in each source file that uses a ```class``` from another ```package```. Hence, both **_SimpleInterestCalculator.java_** (```class``` definition) and **_SimpleInterestCalculatorRunner.java_** (runner ```class``` definition) need to import ```class``` ```java.math.BigDecimal```.
+
+```package java.lang.*``` is imported by default.
+
+The ```.*``` suffix indicates that all classes in the ```package``` ```java.lang``` are being imported.
+
+#### Summary
+
+In this step, we:
+
+* Used ```BigDecimal``` values in a stand-alone Java program
+* Learnt how to make use of built-in Java packages, through the ```import``` statement
+
+### Step 08: ```boolean```, Relational and Logical Operators
+
+The Java ```boolean ``` data type is one that holds only one of two values: ```true``` or ```false```. Both labels are case-sensitive. We have seen examples of built-in comparison operators, such as ```==```, ```!=``` and ```>```, that evaluate expressions to give us ```boolean``` results. Let us do a quick recap of some of these.
+
+##### Snippet-01 : Relational Operators : Recap
+
+Relational Operators are used mainly for comparison. They accept operands of non-```boolean``` primitive data types, and return a ```boolean``` value.
+
+```java
+
+ jshell> int i = 7;
+ i ==> 7
+ jshell> i > 7;
+ $1 ==> false
+ jshell> i >= 7;
+ $2 ==> true
+ jshell> i < 7;
+ $3 ==> false
+ jshell> i <= 7;
+ $4 ==> true
+ jshell> i == 7;
+ $5 ==> true
+ jshell> i == 8;
+ $6 ==> false
+ jshell>
+
+```
+
+#### Logical Operators
+
+Java also has logical operators that are used in expressions. Logical operators expect ```boolean``` operands. Expressions involving these are used for forming ```boolean``` conditions in code, including within ```if```, ```for``` and ```while``` statements. The prominent logical operators are:
+
+* ```&&``` : logical **AND**
+* ```||``` : **OR**
+* ```!``` : **NOT**
+
+Let's learn how we use them in our code.
+
+##### Snippet-02 : Logical Operators
+
+We would want to find if `i` is between `15` and `25`. An expression `i >= 15 && i <= 25` can be used. Details below.
+
+```java
+
+ jshell> int i = 17;
+ i ==> 17
+ jshell> i >= 15
+ $1 ==> true
+ jshell> i <= 25
+ $2 ==> true
+ jshell> i >= 15 && i <= 25
+ $3 ==> true
+ jshell> i == 30;
+ i ==> 30
+ jshell> i >= 15 && i <= 25
+ $4 ==> false
+ jshell> i == 5;
+ i ==> 30
+ jshell> i >= 15 && i <= 25
+ $5 ==> false
+```
+
+An expression with```&&``` evaluates to ```true``` only if **both** its ```boolean``` operands evaluate to ```true```.
+
+```java
+ jshell> true && true
+ $6 ==> true
+ jshell> true && false
+ $7 ==> false
+ jshell> false && true
+ $8 ==> false
+ jshell> false && false
+ $9 ==> false
+ jshell>
+
+```
+
+##### Snippet-02 Explained
+
+The next example helps us visualize truth tables for the prominent logical operators.
+
+```java
+
+ jshell> true || true
+ $1 ==> true
+ jshell> true || false
+ $2 ==> true
+ jshell> false || true
+ $3 ==> true
+ jshell> false || false
+ $4 ==> false
+ jshell> true ^ true
+ $5 ==> false
+ jshell> true ^ false
+ $6 ==> true
+ jshell> false ^ true
+ $7 ==> true
+ jshell> false ^ false
+ $8 ==> false
+ jshell> !true
+ $9 ==> false
+ jshell> !false
+ $10 ==> true
+ jshell> int x = 6;
+ x ==> 6
+ jshell> !(x > 7)
+ $11 ==> true
+ jshell>
+
+```
+
+#### Summary
+
+In this step, we:
+
+* We're introduced to the ```boolean``` primitive type
+* Understood where logical operators are used in Java programs
+* Explored the truth-tables of commonly used logical operators
+
+### Step 09: Short-Circuit Evaluation (With Puzzles)
+
+Consider code below. The expression ```j > 15 && i++ > 5``` evaluates to ```false``` as expected. `j>15` is `false` as `j` has a value of `15`.
+
+
+```java
+
+ jshell> int j = 15;
+ j ==> 15
+ jshell> int i = 10;
+ i ==> 10
+ jshell> j > 15 && i++ > 5
+ $1 ==> false
+ jshell> j
+ j ==> 15
+ jshell> i
+ i ==> 10
+```
+
+You can also observe that the value of i remains unchanged `10`.
+
+Why? Because ```i++ > 5``` was not even evaluated.
+Why? `&&` is lazy. It saw that `j > 15` is false. Irrespective of the result of second expression, the result of this `&&` would be false. So, it does NOT evaluate the second expression.
+
+***A more detailed explanation***
+
+The expression ```j > 15 && i++ > 5``` was scanned from left to right. As the first operand to ```&&``` evaluated to ```false```, the compiler got lazy. `&&` avoids evaluating expressions that don't affect the final result. The optimization has a name: **Short-Circuit Evaluation**, also called **lazy evaluation**.
+
+
+The logical operator ```&``` is another version of the logical **AND** operation, that does away with lazy evaluation.
+
+Both operands to ```&``` are always evaluated.
+
+```java
+
+ jshell> j > 15 & i++ > 5
+ $1 ==> false
+ jshell> j
+ j ==> 15
+ jshell> i
+ i ==> 11
+ jshell>
+
+```
+
+Similarly, the logical **OR** operator also has two versions:
+* The ```||``` operator we saw earlier. This exhibits lazy evaluation.
+* The ```|``` operator, without lazy evaluation.
+
+It is bad programming practice for our code to depend on the compiler's lazy evaluation. It makes code less readable, and can hide difficult-to-fix software bugs. It obviously adds to the code maintenance burden, so don't do it unless you like being in your peers' bad books.
+
+#### Summary
+
+In this step, we:
+
+* Examined conditions involving logical operators, that had lazy evaluation
+* Observed that the lazy evaluation depends on the operator's truth-table
+* Saw versions of the operators without lazy evaluation
+* Learned that code depending on lazy-evaluation, is less readable
+
+### Step 10: Character Types
+
+Earlier, we explored how we could store basic keyboard characters(called **ascii-code** characters), such as:
+* Upper-Case and lower-case letters (A-Z, a-z)
+* Numeric characters (0-9)
+* Punctuation and other special characters (such as ',', '$', '{', etc.)
+
+Turns out Java supports a much larger family of character encoding sets, called **Unicode**. All Unicode characters can be input to, understood and processed by, as well as output from your code.
+
+##### Snippet-01 : Unicode characters
+
+Not all Unicode characters can be input from your keyboard. But Java allows you to handle their values from your code, if you deal correctly with their format.
+
+```java
+
+ jshell> char ch = '"';
+ ch ==> '"'
+ jshell> char c = '\u0022';
+ c ==> '"'
+```
+
+Integer values can be stored in ```char``` variables. If the value is within a meaningful range, it also corresponds to the **ascii** value of a keyboard character.
+
+```java
+ jshell> char cn = 65;
+ cn ==> 'A'
+```
+
+Integer arithmetic can be performed on `char` data.
+
+```java
+ jshell> cn++
+ $1 ==> 'A'
+ jshell> cn
+ $2 ==> 'B'
+ jshell> ++cn
+ $3 ==> 'C'
+ jshell> cn + 5
+ $4 ==> 72
+ jshell> cn
+ cn ==> 'C'
+ jshell> (int)cn
+ cn ==> 67
+ jshell>
+
+```
+
+
+#### Summary
+
+In this step, we:
+
+* Were introduced the the ```char``` data type
+* Learned that Unicode takes the character set beyond your keyboard
+* An ascii character is ```char``` value, encoded by an integer value
+
+### Step 11: Programming Exercise PE-02
+
+#### Exercise Set
+
+1. Write a Java class ```MyChar``` that is a special type of ```char```. An object of type ```MyChar``` is created round an input ```char``` data element, and has operations that do the following:
+ * Check if the input character is a:
+ * Numeric Digit
+ * Letter of the Alphabet
+ * Vowel (Either upper-case or lower-case)
+ * Consonant (Either upper-case or lower-case) NOTE: A letter is a consonant if not a vowel
+ * Print all the letters of the Alphabet in
+ * Upper-Case
+ * Lower-Case
+
+In Essence, a runner ```class``` for ```MyChar``` would have its ```main``` method run code similar to:
+
+```java
+
+ MyChar myChar = new MyChar('c');
+ System.out.println(myChar.isDigit());
+ System.out.println(myChar.isAlphabet());
+ System.out.println(myChar.isVowel());
+ System.out.println(myChar.isConsonant());
+ myChar.printLowerCaseAlphabets();
+ myChar.printUpperCaseAlphabets();
+
+```
+
+### Step 12: Solution To PE-02, Part 1 - ```isVowel()```
+
+**_MyCharRunner.java_**
+
+```java
+
+ package com.in28minutes.primitive.datatypes;
+
+ public class MyCharRunner {
+ public static void main(String[] args) {
+ MyChar myChar = new MyChar('c');
+ System.out.println(myChar.isVowel());
+ }
+ }
+
+```
+
+**_MyChar.java_**
+
+```java
+
+ package com.in28minutes.primitive.datatypes;
+
+ public class MyChar {
+ private char ch;
+
+ public MyChar(char ch) {
+ this.ch = ch;
+ }
+
+ public boolean isVowel() {
+ if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
+ return true;
+ }
+ if(ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') {
+ return true;
+ }
+ return false;
+ }
+ }
+
+```
+
+**_Console Output_** :
+
+_false_
+
+### Step 13: Solution To PE-02, Part 2 - ```isDigit()```
+
+**_MyCharRunner.java_**
+
+```java
+
+ package com.in28minutes.primitive.datatypes;
+
+ public class MyCharRunner {
+ public static void main(String[] args) {
+ MyChar myChar = new MyChar('c');
+ System.out.println(myChar.isDigit());
+ System.out.println(myChar.isVowel());
+ }
+ }
+
+```
+
+**_MyChar.java_**
+
+```java
+
+ package com.in28minutes.primitive.datatypes;
+
+ public class MyChar {
+ private char ch;
+
+ public MyChar(char ch) {
+ this.ch = ch;
+ }
+
+ public boolean isVowel() {
+ if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
+ return true;
+ }
+
+ if(ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') {
+ return true;
+ }
+ return false;
+ }
+
+ public boolean isDigit() {
+ if(ch >= 48 && ch <= 57) {
+ return true;
+ }
+ return false;
+ }
+
+}
+
+```
+
+**_Console Output_** :
+
+_false_
+
+_false_
+
+### Step 14: Solution To PE-02, Part 3 - Other Methods
+
+**_MyCharRunner.java_**
+
+```java
+
+ package com.in28minutes.primitive.datatypes;
+
+ public class MyCharRunner {
+ public static void main(String[] args) {
+ MyChar myChar = new MyChar('c');
+ System.out.println(myChar.isDigit());
+ System.out.println(myChar.isAlphabet());
+ System.out.println(myChar.isVowel());
+ System.out.println(myChar.isConsonant());
+ myChar.printLowerCaseAlphabets();
+ myChar.printUpperCaseAlphabets();
+ }
+ }
+
+```
+
+**_MyChar.java_**
+
+```java
+
+ package com.in28minutes.primitive.datatypes;
+
+ public class MyChar {
+ private char ch;
+
+ public MyChar(char ch) {
+ this.ch = ch;
+ }
+
+ public boolean isVowel() {
+ if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
+ return true;
+ }
+ if(ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') {
+ return true;
+ }
+ return false;
+ }
+
+ public boolean isConsonant() {
+ if(isAlphabet() && !(isVowel())) {
+ return true;
+ }
+ return false;
+ }
+
+ public boolean isDigit() {
+ if(ch >= 48 && ch <= 57) {
+ return true;
+ }
+ return false;
+ }
+
+ public boolean isAlphabet() {
+ if(ch >= 97 && ch <= 122) {
+ return true;
+ }
+ if(ch >= 65 && ch <= 90) {
+ return true;
+ }
+ return false;
+ }
+
+ public void printLowerCaseAlphabets() {
+ for(char ch='a'; ch <= 'z'; ch++) {
+ System.out.println(ch);
+ }
+ }
+
+ public void printUpperCaseAlphabets() {
+ for(char ch='A'; ch <= 'Z'; ch++) {
+ System.out.println(ch);
+ }
+ }
+ }
+
+```
+
+**_Console Output_** :
+
+_false_
+
+_true_
+
+_false_
+
+_true_
+
+a
+
+b
+
+c
+
+d
+
+e
+
+f
+
+g
+
+h
+
+i
+
+j
+
+k
+
+l
+
+m
+
+n
+
+o
+
+p
+
+q
+
+r
+
+s
+
+t
+
+u
+
+v
+
+w
+
+x
+
+y
+
+z
+
+A
+
+B
+
+C
+
+D
+
+E
+
+F
+
+G
+
+H
+
+I
+
+J
+
+K
+
+L
+
+M
+
+N
+
+O
+
+P
+
+Q
+
+R
+
+S
+
+T
+
+U
+
+V
+
+W
+
+X
+
+Y
+
+Z
+
+### Step 15: The Primitive Types - A Review
+
+In this section, we built on our knowledge of the primitive Java types.
+
+* We first got familiar with built-in wrappers for the integer types, that store useful type information.
+* Going from the integer to the floating-point types, we examined type compatibility, and how the compiler warns you about common pitfalls. We used explicit casts to force type conversions, and learned that implicit type conversions are quite common.
+* We moved on to the ```BigDecimal``` class, a floating-point type with greater precision and accuracy.
+* Next in line was ```boolean```, where we built on what we know of logical expressions. We focused on the logical operators, more so on short-circuit evaluation of their expressions.
+* We saw how dependency on side-effects, and on lazy evaluation, is not a good programming practice.
+* Finally, we got to the ```char``` type, and were pleasantly surprised to know, that the keyboard is not the limit.
From cacd7ce678d88bbd0bd56340bea7353e70cfa0dc Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Wed, 5 Apr 2023 12:14:55 +0530
Subject: [PATCH 106/178] .
---
.../06-PrimitiveDataTypesAndAlternatives.md | 253 ++++++++++++++++++
1 file changed, 253 insertions(+)
diff --git a/02-CodeChallenge/06-PrimitiveDataTypesAndAlternatives.md b/02-CodeChallenge/06-PrimitiveDataTypesAndAlternatives.md
index e69de29b..5107ab52 100644
--- a/02-CodeChallenge/06-PrimitiveDataTypesAndAlternatives.md
+++ b/02-CodeChallenge/06-PrimitiveDataTypesAndAlternatives.md
@@ -0,0 +1,253 @@
+
+# Exercise 2: Calculating Average Speed of Formula 1 Cars in a Race using Java
+
+
+
+
+
+## Instructions
+
+### Problem Statement:
+
+You have been tasked with creating a Java program that calculates the average speed of a group of Formula 1 cars during a race, taking into account their total distance covered and the time taken for each car. Your program should use the following primitive data types: int, long, float, and double.
+
+### Instructions:
+
+1. Create a Java class called `Formula1RaceRunner`.
+2. Define a method named `calculateAverageSpeed` that takes three parameters:
+ - an `int` named `numberOfCars`, representing the number of Formula 1 cars in the race
+ - a `long` named `totalDistance`, representing the total distance covered by all cars in meters
+ - a `float` named `totalTime`, representing the total time taken by all cars in seconds
+3. In the `calculateAverageSpeed` method, calculate the average distance covered by each car by dividing the total distance by the number of cars.
+4. Calculate the average time taken by each car by dividing the total time by the number of cars.
+5. Calculate the average speed by dividing the average distance by the average time. Return the result as a `double`.
+6. Create a `main` method in the `Formula1RaceRunner` class.
+7. In the `main` method, define variables for the number of cars, total distance, and total time. Assign appropriate values to these variables.
+8. Call the `calculateAverageSpeed` method with the defined variables as arguments and store the result in a `double` variable named `averageSpeed`.
+9. Print the `averageSpeed` to the console, formatted to one decimal place.
+
+By following these instructions, you will create a Java program that calculates the average speed of a group of Formula 1 cars during a race, considering their total distance covered and the time taken for each car, using the requested primitive data types.
+
+#### Output:
+
+**When you run the `Formula1RaceRunner` class with your code, you will get the following output:**
+
+```
+Average speed for the Formula 1 cars: 16.7 m/s
+```
+
+This output shows the calculated average speed for the Formula 1 cars during the race, considering their total distance covered and the time taken for each car. The result is formatted to one decimal place.
+
+
+## Hints
+
+Here are the hints:
+
+1. **Hint 1**: Create a `Formula1RaceRunner` class and define a method named `calculateAverageSpeed` that takes three parameters - `numberOfCars`, `totalDistance`, and `totalTime`.
+2. **Hint 2**: Calculate `averageDistance` by dividing `totalDistance` by `numberOfCars`. Calculate `averageTime` by dividing `totalTime` by `numberOfCars`.
+3. **Hint 3**: Calculate the `averageSpeed` by dividing `averageDistance` by `averageTime`. Return the result as a `double`.
+4. **Hint 4**: Create a `main` method in the `Formula1RaceRunner` class. Define variables for the `numberOfCars`, `totalDistance`, and `totalTime`. Assign appropriate values to these variables.
+5. **Hint 5**: Call the `calculateAverageSpeed` method with the defined variables as arguments and store the result in a `double` variable named `averageSpeed`.
+6. **Hint 6**: Print the `averageSpeed` to the console, formatted to one decimal place using `System.out.printf()`.
+
+
+
+
+## Solution Explanation
+Here is the solution explanation with code in Markdown format:
+
+To solve this problem, we'll create a Java class called `Formula1RaceRunner` that calculates the average speed of a group of Formula 1 cars during a race, considering their total distance covered and the time taken for each car.
+
+**Step 1**: Create a method named `calculateAverageSpeed` in the `Formula1RaceRunner` class:
+
+```
+static double calculateAverageSpeed(int numberOfCars, long totalDistance, float totalTime) {
+ // .....
+}
+```
+
+This method takes three parameters: `numberOfCars` (an integer), `totalDistance` (a long), and `totalTime` (a float).
+
+**Step 2**: Calculate the average distance and average time:
+
+```
+double averageDistance = (double) totalDistance / numberOfCars;
+double averageTime = totalTime / numberOfCars;
+```
+
+We divide the total distance by the number of cars to get the average distance. Similarly, we divide the total time by the number of cars to get the average time.
+
+**Step 3**: Calculate and return the average speed:
+
+```
+return averageDistance / averageTime;
+```
+
+To calculate the average speed, we divide the average distance by the average time.
+
+**Step 4**: Create the `main` method in the `Formula1RaceRunner` class:
+
+```
+public static void main(String[] args) {
+ // ...
+}
+```
+
+**Step 5**: Define the variables for the number of cars, total distance, and total time, and assign appropriate values to them:
+
+```
+int numberOfCars = 5;
+long totalDistance = 12000; // in meters
+float totalTime = 720.5f; // in seconds
+```
+
+**Step 6**: Call the `calculateAverageSpeed` method with the defined variables as arguments and store the result in a `double` variable named `averageSpeed`:
+
+```
+double averageSpeed = calculateAverageSpeed(numberOfCars, totalDistance, totalTime);
+```
+
+**Step 7**: Print the `averageSpeed` to the console, formatted to one decimal place using `System.out.printf()`:
+
+```
+System.out.printf("Average speed for the Formula 1 cars: %.1f m/s\n", averageSpeed);
+```
+
+The complete `Formula1RaceRunner` class should look like this:
+
+```
+public class Formula1RaceRunner {
+
+ static double calculateAverageSpeed(int numberOfCars, long totalDistance, float totalTime) {
+ double averageDistance = (double) totalDistance / numberOfCars;
+ double averageTime = totalTime / numberOfCars;
+
+ return averageDistance / averageTime;
+ }
+
+ public static void main(String[] args) {
+ int numberOfCars = 5;
+ long totalDistance = 12000; // in meters
+ float totalTime = 720.5f; // in seconds
+
+ double averageSpeed = calculateAverageSpeed(numberOfCars, totalDistance, totalTime);
+
+ System.out.printf("Average speed for the Formula 1 cars: %.1f m/s\n", averageSpeed);
+ }
+}
+```
+
+When you run this Java program, it calculates the average speed of the Formula 1 cars during the race and prints the result:
+
+```
+Average speed for the Formula 1 cars: 16.7 m/s
+```
+
+
+## Student File
+
+
+
+**Formula1RaceRunner.java**
+
+
+
+```
+public class Formula1RaceRunner {
+
+ static double calculateAverageSpeed(int numberOfCars, long totalDistance, float totalTime) {
+ // Complete the code
+ }
+
+ public static void main(String[] args) {
+ int numberOfCars = 5;
+ long totalDistance = 12000; // in meters
+ float totalTime = 720.5f; // in seconds
+
+ // Complete the code
+ double averageSpeed;
+
+ System.out.printf("Average speed for the Formula 1 cars: %.1f m/s\n", averageSpeed);
+ }
+}
+
+```
+
+
+
+
+
+## Solution File
+
+
+
+**Formula1RaceRunner.java**
+
+
+
+```
+public class Formula1RaceRunner {
+
+ static double calculateAverageSpeed(int numberOfCars, long totalDistance, float totalTime) {
+ double averageDistance = (double) totalDistance / numberOfCars;
+ double averageTime = totalTime / numberOfCars;
+
+ return averageDistance / averageTime;
+ }
+
+ public static void main(String[] args) {
+ int numberOfCars = 5;
+ long totalDistance = 12000; // in meters
+ float totalTime = 720.5f; // in seconds
+
+ double averageSpeed = calculateAverageSpeed(numberOfCars, totalDistance, totalTime);
+
+ System.out.printf("Average speed for the Formula 1 cars: %.1f m/s\n", averageSpeed);
+ }
+}
+
+```
+
+
+
+
+## Evaluation File
+
+
+**Evaluate.java**
+
+
+
+```
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import java.util.logging.Logger;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+public class Evaluate {
+
+ private Formula1RaceRunner formula1RaceRunner;
+ private static final Logger LOGGER = Logger.getLogger(Evaluate.class.getName());
+
+ @BeforeEach
+ public void setUp() {
+ formula1RaceRunner = new Formula1RaceRunner();
+ }
+
+ @Test
+ public void testCalculateAverageSpeed() {
+ LOGGER.info("Running testCalculateAverageSpeed...");
+
+ int numberOfCars = 5;
+ long totalDistance = 12000; // in meters
+ float totalTime = 720.5f; // in seconds
+
+ double expectedAverageSpeed = 16.7;
+
+ double actualAverageSpeed = Formula1RaceRunner.calculateAverageSpeed(numberOfCars, totalDistance, totalTime);
+
+ assertEquals(expectedAverageSpeed, actualAverageSpeed, 0.1, "The average speed calculation is not correct");
+ }
+}
+
+```
\ No newline at end of file
From 1bfa155bbe3d8cbb34e4ba2643a430b3d27ed47b Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sat, 8 Apr 2023 21:17:09 +0530
Subject: [PATCH 107/178] Update 03-IntroductionToJavaPlatform.md
---
.../03-IntroductionToJavaPlatform.md | 20 +++++++------------
1 file changed, 7 insertions(+), 13 deletions(-)
diff --git a/02-CodeChallenge/03-IntroductionToJavaPlatform.md b/02-CodeChallenge/03-IntroductionToJavaPlatform.md
index 1bc85d2d..6ff742f2 100644
--- a/02-CodeChallenge/03-IntroductionToJavaPlatform.md
+++ b/02-CodeChallenge/03-IntroductionToJavaPlatform.md
@@ -51,26 +51,20 @@ public class Exercise {
```
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
-import java.io.ByteArrayOutputStream;
-import java.io.PrintStream;
+import com.udemy.ucp.IOHelper;
public class Evaluate {
+ Exercise ex = new Exercise();
+ IOHelper helper = new IOHelper();
@Test
- public void testExerciseOutput() {
- // Redirect output to a ByteArrayOutputStream
- ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
- PrintStream printStream = new PrintStream(outputStream);
- System.setOut(printStream);
-
- // Call the main method of the Exercise class
+ public void testHelloWorld() {
+ helper.resetStdOut(); // clean stdout
Exercise.main(null);
-
- // Verify that the output contains the message "Hello World"
- String output = outputStream.toString();
- assertEquals("Hello World\n", output);
+ assertEquals("Hello World\n", helper.getOutput(), "The output should be 'Hello World'");
}
}
+
```
From 5288e77e0fc17898bcd5f9765d95a5060f562f1f Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Mon, 10 Apr 2023 11:31:31 +0530
Subject: [PATCH 108/178] .
---
.../04-IntroductionToEclipse-FirstJavaProject.md | 5 ++++-
1 file changed, 4 insertions(+), 1 deletion(-)
diff --git a/02-CodeChallenge/04-IntroductionToEclipse-FirstJavaProject.md b/02-CodeChallenge/04-IntroductionToEclipse-FirstJavaProject.md
index 8ecb1b21..b744d9d7 100644
--- a/02-CodeChallenge/04-IntroductionToEclipse-FirstJavaProject.md
+++ b/02-CodeChallenge/04-IntroductionToEclipse-FirstJavaProject.md
@@ -196,7 +196,7 @@ public class Evaluate {
-
+
\ No newline at end of file
From d3ab262f56520c67b5d33036f1ca6c040bf024dd Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Mon, 10 Apr 2023 11:32:25 +0530
Subject: [PATCH 109/178] .
---
02-CodeChallenge/03-IntroductionToJavaPlatform.md | 4 +++-
1 file changed, 3 insertions(+), 1 deletion(-)
diff --git a/02-CodeChallenge/03-IntroductionToJavaPlatform.md b/02-CodeChallenge/03-IntroductionToJavaPlatform.md
index 6ff742f2..2378027d 100644
--- a/02-CodeChallenge/03-IntroductionToJavaPlatform.md
+++ b/02-CodeChallenge/03-IntroductionToJavaPlatform.md
@@ -67,7 +67,7 @@ public class Evaluate {
```
-
+
\ No newline at end of file
From a781dc05a04878ccda7085696b9c284362c45bf5 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Mon, 10 Apr 2023 11:33:57 +0530
Subject: [PATCH 110/178] .
---
...4-IntroductionToEclipse-FirstJavaProject.md | 18 ++----------------
1 file changed, 2 insertions(+), 16 deletions(-)
diff --git a/02-CodeChallenge/04-IntroductionToEclipse-FirstJavaProject.md b/02-CodeChallenge/04-IntroductionToEclipse-FirstJavaProject.md
index b744d9d7..eb5fe5b1 100644
--- a/02-CodeChallenge/04-IntroductionToEclipse-FirstJavaProject.md
+++ b/02-CodeChallenge/04-IntroductionToEclipse-FirstJavaProject.md
@@ -1,3 +1,4 @@
+
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
From dca768219aa5ed621b664e2932324e8836010e37 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Mon, 10 Apr 2023 13:04:48 +0530
Subject: [PATCH 111/178] .
---
...-IntroductionToEclipse-FirstJavaProject.md | 279 +++++++++++++++++-
1 file changed, 278 insertions(+), 1 deletion(-)
diff --git a/02-CodeChallenge/04-IntroductionToEclipse-FirstJavaProject.md b/02-CodeChallenge/04-IntroductionToEclipse-FirstJavaProject.md
index eb5fe5b1..fb986beb 100644
--- a/02-CodeChallenge/04-IntroductionToEclipse-FirstJavaProject.md
+++ b/02-CodeChallenge/04-IntroductionToEclipse-FirstJavaProject.md
@@ -1,3 +1,279 @@
+
+# Exercise 2: Even Number Printer Calculator
+
+
+
+## Instructions
+
+#### Objective:
+
+Complete the missing parts of the `EvenNumberPrinter` class in the `EvenNumberPrinterRunner` code file to implement the following methods:
+
+- `printEvenNumbers(int from, int to)`: Prints all even numbers in the range from `from` to `to` (inclusive), separated by a space.
+- `printEvenNumbers(int number)`: Prints all even numbers from 1 to the given number, separated by a space.
+- `printEvenNumbers()`: Prints all even numbers from 1 to 10 separated by a space.
+
+#### Instructions:
+
+1. Implement the `printEvenNumbers(int from, int to)` method in the `EvenNumberPrinter` class:
+
+ - Use a for loop to iterate through the range of numbers from `from` to `to` (inclusive).
+ - Check if the current number is even using the modulo operator (i % 2 == 0).
+ - If the current number is even, print it using `System.out.printf(" %d", i)`.
+2. Implement the `printEvenNumbers(int number)` method in the `EvenNumberPrinter` class:
+
+ - Call the `printEvenNumbers(int from, int to)` method with `from` as 1 and `to` as the given `number`.
+3. Implement the `printEvenNumbers()` method in the `EvenNumberPrinter` class:
+
+ - Call the `printEvenNumbers(int from, int to)` method with `from` as 1 and `to` as 10.
+
+#### Sample Input and Output:
+
+Here are some sample inputs and their corresponding outputs to help you understand how the `EvenNumberPrinter` class should work:
+
+1. `evenNumberPrinter.printEvenNumbers(3, 12);`
+
+ - Output: `4 6 8 10 12`
+2. `evenNumberPrinter.printEvenNumbers(8);`
+
+ - Output: `2 4 6 8`
+3. `evenNumberPrinter.printEvenNumbers();`
+
+ - Output: `2 4 6 8 10`
+
+These examples show the expected output when calling the different `printEvenNumbers` methods with various input values. Ensure that your implementation produces the correct output for each method. Note that the output should be separated by spaces, and there is no trailing or leading space.
+
+
+## Hints
+
+1. Use a `for` loop to iterate through the given range of numbers.
+
+2. Use the modulo operator (`%`) to check if a number is even (i.e., if `number % 2 == 0`).
+
+3. Use `System.out.printf()` to print the even numbers in each method.
+
+
+
+## Solution Explanation
+
+
+To implement the `EvenNumberPrinter` class, we need to complete the three methods: `printEvenNumbers(int from, int to)`, `printEvenNumbers(int number)`, and `printEvenNumbers()`.
+
+### printEvenNumbers(int from, int to)
+
+The `printEvenNumbers(int from, int to)` method should print all even numbers within the range `[from, to]` (inclusive). We can achieve this using a for loop to iterate through the range and an if statement to check if a number is even:
+
+```
+public static void printEvenNumbers(int from, int to) {
+ for (int i = from; i <= to; i++) {
+ if (i % 2 == 0) {
+ System.out.printf(" %d", i);
+ }
+ }
+}
+```
+
+### printEvenNumbers(int number)
+
+The `printEvenNumbers(int number)` method should print all even numbers from 1 up to the given `number` (inclusive). We can use the previously defined `printEvenNumbers(int from, int to)` method to achieve this:
+
+```
+public static void printEvenNumbers(int number) {
+ printEvenNumbers(1, number);
+}
+```
+
+### printEvenNumbers()
+
+The `printEvenNumbers()` method should print all even numbers up to 10 (inclusive). We can again use the `printEvenNumbers(int from, int to)` method for this:
+
+```
+public static void printEvenNumbers() {
+ printEvenNumbers(1, 10);
+}
+```
+
+### Testing the Solution
+
+We can test the solution by calling each of the three methods with appropriate arguments in the `main` method:
+
+```
+public static void main(String[] args) {
+ EvenNumberPrinter evenNumberPrinter = new EvenNumberPrinter();
+ evenNumberPrinter.printEvenNumbers(3, 12); // Output: 4 6 8 10 12
+ evenNumberPrinter.printEvenNumbers(8); // Output: 2 4 6 8
+ evenNumberPrinter.printEvenNumbers(); // Output: 2 4 6 8 10
+}
+```
+
+This completes the implementation of the `EvenNumberPrinter` class.
+
+
+
+## Student File
+
+**EvenNumberPrinterRunner.java**
+
+```
+public class EvenNumberPrinterRunner {
+
+ public static class EvenNumberPrinter {
+
+ public static void printEvenNumbers(int from, int to) {
+ // Complete the code
+ }
+
+ public static void printEvenNumbers(int number) {
+ // Complete the code
+ }
+
+ public static void printEvenNumbers() {
+ // Complete the code
+ }
+
+ }
+
+ public static void main(String[] args) {
+ EvenNumberPrinter evenNumberPrinter = new EvenNumberPrinter();
+ evenNumberPrinter.printEvenNumbers(3, 12);
+ evenNumberPrinter.printEvenNumbers(8);
+ evenNumberPrinter.printEvenNumbers();
+
+
+ }
+}
+
+```
+
+
+
+
+## Solution File
+
+**EvenNumberPrinterRunner.java**
+
+```
+public class EvenNumberPrinterRunner {
+
+ public static class EvenNumberPrinter {
+
+ public static void printEvenNumbers(int from, int to) {
+ for (int i = from; i <= to; i++) {
+ if (i % 2 == 0) {
+ System.out.printf(" %d", i);
+ }
+ }
+ }
+
+ public static void printEvenNumbers(int number) {
+ printEvenNumbers(1, number);
+ }
+
+ public static void printEvenNumbers() {
+ printEvenNumbers(1, 10);
+ }
+ }
+
+ public static void main(String[] args) {
+ EvenNumberPrinter evenNumberPrinter = new EvenNumberPrinter();
+ evenNumberPrinter.printEvenNumbers(3, 12);
+ evenNumberPrinter.printEvenNumbers(8);
+ evenNumberPrinter.printEvenNumbers();
+ }
+}
+```
+
+
+
+## Evaluation File
+
+**Evaluate.java**
+
+```
+import com.udemy.ucp.IOHelper;
+import org.junit.jupiter.api.Test;
+import java.util.logging.Logger;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+public class Evaluate {
+
+ IOHelper helper = new IOHelper();
+ private static final Logger LOGGER = Logger.getLogger(Evaluate.class.getName());
+
+ @Test
+ public void testPrintEvenNumbers() {
+ helper.resetStdOut(); // clean stdout
+ EvenNumberPrinterRunner.EvenNumberPrinter.printEvenNumbers();
+ String expectedOutput = " 2 4 6 8 10";
+ String actualOutput = helper.getOutput();
+ LOGGER.info("Expected Output: " + expectedOutput);
+ LOGGER.info("Your output: " + actualOutput);
+ assertEquals(expectedOutput, actualOutput, "Even numbers from 1 to 10 are not printed correctly.");
+
+ }
+
+ @Test
+ public void testPrintEvenNumbersWithNumber() {
+ helper.resetStdOut(); // clean stdout
+ EvenNumberPrinterRunner.EvenNumberPrinter.printEvenNumbers(8);
+ String expectedOutput = " 2 4 6 8";
+ String actualOutput = helper.getOutput();
+ LOGGER.info("Expected Output: " + expectedOutput);
+ LOGGER.info("Your output: " + actualOutput);
+ assertEquals(expectedOutput, actualOutput, "Even numbers from 1 to 8 are not printed correctly.");
+
+ }
+
+ @Test
+ public void testPrintEvenNumbersWithRange() {
+ helper.resetStdOut(); // clean stdout
+ EvenNumberPrinterRunner.EvenNumberPrinter.printEvenNumbers(3, 12);
+ String expectedOutput = " 4 6 8 10 12";
+ String actualOutput = helper.getOutput();
+ LOGGER.info("Expected Output: " + expectedOutput);
+ LOGGER.info("Your output: " + actualOutput);
+ assertEquals(expectedOutput, actualOutput, "Even numbers from 3 to 12 are not printed correctly.");
+
+ }
+}
+
+```
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
@@ -377,3 +653,4 @@ public class Evaluate {
```
+--->
\ No newline at end of file
From e0f6f383e71d0a1983c667056d24be31b1b7fd88 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Mon, 10 Apr 2023 15:59:08 +0530
Subject: [PATCH 112/178] .
---
...-IntroductionToObjectOrientedProgrammin.md | 1 -
02-CodeChallenge/05-RENEW.md | 330 ++++++++++++++++++
2 files changed, 330 insertions(+), 1 deletion(-)
create mode 100644 02-CodeChallenge/05-RENEW.md
diff --git a/02-CodeChallenge/05-IntroductionToObjectOrientedProgrammin.md b/02-CodeChallenge/05-IntroductionToObjectOrientedProgrammin.md
index 57e32c5c..a2f9495e 100644
--- a/02-CodeChallenge/05-IntroductionToObjectOrientedProgrammin.md
+++ b/02-CodeChallenge/05-IntroductionToObjectOrientedProgrammin.md
@@ -1,4 +1,3 @@
-
## Exercise 1: Implementing Encapsulation Techniques in the VideoGame Class
diff --git a/02-CodeChallenge/05-RENEW.md b/02-CodeChallenge/05-RENEW.md
new file mode 100644
index 00000000..5fc72fa1
--- /dev/null
+++ b/02-CodeChallenge/05-RENEW.md
@@ -0,0 +1,330 @@
+
+# ## Exercise 1: Implementing Encapsulation Techniques in the VideoGame Class
+
+
+
+## Instructions
+
+
+**Instructions**
+
+**Task 1: Implement VideoGame class attributes**
+
+In the given `VideoGameRunner` class, add the following attributes to the `VideoGame` class:
+
+- `title` of type `String`
+
+- `numberOfCopies` of type `int`
+
+
+**Task 2: Implement methods for VideoGame class**
+
+Implement the following methods for the `VideoGame` class:
+
+- `setTitle(String gameTitle)`: Sets the title of the video game.
+
+- `getTitle()`: Returns the title of the video game.
+
+- `setNumberOfCopies(int numberOfCopies)`: Sets the number of copies if the provided number is greater than or equal to 0.
+
+- `getNumberOfCopies()`: Returns the number of copies.
+
+
+**Task 3: Test the VideoGame class in the main method**
+
+In the `main` method of the `VideoGameRunner` class, do the following:
+
+1. Create three instances of the `VideoGame` class and set their titles as follows:
+
+ - Create an instance named `rdr2` and set its title to "Red Dead Redemption 2".
+
+ - Create an instance named `tw3` and set its title to "The Witcher 3".
+
+ - Create an instance named `botw` and set its title to "Breath of the Wild".
+
+2. Set the number of copies for each video game instance as follows:
+
+ - Set the number of copies for `rdr2` to 5.
+
+ - Set the number of copies for `tw3` to 8.
+
+ - Set the number of copies for `botw` to 10.
+
+3. After setting the number of copies for each video game instance, print the title and number of copies for each video game instance using the following format:
+
+ ```
+ System.out.println(videoGameInstance.getTitle() + " - Number of copies: " + videoGameInstance.getNumberOfCopies());
+```
+
+
+**The output should look like:**
+
+
+```
+Red Dead Redemption 2 - Number of copies: 5
+The Witcher 3 - Number of copies: 8
+Breath of the Wild - Number of copies: 10
+```
+
+## Hints
+
+1. Task 1 requires you to add the attributes `title` and `numberOfCopies` to the `VideoGame` class. To do this, you need to declare these attributes as private instance variables in the `VideoGame` class.
+
+2. Task 2 requires you to implement four methods in the `VideoGame` class: `setTitle(String gameTitle)`, `getTitle()`, `setNumberOfCopies(int numberOfCopies)`, and `getNumberOfCopies()`. Remember to use appropriate access modifiers and parameter types for each method.
+
+3. For Task 3, start by creating three instances of the `VideoGame` class: `rdr2`, `tw3`, and `botw`. Then use the `setTitle(String gameTitle)` method to set the title of each instance, and use the `setNumberOfCopies(int numberOfCopies)` method to set the number of copies for each instance.
+
+4. After setting the number of copies for each instance, use the `getTitle()` and `getNumberOfCopies()` methods to print the title and number of copies for each instance using the format shown in the problem statement.
+
+
+I hope these hints help you complete the exercise!
+
+
+## Solution Explanation
+
+In this problem, we need to implement a VideoGame class and test it in the main method of the VideoGameRunner class.
+
+**Task 1: Implement VideoGame class attributes**
+
+In the VideoGame class, we need to add two attributes: `title` of type `String` and `numberOfCopies` of type `int`.
+
+```
+public class VideoGame {
+ private String title;
+ private int numberOfCopies;
+}
+```
+
+**Task 2: Implement methods for VideoGame class**
+
+In the VideoGame class, we need to implement four methods: `setTitle`, `getTitle`, `setNumberOfCopies`, and `getNumberOfCopies`.
+
+`setTitle(String gameTitle)`: Sets the title of the video game.
+
+```
+public void setTitle(String gameTitle) {
+ title = gameTitle;
+}
+```
+
+`getTitle()`: Returns the title of the video game.
+
+```
+public String getTitle() {
+ return title;
+}
+```
+
+`setNumberOfCopies(int numberOfCopies)`: Sets the number of copies if the provided number is greater than or equal to 0.
+
+```
+public void setNumberOfCopies(int numberOfCopies) {
+ if (numberOfCopies >= 0) {
+ this.numberOfCopies = numberOfCopies;
+ }
+}`
+```
+
+`getNumberOfCopies()`: Returns the number of copies.
+
+```
+public int getNumberOfCopies() {
+ return numberOfCopies;
+}
+```
+
+**Task 3: Test the VideoGame class in the main method**
+
+In the main method of the VideoGameRunner class, we need to create three instances of the VideoGame class and set their titles. Then, we need to set the number of copies for each video game instance and print the title and number of copies for each video game instance.
+
+```
+public static void main(String[] args) {
+ VideoGame rdr2 = new VideoGame();
+ rdr2.setTitle("Red Dead Redemption 2");
+ rdr2.setNumberOfCopies(5);
+
+ VideoGame tw3 = new VideoGame();
+ tw3.setTitle("The Witcher 3");
+ tw3.setNumberOfCopies(8);
+
+ VideoGame botw = new VideoGame();
+ botw.setTitle("Breath of the Wild");
+ botw.setNumberOfCopies(10);
+
+ System.out.println(rdr2.getTitle() + " - Number of copies: " + rdr2.getNumberOfCopies());
+ System.out.println(tw3.getTitle() + " - Number of copies: " + tw3.getNumberOfCopies());
+ System.out.println(botw.getTitle() + " - Number of copies: " + botw.getNumberOfCopies());
+}
+```
+
+The above code creates three VideoGame instances `rdr2`, `tw3`, and `botw`. Then, it sets the titles and number of copies for each instance. Finally, it prints the title and number of copies for each video game instance.
+
+The output of the above code is:
+
+```
+Red Dead Redemption 2 - Number of copies: 5
+The Witcher 3 - Number of copies: 8
+Breath of the Wild - Number of copies: 10
+```
+
+This output matches the expected output mentioned in the problem statement.
+
+
+## Student File
+
+**VideoGameRunner.java**
+
+```
+public class VideoGameRunner {
+
+ static class VideoGame {
+ // Complete the code
+ }
+
+ public static void main(String[] args) {
+
+ // VideoGame rdr2 = new VideoGame();
+ // rdr2.setTitle("Red Dead Redemption 2");
+ // rdr2.setNumberOfCopies(5);
+ // Complete the code
+
+
+
+ // System.out.println(rdr2.getTitle() + " - Number of copies: " + rdr2.getNumberOfCopies());
+ // Complete the code
+
+
+ }
+}
+```
+
+
+
+
+## Solution File
+
+**VideoGameRunner.java**
+
+```
+public class VideoGameRunner {
+
+ static class VideoGame {
+ private String title;
+ private int numberOfCopies;
+
+ public void setTitle(String gameTitle) {
+ title = gameTitle;
+ }
+
+ public String getTitle() {
+ return title;
+ }
+
+ public void setNumberOfCopies(int numberOfCopies) {
+ if (numberOfCopies >= 0) {
+ this.numberOfCopies = numberOfCopies;
+ }
+ }
+
+ public int getNumberOfCopies() {
+ return numberOfCopies;
+ }
+ }
+
+ public static void main(String[] args) {
+ VideoGame rdr2 = new VideoGame();
+ rdr2.setTitle("Red Dead Redemption 2");
+ rdr2.setNumberOfCopies(5);
+
+ VideoGame tw3 = new VideoGame();
+ tw3.setTitle("The Witcher 3");
+ tw3.setNumberOfCopies(8);
+
+ VideoGame botw = new VideoGame();
+ botw.setTitle("Breath of the Wild");
+ botw.setNumberOfCopies(10);
+
+ System.out.println(rdr2.getTitle() + " - Number of copies: " + rdr2.getNumberOfCopies());
+ System.out.println(tw3.getTitle() + " - Number of copies: " + tw3.getNumberOfCopies());
+ System.out.println(botw.getTitle() + " - Number of copies: " + botw.getNumberOfCopies());
+ }
+}
+
+```
+
+
+
+## Evaluation File
+
+**Evaluate.java**
+
+```
+import com.udemy.ucp.IOHelper;
+import org.junit.jupiter.api.Test;
+import java.util.logging.Logger;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+public class Evaluate {
+
+ IOHelper helper = new IOHelper();
+ private static final Logger LOGGER = Logger.getLogger(Evaluate.class.getName());
+
+ @Test
+ public void testSetAndGetMethods() {
+ try {
+ assertTrue(VideoGameRunner.VideoGame.class.getDeclaredMethod("setTitle", String.class) != null, "Method setTitle is not declared in VideoGame class.");
+ assertTrue(VideoGameRunner.VideoGame.class.getDeclaredMethod("getTitle") != null, "Method getTitle is not declared in VideoGame class.");
+ assertTrue(VideoGameRunner.VideoGame.class.getDeclaredMethod("setNumberOfCopies", int.class) != null, "Method setNumberOfCopies is not declared in VideoGame class.");
+ assertTrue(VideoGameRunner.VideoGame.class.getDeclaredMethod("getNumberOfCopies") != null, "Method getNumberOfCopies is not declared in VideoGame class.");
+
+ assertTrue(VideoGameRunner.VideoGame.class.getDeclaredField("title") != null, "Field title is not declared in VideoGame class.");
+ assertTrue(VideoGameRunner.VideoGame.class.getDeclaredField("numberOfCopies") != null, "Field numberOfCopies is not declared in VideoGame class.");
+ } catch (NoSuchMethodException | NoSuchFieldException e) {
+ LOGGER.severe("Error: " + e.getMessage());
+ }
+ }
+
+ @Test
+ public void testMainMethod() {
+ helper.resetStdOut(); // clean stdout
+ VideoGameRunner.main(new String[]{});
+ String actualOutput = helper.getOutput();
+ String refinedActualOutput = helper.getOutput().replace("\n", " ");
+
+ String expectedOutput = "Red Dead Redemption 2 - Number of copies: 5\n" +
+ "The Witcher 3 - Number of copies: 8\n" +
+ "Breath of the Wild - Number of copies: 10\n";
+ LOGGER.info("Expected Output: " + expectedOutput);
+ LOGGER.info("Actual Output: " + actualOutput);
+ assertEquals(expectedOutput, actualOutput, "Output does not match the expected value. Please check user logs for more detailed view. Expected: Red Dead Redemption 2 - Number of copies: 5 " +
+ "The Witcher 3 - Number of copies: 8 " +
+ "Breath of the Wild - Number of copies: 10 " + ", actual: " + refinedActualOutput);
+ }
+
+ @Test
+ public void testRdr2Output() {
+ helper.resetStdOut(); // clean stdout
+ VideoGameRunner.main(new String[]{});
+ String actualOutput = helper.getOutput();
+ assertTrue(actualOutput.contains("Red Dead Redemption 2 - Number of copies: 5"), "Output does not contain expected string: Red Dead Redemption 2 - Number of copies: 5");
+ }
+
+ @Test
+ public void testTw3Output() {
+ helper.resetStdOut(); // clean stdout
+ VideoGameRunner.main(new String[]{});
+ String actualOutput = helper.getOutput();
+ assertTrue(actualOutput.contains("The Witcher 3 - Number of copies: 8"), "Output does not contain expected string: The Witcher 3 - Number of copies: 8");
+ }
+
+ @Test
+ public void testBotwOutput() {
+ helper.resetStdOut(); // clean stdout
+ VideoGameRunner.main(new String[]{});
+ String actualOutput = helper.getOutput();
+ assertTrue(actualOutput.contains("Breath of the Wild - Number of copies: 10"), "Output does not contain expected string: Breath of the Wild - Number of copies: 10");
+ }
+}
+
+```
\ No newline at end of file
From dc9998eea66ee7295fa8491f9e1b9318e46c66a3 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Mon, 10 Apr 2023 15:59:35 +0530
Subject: [PATCH 113/178] .
---
02-CodeChallenge/05-RENEW.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/02-CodeChallenge/05-RENEW.md b/02-CodeChallenge/05-RENEW.md
index 5fc72fa1..24e31230 100644
--- a/02-CodeChallenge/05-RENEW.md
+++ b/02-CodeChallenge/05-RENEW.md
@@ -1,5 +1,5 @@
-# ## Exercise 1: Implementing Encapsulation Techniques in the VideoGame Class
+## Exercise 1: Implementing Encapsulation Techniques in the VideoGame Class
From 2441d3a7660940978d63d0be58141c4803794fbe Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Mon, 10 Apr 2023 16:04:57 +0530
Subject: [PATCH 114/178] Update 05-RENEW.md
---
02-CodeChallenge/05-RENEW.md | 19 ++++++++-----------
1 file changed, 8 insertions(+), 11 deletions(-)
diff --git a/02-CodeChallenge/05-RENEW.md b/02-CodeChallenge/05-RENEW.md
index 24e31230..8e84f41f 100644
--- a/02-CodeChallenge/05-RENEW.md
+++ b/02-CodeChallenge/05-RENEW.md
@@ -5,10 +5,7 @@
## Instructions
-
-**Instructions**
-
-**Task 1: Implement VideoGame class attributes**
+### Task 1: Implement VideoGame class attributes**
In the given `VideoGameRunner` class, add the following attributes to the `VideoGame` class:
@@ -17,7 +14,7 @@ In the given `VideoGameRunner` class, add the following attributes to the `Video
- `numberOfCopies` of type `int`
-**Task 2: Implement methods for VideoGame class**
+### Task 2: Implement methods for VideoGame class**
Implement the following methods for the `VideoGame` class:
@@ -30,7 +27,7 @@ Implement the following methods for the `VideoGame` class:
- `getNumberOfCopies()`: Returns the number of copies.
-**Task 3: Test the VideoGame class in the main method**
+### Task 3: Test the VideoGame class in the main method**
In the `main` method of the `VideoGameRunner` class, do the following:
@@ -57,7 +54,7 @@ In the `main` method of the `VideoGameRunner` class, do the following:
```
-**The output should look like:**
+### The output should look like:
```
@@ -84,7 +81,7 @@ I hope these hints help you complete the exercise!
In this problem, we need to implement a VideoGame class and test it in the main method of the VideoGameRunner class.
-**Task 1: Implement VideoGame class attributes**
+### Task 1: Implement VideoGame class attributes**
In the VideoGame class, we need to add two attributes: `title` of type `String` and `numberOfCopies` of type `int`.
@@ -95,7 +92,7 @@ public class VideoGame {
}
```
-**Task 2: Implement methods for VideoGame class**
+### Task 2: Implement methods for VideoGame class**
In the VideoGame class, we need to implement four methods: `setTitle`, `getTitle`, `setNumberOfCopies`, and `getNumberOfCopies`.
@@ -133,7 +130,7 @@ public int getNumberOfCopies() {
}
```
-**Task 3: Test the VideoGame class in the main method**
+### Task 3: Test the VideoGame class in the main method**
In the main method of the VideoGameRunner class, we need to create three instances of the VideoGame class and set their titles. Then, we need to set the number of copies for each video game instance and print the title and number of copies for each video game instance.
@@ -327,4 +324,4 @@ public class Evaluate {
}
}
-```
\ No newline at end of file
+```
From 0028f48815e0c6737b15d48f1c28b65e989f3e8a Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Mon, 10 Apr 2023 21:09:15 +0530
Subject: [PATCH 115/178] ...
---
02-CodeChallenge/05-RENEW.md | 487 ++++++++++++++++++++++++++++++++++-
1 file changed, 479 insertions(+), 8 deletions(-)
diff --git a/02-CodeChallenge/05-RENEW.md b/02-CodeChallenge/05-RENEW.md
index 8e84f41f..1db3a76c 100644
--- a/02-CodeChallenge/05-RENEW.md
+++ b/02-CodeChallenge/05-RENEW.md
@@ -1,11 +1,14 @@
-## Exercise 1: Implementing Encapsulation Techniques in the VideoGame Class
+## Exercise 1: Implementing Encapsulation Techniques in the VideoGame Class Part 1
## Instructions
-### Task 1: Implement VideoGame class attributes**
+
+**Instructions**
+
+**Task 1: Implement VideoGame class attributes**
In the given `VideoGameRunner` class, add the following attributes to the `VideoGame` class:
@@ -14,7 +17,7 @@ In the given `VideoGameRunner` class, add the following attributes to the `Video
- `numberOfCopies` of type `int`
-### Task 2: Implement methods for VideoGame class**
+**Task 2: Implement methods for VideoGame class**
Implement the following methods for the `VideoGame` class:
@@ -27,7 +30,7 @@ Implement the following methods for the `VideoGame` class:
- `getNumberOfCopies()`: Returns the number of copies.
-### Task 3: Test the VideoGame class in the main method**
+**Task 3: Test the VideoGame class in the main method**
In the `main` method of the `VideoGameRunner` class, do the following:
@@ -54,7 +57,7 @@ In the `main` method of the `VideoGameRunner` class, do the following:
```
-### The output should look like:
+**The output should look like:**
```
@@ -81,7 +84,7 @@ I hope these hints help you complete the exercise!
In this problem, we need to implement a VideoGame class and test it in the main method of the VideoGameRunner class.
-### Task 1: Implement VideoGame class attributes**
+**Task 1: Implement VideoGame class attributes**
In the VideoGame class, we need to add two attributes: `title` of type `String` and `numberOfCopies` of type `int`.
@@ -92,7 +95,7 @@ public class VideoGame {
}
```
-### Task 2: Implement methods for VideoGame class**
+**Task 2: Implement methods for VideoGame class**
In the VideoGame class, we need to implement four methods: `setTitle`, `getTitle`, `setNumberOfCopies`, and `getNumberOfCopies`.
@@ -130,7 +133,7 @@ public int getNumberOfCopies() {
}
```
-### Task 3: Test the VideoGame class in the main method**
+**Task 3: Test the VideoGame class in the main method**
In the main method of the VideoGameRunner class, we need to create three instances of the VideoGame class and set their titles. Then, we need to set the number of copies for each video game instance and print the title and number of copies for each video game instance.
@@ -325,3 +328,471 @@ public class Evaluate {
}
```
+
+
+
+
+
+
+
+# ## Exercise 2: Implementing Encapsulation Techniques in the VideoGame Class Part 2
+
+
+
+## Instructions
+
+
+You are asked to implement methods for the `VideoGame` class and perform some operations in the `main` method of the `VideoGameRunner` class.
+
+### Task 1: Implement methods for VideoGame class
+
+Implement the following methods for the `VideoGame` class:
+
+1. `increaseCopies(int howMuch)`: Increases the number of copies of the video game instance by the provided integer value, only if the value is greater than 0.
+
+2. `decreaseCopies(int howMuch)`: Decreases the number of copies of the video game instance by the provided integer value, only if the value is greater than 0 and the resulting value is not negative. If the resulting value is negative, then the `numberOfCopies` attribute is set to 0.
+
+
+### Task 2: Perform operations in the main method of VideoGameRunner class
+
+In the `main` method of the `VideoGameRunner` class, do the following:
+
+1. Increase the number of copies for each video game instance as follows:
+
+ - Increase the number of copies for `rdr2` by 12.
+ - Increase the number of copies for `tw3` by 18.
+ - Increase the number of copies for `botw` by 24.
+2. After increasing the number of copies for each video game instance, print the title and number of copies for each video game instance using the following format:
+
+ ```
+ System.out.println(videoGameInstance.getTitle() + " - Number of copies after increasing copies : " + videoGameInstance.getNumberOfCopies());
+ ```
+
+3. Decrease the number of copies for each video game instance as follows:
+
+ - Decrease the number of copies for `rdr2` by 6.
+ - Decrease the number of copies for `tw3` by 12.
+ - Decrease the number of copies for `botw` by 18.
+4. After decreasing the number of copies for each video game instance, print the title and number of copies for each video game instance using the following format:
+
+ ```
+ System.out.println(videoGameInstance.getTitle() + " - Number of copies after decreasing copies : " + videoGameInstance.getNumberOfCopies());
+ ```
+
+
+The output should look like this:
+
+```
+Red Dead Redemption 2 - Number of copies: 5
+The Witcher 3 - Number of copies: 8
+Breath of the Wild - Number of copies: 10
+Red Dead Redemption 2 - Number of copies after increasing copies : 17
+The Witcher 3 - Number of copies after increasing copies : 26
+Breath of the Wild - Number of copies after increasing copies : 34
+Red Dead Redemption 2 - Number of copies after decreasing copies : 11
+The Witcher 3 - Number of copies after decreasing copies : 14
+Breath of the Wild - Number of copies after decreasing copies : 16
+```
+
+## Hints
+
+
+1. **Hint 1**: To implement the `increaseCopies()` method, first create a public method with the signature `public void increaseCopies(int howMuch)`. Inside the method, check if `howMuch` is greater than 0, and if it is, add `howMuch` to `numberOfCopies`.
+
+2. **Hint 2**: To implement the `decreaseCopies()` method, first create a public method with the signature `public void decreaseCopies(int howMuch)`. Inside the method, check if `howMuch` is greater than 0 and if the result of `numberOfCopies - howMuch` is greater than or equal to 0. If both conditions are true, subtract `howMuch` from `numberOfCopies`. If the resulting value is negative, set `numberOfCopies` to 0.
+
+3. **Hint 3**: After implementing the `increaseCopies()` and `decreaseCopies()` methods, use them to increase and decrease the number of copies for each video game instance, as specified in the instructions.
+
+4. **Hint 4**: To print the updated number of copies after increasing and decreasing the copies, use the given format `System.out.println(videoGameInstance.getTitle() + " - Number of copies after (increasing/decreasing) copies : " + videoGameInstance.getNumberOfCopies());` after calling the respective methods.
+
+
+## Solution Explanation
+
+
+The solution to this task can be broken down into two parts: implementing the `increaseCopies` and `decreaseCopies` methods for the `VideoGame` class, and then calling these methods in the `main` method of the `VideoGameRunner` class as instructed.
+
+### Implementing the increaseCopies and decreaseCopies methods
+
+First, we need to implement the `increaseCopies` and `decreaseCopies` methods inside the `VideoGame` class:
+
+```
+public void increaseCopies(int howMuch) {
+ if (howMuch > 0) {
+ numberOfCopies += howMuch;
+ }
+}
+
+public void decreaseCopies(int howMuch) {
+ if (howMuch > 0 && numberOfCopies >= howMuch) {
+ numberOfCopies -= howMuch;
+ } else {
+ numberOfCopies = 0;
+ }
+}
+```
+
+In the `increaseCopies` method, we check if the provided integer value `howMuch` is greater than 0. If it is, we increase the `numberOfCopies` attribute by `howMuch`.
+
+In the `decreaseCopies` method, we again check if the provided integer value `howMuch` is greater than 0, and also if the `numberOfCopies` attribute is greater than or equal to `howMuch`. If both conditions are satisfied, we decrease the `numberOfCopies` attribute by `howMuch`. Otherwise, we set the `numberOfCopies` attribute to 0.
+
+### Calling the increaseCopies and decreaseCopies methods in the main method
+
+Next, we need to call the `increaseCopies` and `decreaseCopies` methods for each video game instance as instructed, and print the number of copies after each operation:
+
+```
+// Increase the number of copies
+rdr2.increaseCopies(12);
+tw3.increaseCopies(18);
+botw.increaseCopies(24);
+
+// Print number of copies after increasing copies
+System.out.println(rdr2.getTitle() + " - Number of copies after increasing copies : " + rdr2.getNumberOfCopies());
+System.out.println(tw3.getTitle() + " - Number of copies after increasing copies : " + tw3.getNumberOfCopies());
+System.out.println(botw.getTitle() + " - Number of copies after increasing copies : " + botw.getNumberOfCopies());
+
+// Decrease the number of copies
+rdr2.decreaseCopies(6);
+tw3.decreaseCopies(12);
+botw.decreaseCopies(18);
+
+// Print number of copies after decreasing copies
+System.out.println(rdr2.getTitle() + " - Number of copies after decreasing copies : " + rdr2.getNumberOfCopies());
+System.out.println(tw3.getTitle() + " - Number of copies after decreasing copies : " + tw3.getNumberOfCopies());
+System.out.println(botw.getTitle() + " - Number of copies after decreasing copies : " + botw.getNumberOfCopies());
+```
+
+We first increase the number of copies for each video game instance by calling the `increaseCopies` method with the specified values (12 for `rdr2`, 18 for `tw3`, and 24 for `botw`). Then, we print the number of copies after increasing copies using the provided format.
+
+Next, we decrease the number of copies for each video game instance by calling the `decreaseCopies` method with the specified values (6 for `rdr2`, 12 for `tw3`, and 18 for `botw`). Finally, we print the number of copies after decreasing copies using the provided format.
+
+After incorporating these changes, the main method of the `VideoGameRunner` class should look like this:
+
+```
+public static void main(String[] args) {
+ VideoGame rdr2 = new VideoGame();
+ rdr2.setTitle("Red Dead Redemption 2");
+ rdr2.setNumberOfCopies(5);
+
+ VideoGame tw3 = new VideoGame();
+ tw3.setTitle("The Witcher 3");
+ tw3.setNumberOfCopies(8);
+
+ VideoGame botw = new VideoGame();
+ botw.setTitle("Breath of the Wild");
+ botw.setNumberOfCopies(10);
+
+ System.out.println(rdr2.getTitle() + " - Number of copies: " + rdr2.getNumberOfCopies());
+ System.out.println(tw3.getTitle() + " - Number of copies: " + tw3.getNumberOfCopies());
+ System.out.println(botw.getTitle() + " - Number of copies: " + botw.getNumberOfCopies());
+
+ // Increase the number of copies
+ rdr2.increaseCopies(12);
+ tw3.increaseCopies(18);
+ botw.increaseCopies(24);
+
+ // Print number of copies after increasing copies
+ System.out.println(rdr2.getTitle() + " - Number of copies after increasing copies : " + rdr2.getNumberOfCopies());
+ System.out.println(tw3.getTitle() + " - Number of copies after increasing copies : " + tw3.getNumberOfCopies());
+ System.out.println(botw.getTitle() + " - Number of copies after increasing copies : " + botw.getNumberOfCopies());
+
+ // Decrease the number of copies
+ rdr2.decreaseCopies(6);
+ tw3.decreaseCopies(12);
+ botw.decreaseCopies(18);
+
+ // Print number of copies after decreasing copies
+ System.out.println(rdr2.getTitle() + " - Number of copies after decreasing copies : " + rdr2.getNumberOfCopies());
+ System.out.println(tw3.getTitle() + " - Number of copies after decreasing copies : " + tw3.getNumberOfCopies());
+ System.out.println(botw.getTitle() + " - Number of copies after decreasing copies : " + botw.getNumberOfCopies());
+}
+```
+
+When executed, this code will produce the expected output:
+
+```
+Red Dead Redemption 2 - Number of copies: 5
+The Witcher 3 - Number of copies: 8
+Breath of the Wild - Number of copies: 10
+Red Dead Redemption 2 - Number of copies after increasing copies : 17
+The Witcher 3 - Number of copies after increasing copies : 26
+Breath of the Wild - Number of copies after increasing copies : 34
+Red Dead Redemption 2 - Number of copies after decreasing copies : 11
+The Witcher 3 - Number of copies after decreasing copies : 14
+Breath of the Wild - Number of copies after decreasing copies : 16`
+```
+
+This solution implements the required methods for the `VideoGame` class and demonstrates their functionality within the `main` method of the `VideoGameRunner` class.
+
+
+## Student File
+
+**VideoGameRunner.java**
+
+```
+public class VideoGameRunner {
+
+ static class VideoGame {
+ private String title;
+ private int numberOfCopies;
+
+ public void setTitle(String gameTitle) {
+ title = gameTitle;
+ }
+
+ public String getTitle() {
+ return title;
+ }
+
+ public void setNumberOfCopies(int numberOfCopies) {
+ if (numberOfCopies >= 0) {
+ this.numberOfCopies = numberOfCopies;
+ }
+ }
+
+ public int getNumberOfCopies() {
+ return numberOfCopies;
+ }
+
+ // TODO: Implement the increaseCopies() and decreaseCopies() methods for the VideoGame class
+
+ }
+
+ public static void main(String[] args) {
+ VideoGame rdr2 = new VideoGame();
+ rdr2.setTitle("Red Dead Redemption 2");
+ rdr2.setNumberOfCopies(5);
+
+ VideoGame tw3 = new VideoGame();
+ tw3.setTitle("The Witcher 3");
+ tw3.setNumberOfCopies(8);
+
+ VideoGame botw = new VideoGame();
+ botw.setTitle("Breath of the Wild");
+ botw.setNumberOfCopies(10);
+
+ // Print initial number of copies for each video game
+ System.out.println(rdr2.getTitle() + " - Number of copies: " + rdr2.getNumberOfCopies());
+ System.out.println(tw3.getTitle() + " - Number of copies: " + tw3.getNumberOfCopies());
+ System.out.println(botw.getTitle() + " - Number of copies: " + botw.getNumberOfCopies());
+
+ // TODO: Increase the number of copies for each video game instance and print the updated number of copies
+
+ rdr2.increaseCopies(12);
+
+ // TODO: Print the updated number of copies for rdr2 after increasing copies
+
+ System.out.println(rdr2.getTitle() + " - Number of copies after increasing copies : " + rdr2.getNumberOfCopies());
+
+ // TODO: Decrease the number of copies for each video game instance and print the updated number of copies
+
+ rdr2.decreaseCopies(6);
+
+ // TODO: Print the updated number of copies for rdr2 after decreasing copies
+ System.out.println(rdr2.getTitle() + " - Number of copies after decreasing copies : " + rdr2.getNumberOfCopies());
+ }
+}
+
+```
+
+
+
+
+## Solution File
+
+**VideoGameRunner.java**
+
+```
+public class VideoGameRunner {
+
+ static class VideoGame {
+ private String title;
+ private int numberOfCopies;
+
+ public void setTitle(String gameTitle) {
+ title = gameTitle;
+ }
+
+ public String getTitle() {
+ return title;
+ }
+
+ public void setNumberOfCopies(int numberOfCopies) {
+ if (numberOfCopies >= 0) {
+ this.numberOfCopies = numberOfCopies;
+ }
+ }
+
+ public int getNumberOfCopies() {
+ return numberOfCopies;
+ }
+
+ public void increaseCopies(int howMuch) {
+ if (howMuch > 0) {
+ numberOfCopies += howMuch;
+ }
+ }
+
+ public void decreaseCopies(int howMuch) {
+ if (howMuch > 0 && numberOfCopies >= howMuch) {
+ numberOfCopies -= howMuch;
+ } else {
+ numberOfCopies = 0;
+ }
+ }
+
+ }
+
+ public static void main(String[] args) {
+ VideoGame rdr2 = new VideoGame();
+ rdr2.setTitle("Red Dead Redemption 2");
+ rdr2.setNumberOfCopies(5);
+
+ VideoGame tw3 = new VideoGame();
+ tw3.setTitle("The Witcher 3");
+ tw3.setNumberOfCopies(8);
+
+ VideoGame botw = new VideoGame();
+ botw.setTitle("Breath of the Wild");
+ botw.setNumberOfCopies(10);
+
+ System.out.println(rdr2.getTitle() + " - Number of copies: " + rdr2.getNumberOfCopies());
+ System.out.println(tw3.getTitle() + " - Number of copies: " + tw3.getNumberOfCopies());
+ System.out.println(botw.getTitle() + " - Number of copies: " + botw.getNumberOfCopies());
+
+
+ rdr2.increaseCopies(12);
+ tw3.increaseCopies(18);
+ botw.increaseCopies(24);
+
+ System.out.println(rdr2.getTitle() + " - Number of copies after increasing copies : " + rdr2.getNumberOfCopies());
+ System.out.println(tw3.getTitle() + " - Number of copies after increasing copies : " + tw3.getNumberOfCopies());
+ System.out.println(botw.getTitle() + " - Number of copies after increasing copies : " + botw.getNumberOfCopies());
+
+ rdr2.decreaseCopies(6);
+ tw3.decreaseCopies(12);
+ botw.decreaseCopies(18);
+
+ System.out.println(rdr2.getTitle() + " - Number of copies after decreasing copies : " + rdr2.getNumberOfCopies());
+ System.out.println(tw3.getTitle() + " - Number of copies after decreasing copies : " + tw3.getNumberOfCopies());
+ System.out.println(botw.getTitle() + " - Number of copies after decreasing copies : " + botw.getNumberOfCopies());
+ }
+}
+
+```
+
+
+
+## Evaluation File
+
+**Evaluate.java**
+
+```
+import com.udemy.ucp.IOHelper;
+import org.junit.jupiter.api.Test;
+import java.util.logging.Logger;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+public class Evaluate {
+
+ IOHelper helper = new IOHelper();
+ private static final Logger LOGGER = Logger.getLogger(Evaluate.class.getName());
+
+ @Test
+ public void testSetAndGetMethods() {
+ try {
+ assertTrue(VideoGameRunner.VideoGame.class.getDeclaredMethod("setTitle", String.class) != null, "Method setTitle is not declared in VideoGame class.");
+ assertTrue(VideoGameRunner.VideoGame.class.getDeclaredMethod("getTitle") != null, "Method getTitle is not declared in VideoGame class.");
+ assertTrue(VideoGameRunner.VideoGame.class.getDeclaredMethod("setNumberOfCopies", int.class) != null, "Method setNumberOfCopies is not declared in VideoGame class.");
+ assertTrue(VideoGameRunner.VideoGame.class.getDeclaredMethod("getNumberOfCopies") != null, "Method getNumberOfCopies is not declared in VideoGame class.");
+ assertTrue(VideoGameRunner.VideoGame.class.getDeclaredMethod("increaseCopies", int.class) != null, "Method increaseCopies is not declared in VideoGame class.");
+ assertTrue(VideoGameRunner.VideoGame.class.getDeclaredMethod("decreaseCopies", int.class) != null, "Method decreaseCopies is not declared in VideoGame class.");
+
+ assertTrue(VideoGameRunner.VideoGame.class.getDeclaredField("title") != null, "Field title is not declared in VideoGame class.");
+ assertTrue(VideoGameRunner.VideoGame.class.getDeclaredField("numberOfCopies") != null, "Field numberOfCopies is not declared in VideoGame class.");
+ } catch (NoSuchMethodException | NoSuchFieldException e) {
+ LOGGER.severe("Error: " + e.getMessage());
+ }
+ }
+
+ @Test
+ public void testMainMethod() {
+ helper.resetStdOut(); // clean stdout
+ VideoGameRunner.main(new String[] {});
+ String actualOutput = helper.getOutput().trim(); // remove leading/trailing whitespaces
+ String[] lines = actualOutput.split("\n"); // split by line
+
+ // check each line to match expected format
+ assertEquals("Red Dead Redemption 2 - Number of copies: 5", lines[0]);
+ assertEquals("The Witcher 3 - Number of copies: 8", lines[1]);
+ assertEquals("Breath of the Wild - Number of copies: 10", lines[2]);
+ assertTrue(lines[3].startsWith("Red Dead Redemption 2 - Number of copies after increasing copies : "));
+ assertTrue(lines[4].startsWith("The Witcher 3 - Number of copies after increasing copies : "));
+ assertTrue(lines[5].startsWith("Breath of the Wild - Number of copies after increasing copies : "));
+ assertTrue(lines[6].startsWith("Red Dead Redemption 2 - Number of copies after decreasing copies : "));
+ assertTrue(lines[7].startsWith("The Witcher 3 - Number of copies after decreasing copies : "));
+ assertTrue(lines[8].startsWith("Breath of the Wild - Number of copies after decreasing copies : "));
+ }
+
+
+ @Test
+ public void testRdr2Output() {
+ helper.resetStdOut(); // clean stdout
+ VideoGameRunner.main(new String[] {});
+ String actualOutput = helper.getOutput();
+ assertTrue(actualOutput.contains("Red Dead Redemption 2 - Number of copies: 5"), "Output does not contain expected string: Red Dead Redemption 2 - Number of copies: 5");
+ }
+
+ @Test
+ public void testTw3Output() {
+ helper.resetStdOut(); // clean stdout
+ VideoGameRunner.main(new String[] {});
+ String actualOutput = helper.getOutput();
+ assertTrue(actualOutput.contains("The Witcher 3 - Number of copies: 8"), "Output does not contain expected string: The Witcher 3 - Number of copies: 8");
+ }
+
+ @Test
+ public void testBotwOutput() {
+ helper.resetStdOut(); // clean stdout
+ VideoGameRunner.main(new String[] {});
+ String actualOutput = helper.getOutput();
+ assertTrue(actualOutput.contains("Breath of the Wild - Number of copies: 10"), "Output does not contain expected string: Breath of the Wild - Number of copies: 10");
+ }
+
+ @Test
+ public void testIncreaseCopies() {
+ VideoGameRunner.VideoGame game = new VideoGameRunner.VideoGame();
+ game.setNumberOfCopies(10);
+ game.increaseCopies(5);
+ assertEquals(15, game.getNumberOfCopies(), "Number of copies did not increase by the expected amount.");
+ }
+
+ @Test
+ public void testDecreaseCopies() {
+ VideoGameRunner.VideoGame game = new VideoGameRunner.VideoGame();
+ game.setNumberOfCopies(10);
+ game.decreaseCopies(5);
+ assertEquals(5, game.getNumberOfCopies(), "Number of copies did not decrease by the expected amount.");
+ }
+
+ @Test
+ public void testIncreaseCopiesOutput() {
+ helper.resetStdOut(); // clean stdout
+ VideoGameRunner.main(new String[] {});
+ String actualOutput = helper.getOutput();
+ assertTrue(actualOutput.contains("Red Dead Redemption 2 - Number of copies after increasing copies : 17"), "Output does not contain expected string: Red Dead Redemption 2 - Number of copies after increasing copies : 17");
+ assertTrue(actualOutput.contains("The Witcher 3 - Number of copies after increasing copies : 26"), "Output does not contain expected string: The Witcher 3 - Number of copies after increasing copies : 26");
+ assertTrue(actualOutput.contains("Breath of the Wild - Number of copies after increasing copies : 34"), "Output does not contain expected string: Breath of the Wild - Number of copies after increasing copies : 34");
+ }
+
+ @Test
+ public void testDecreaseCopiesOutput() {
+ helper.resetStdOut(); // clean stdout
+ VideoGameRunner.main(new String[] {});
+ String actualOutput = helper.getOutput();
+ assertTrue(actualOutput.contains("Red Dead Redemption 2 - Number of copies after decreasing copies : 11"), "Output does not contain expected string: Red Dead Redemption 2 - Number of copies after decreasing copies : 11");
+ assertTrue(actualOutput.contains("The Witcher 3 - Number of copies after decreasing copies : 14"), "Output does not contain expected string: The Witcher 3 - Number of copies after decreasing copies : 14");
+ assertTrue(actualOutput.contains("Breath of the Wild - Number of copies after decreasing copies : 16"), "Output does not contain expected string: Breath of the Wild - Number of copies after decreasing copies : 16");
+ }
+}
+```
\ No newline at end of file
From 825d9e4657b07122c9e70472a31c5bdff46528ee Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Mon, 10 Apr 2023 21:10:07 +0530
Subject: [PATCH 116/178] .
---
02-CodeChallenge/05-RENEW.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/02-CodeChallenge/05-RENEW.md b/02-CodeChallenge/05-RENEW.md
index 1db3a76c..34be62cb 100644
--- a/02-CodeChallenge/05-RENEW.md
+++ b/02-CodeChallenge/05-RENEW.md
@@ -335,7 +335,7 @@ public class Evaluate {
-# ## Exercise 2: Implementing Encapsulation Techniques in the VideoGame Class Part 2
+## Exercise 2: Implementing Encapsulation Techniques in the VideoGame Class Part 2
From bc5fb0deb8c504c7a37066f55b7ec3e18c7a248d Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Mon, 10 Apr 2023 21:13:45 +0530
Subject: [PATCH 117/178] .
---
02-CodeChallenge/05-RENEW.md | 33 ++++++++++++++++++++++-----------
1 file changed, 22 insertions(+), 11 deletions(-)
diff --git a/02-CodeChallenge/05-RENEW.md b/02-CodeChallenge/05-RENEW.md
index 34be62cb..a7b95bce 100644
--- a/02-CodeChallenge/05-RENEW.md
+++ b/02-CodeChallenge/05-RENEW.md
@@ -178,24 +178,35 @@ This output matches the expected output mentioned in the problem statement.
public class VideoGameRunner {
static class VideoGame {
- // Complete the code
+ // Add two private attributes: title (type: String) and numberOfCopies (type: int)
+
+ // Implement setTitle method: public void setTitle(String gameTitle)
+
+ // Implement getTitle method: public String getTitle()
+
+ // Implement setNumberOfCopies method: public void setNumberOfCopies(int numberOfCopies) with a condition to check if numberOfCopies is greater than or equal to 0
+
+ // Implement getNumberOfCopies method: public int getNumberOfCopies()
}
public static void main(String[] args) {
-
- // VideoGame rdr2 = new VideoGame();
- // rdr2.setTitle("Red Dead Redemption 2");
- // rdr2.setNumberOfCopies(5);
- // Complete the code
+ // Create a VideoGame instance called rdr2 and set its title to "Red Dead Redemption 2"
+ // Set the number of copies for rdr2 to 5
+ // VideoGame rdr2 = new VideoGame();
+ // rdr2.setTitle("Red Dead Redemption 2");
+ // rdr2.setNumberOfCopies(5);
-
+ // Create a VideoGame instance called tw3 and set its title to "The Witcher 3"
+ // Set the number of copies for tw3 to 8
- // System.out.println(rdr2.getTitle() + " - Number of copies: " + rdr2.getNumberOfCopies());
- // Complete the code
-
-
+ // Create a VideoGame instance called botw and set its title to "Breath of the Wild"
+ // Set the number of copies for botw to 10
+
+ // Print the title and number of copies for each instance in the format: "Title - Number of copies: X"
+ // System.out.println(rdr2.getTitle() + " - Number of copies: " + rdr2.getNumberOfCopies());
}
}
+
```
From b6f2245a7ed884f655955e1172f2bfaf8401851a Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sat, 15 Apr 2023 11:03:55 +0530
Subject: [PATCH 118/178] .
---
02-CodeChallenge/05-RENEW.md | 162 +++++++++++++++++++++++++++--------
1 file changed, 124 insertions(+), 38 deletions(-)
diff --git a/02-CodeChallenge/05-RENEW.md b/02-CodeChallenge/05-RENEW.md
index a7b95bce..d9e39c31 100644
--- a/02-CodeChallenge/05-RENEW.md
+++ b/02-CodeChallenge/05-RENEW.md
@@ -271,71 +271,157 @@ public class VideoGameRunner {
```
import com.udemy.ucp.IOHelper;
+
+import com.udemy.ucp.EvaluationHelper;
+
import org.junit.jupiter.api.Test;
+
import java.util.logging.Logger;
+
import static org.junit.jupiter.api.Assertions.assertEquals;
+
import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+
+
+
public class Evaluate {
+
+
IOHelper helper = new IOHelper();
+
+ EvaluationHelper evaluationHelper = new EvaluationHelper();
+
+ VideoGameRunner.VideoGame videoGame = new VideoGameRunner.VideoGame();
+
+
+
private static final Logger LOGGER = Logger.getLogger(Evaluate.class.getName());
- @Test
- public void testSetAndGetMethods() {
- try {
- assertTrue(VideoGameRunner.VideoGame.class.getDeclaredMethod("setTitle", String.class) != null, "Method setTitle is not declared in VideoGame class.");
- assertTrue(VideoGameRunner.VideoGame.class.getDeclaredMethod("getTitle") != null, "Method getTitle is not declared in VideoGame class.");
- assertTrue(VideoGameRunner.VideoGame.class.getDeclaredMethod("setNumberOfCopies", int.class) != null, "Method setNumberOfCopies is not declared in VideoGame class.");
- assertTrue(VideoGameRunner.VideoGame.class.getDeclaredMethod("getNumberOfCopies") != null, "Method getNumberOfCopies is not declared in VideoGame class.");
- assertTrue(VideoGameRunner.VideoGame.class.getDeclaredField("title") != null, "Field title is not declared in VideoGame class.");
- assertTrue(VideoGameRunner.VideoGame.class.getDeclaredField("numberOfCopies") != null, "Field numberOfCopies is not declared in VideoGame class.");
- } catch (NoSuchMethodException | NoSuchFieldException e) {
- LOGGER.severe("Error: " + e.getMessage());
- }
- }
@Test
+
public void testMainMethod() {
+
helper.resetStdOut(); // clean stdout
- VideoGameRunner.main(new String[]{});
+
+ VideoGameRunner.main(new String[] {});
+
String actualOutput = helper.getOutput();
+
String refinedActualOutput = helper.getOutput().replace("\n", " ");
+
+
String expectedOutput = "Red Dead Redemption 2 - Number of copies: 5\n" +
- "The Witcher 3 - Number of copies: 8\n" +
- "Breath of the Wild - Number of copies: 10\n";
+
+ "The Witcher 3 - Number of copies: 8\n" +
+
+ "Breath of the Wild - Number of copies: 10\n";
+
LOGGER.info("Expected Output: " + expectedOutput);
+
LOGGER.info("Actual Output: " + actualOutput);
+
assertEquals(expectedOutput, actualOutput, "Output does not match the expected value. Please check user logs for more detailed view. Expected: Red Dead Redemption 2 - Number of copies: 5 " +
- "The Witcher 3 - Number of copies: 8 " +
- "Breath of the Wild - Number of copies: 10 " + ", actual: " + refinedActualOutput);
+
+ "The Witcher 3 - Number of copies: 8 " +
+
+ "Breath of the Wild - Number of copies: 10 " + ", actual: " + refinedActualOutput);
+
}
-
+
@Test
+
public void testRdr2Output() {
- helper.resetStdOut(); // clean stdout
- VideoGameRunner.main(new String[]{});
- String actualOutput = helper.getOutput();
- assertTrue(actualOutput.contains("Red Dead Redemption 2 - Number of copies: 5"), "Output does not contain expected string: Red Dead Redemption 2 - Number of copies: 5");
+
+ helper.resetStdOut(); // clean stdout
+
+ VideoGameRunner.main(new String[] {});
+
+ String actualOutput = helper.getOutput();
+
+ assertTrue(actualOutput.contains("Red Dead Redemption 2 - Number of copies: 5"), "Output does not contain expected string: Red Dead Redemption 2 - Number of copies: 5");
+
+ }
+
+
+
+ @Test
+
+ public void testTw3Output() {
+
+ helper.resetStdOut(); // clean stdout
+
+ VideoGameRunner.main(new String[] {});
+
+ String actualOutput = helper.getOutput();
+
+ assertTrue(actualOutput.contains("The Witcher 3 - Number of copies: 8"), "Output does not contain expected string: The Witcher 3 - Number of copies: 8");
+
+ }
+
+
+
+ @Test
+
+ public void testBotwOutput() {
+
+ helper.resetStdOut(); // clean stdout
+
+ VideoGameRunner.main(new String[] {});
+
+ String actualOutput = helper.getOutput();
+
+ assertTrue(actualOutput.contains("Breath of the Wild - Number of copies: 10"), "Output does not contain expected string: Breath of the Wild - Number of copies: 10");
+
+ }
+
+ @Test
+
+ public void testFieldsAndMethods() {
+
+ if (!evaluationHelper.isFieldDeclared(videoGame, "title", String.class)) {
+
+ fail("'title' field is not declared.");
+
+ }
+
+ if (!evaluationHelper.isFieldDeclared(videoGame, "numberOfCopies", int.class)) {
+
+ fail("'numberOfCopies' field is not declared.");
+
+ }
+
+ if (!evaluationHelper.isMethodDeclared(videoGame, "setTitle", String.class)) {
+
+ fail("'setTitle' method is not declared.");
+
+ }
+
+ if (!evaluationHelper.isMethodDeclared(videoGame, "getTitle")) {
+
+ fail("'getTitle' method is not declared.");
+
+ }
+
+ if (!evaluationHelper.isMethodDeclared(videoGame, "setNumberOfCopies", int.class)) {
+
+ fail("'setNumberOfCopies' method is not declared.");
+
+ }
+
+ if (!evaluationHelper.isMethodDeclared(videoGame, "getNumberOfCopies")) {
+
+ fail("'getNumberOfCopies' method is not declared.");
+
+ }
+
}
- @Test
- public void testTw3Output() {
- helper.resetStdOut(); // clean stdout
- VideoGameRunner.main(new String[]{});
- String actualOutput = helper.getOutput();
- assertTrue(actualOutput.contains("The Witcher 3 - Number of copies: 8"), "Output does not contain expected string: The Witcher 3 - Number of copies: 8");
- }
-
- @Test
- public void testBotwOutput() {
- helper.resetStdOut(); // clean stdout
- VideoGameRunner.main(new String[]{});
- String actualOutput = helper.getOutput();
- assertTrue(actualOutput.contains("Breath of the Wild - Number of copies: 10"), "Output does not contain expected string: Breath of the Wild - Number of copies: 10");
- }
}
```
From 141a2540a0fd4dcd869ce51b4a656df5525df5a9 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sat, 15 Apr 2023 11:47:34 +0530
Subject: [PATCH 119/178] .
---
02-CodeChallenge/05-RENEW.md | 33 +++++++++++++++++++++++++++++++++
1 file changed, 33 insertions(+)
diff --git a/02-CodeChallenge/05-RENEW.md b/02-CodeChallenge/05-RENEW.md
index d9e39c31..e70d4274 100644
--- a/02-CodeChallenge/05-RENEW.md
+++ b/02-CodeChallenge/05-RENEW.md
@@ -789,11 +789,44 @@ import org.junit.jupiter.api.Test;
import java.util.logging.Logger;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
+import org.junit.jupiter.api.Assertions;
+import com.udemy.ucp.EvaluationHelper;
+import static org.junit.jupiter.api.Assertions.fail;
public class Evaluate {
IOHelper helper = new IOHelper();
private static final Logger LOGGER = Logger.getLogger(Evaluate.class.getName());
+ EvaluationHelper evaluationHelper = new EvaluationHelper();
+ VideoGameRunner.VideoGame videoGame = new VideoGameRunner.VideoGame();
+
+
+ @Test
+ public void testFieldsAndMethods() {
+ if (!evaluationHelper.isFieldDeclared(videoGame, "title", String.class)) {
+ fail("'title' field is not declared.");
+ }
+
+ if (!evaluationHelper.isFieldDeclared(videoGame, "numberOfCopies", int.class)) {
+ fail("'numberOfCopies' field is not declared.");
+ }
+
+ if (!evaluationHelper.isMethodDeclared(videoGame, "setTitle", String.class)) {
+ fail("'setTitle' method is not declared.");
+ }
+
+ if (!evaluationHelper.isMethodDeclared(videoGame, "getTitle")) {
+ fail("'getTitle' method is not declared.");
+ }
+
+ if (!evaluationHelper.isMethodDeclared(videoGame, "setNumberOfCopies", int.class)) {
+ fail("'setNumberOfCopies' method is not declared.");
+ }
+
+ if (!evaluationHelper.isMethodDeclared(videoGame, "getNumberOfCopies")) {
+ fail("'getNumberOfCopies' method is not declared.");
+ }
+ }
@Test
public void testSetAndGetMethods() {
From 54920d0c06f7a472da45b99b7940f9def3e9c993 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sat, 15 Apr 2023 23:41:00 +0530
Subject: [PATCH 120/178] .
---
.../Q06-PrimitiveDataTypesAndAlternatives.md | 241 ++++++++++++++++++
1 file changed, 241 insertions(+)
create mode 100644 01-Quiz/Q06-PrimitiveDataTypesAndAlternatives.md
diff --git a/01-Quiz/Q06-PrimitiveDataTypesAndAlternatives.md b/01-Quiz/Q06-PrimitiveDataTypesAndAlternatives.md
new file mode 100644
index 00000000..b533c723
--- /dev/null
+++ b/01-Quiz/Q06-PrimitiveDataTypesAndAlternatives.md
@@ -0,0 +1,241 @@
+
+### Step 01: The Integer Types
+
+**Question 1:** Which of the following wrapper classes corresponds to the `int` primitive type in Java?
+
+1. Byte
+2. Integer
+3. Short
+
+**Answer:** `2. Integer`
+
+**Question 2:** What is the maximum value of a `short` data type in Java?
+
+1. 127
+2. 32767
+3. 2147483647
+
+**Answer:** `2. 32767`
+
+**Question 3:** What type of cast is used to store a smaller data value in a larger data type variable?
+
+1. Implicit cast
+2. Explicit cast
+
+**Answer:** `1. Implicit cast`
+
+### Step 02: Integer Representations, And Other Puzzles
+
+**Question 1**
+
+What are the three number systems supported by Java for integers?
+
+1. Decimal, Octal, and Binary
+2. Decimal, Octal, and Hexadecimal
+3. Decimal, Binary, and Hexadecimal
+
+**Answer:** 2. Decimal, Octal, and Hexadecimal
+
+**Question 2**
+
+Which of the following is the correct representation for the value 16 in a hexadecimal system?
+
+1. 0x10
+2. 010
+3. 0x16
+
+**Answer:** 1. 0x10
+
+**Question 3**
+
+What is the difference between prefix and post-fix increment operators in Java?
+
+1. Prefix increment takes place before the assignment, and post-fix increment takes place after the assignment.
+2. Prefix increment takes place after the assignment, and post-fix increment takes place before the assignment.
+3. There is no difference between prefix and post-fix increment operators in Java.
+
+**Answer:** 1. Prefix increment takes place before the assignment, and post-fix increment takes place after the assignment.
+
+### Step 03: Classroom Exercise CE-01 (With Solutions)
+
+
+**Question 1: What is the purpose of the `BiNumber` class?**
+
+- A) To store a single integer and perform basic arithmetic operations
+- B) **To store a pair of integers and perform basic arithmetic operations**
+- C) To store a list of integers and perform basic arithmetic operations
+
+**Question 2: Which method is used to double the values of both numbers in a `BiNumber` object?**
+
+- A) `double()`
+- B) `doubleNumbers()`
+- C) **`doubleValue()`**
+
+**Question 3: What will be the output of the following code snippet?**
+
+```
+BiNumber numbers = new BiNumber(4, 5);
+System.out.println(numbers.add());
+numbers.doubleValue();
+System.out.println(numbers.getNumber1());
+System.out.println(numbers.getNumber2());
+```
+
+- A) 9, 8, 10
+- B) **9, 8, 5**
+- C) 9, 4, 5
+
+
+### Step 05: Floating-Point Types
+
+#### Question 1
+
+What is the default type for floating-point literals in Java?
+
+- A) float
+- **B) double**
+
+#### Question 2
+
+How can you create a float literal?
+
+- A) float f = 34.5
+- **B) float f = 34.5f;**
+- C) float f = (float)34.5
+
+#### Question 3
+
+Which type of casting is needed to convert a double value to a float value?
+
+- A) Implicit casting
+- **B) Explicit casting**
+
+
+### Step 06: Introducing BigDecimal
+
+
+
+**Question 1:** What is the main reason for using the BigDecimal data type in Java?
+
+1. To represent floating-point numbers with higher precision
+2. To perform faster calculations
+3. To store large integer values
+
+_Answer: 1. To represent floating-point numbers with higher precision_
+
+**Question 2:** What is the best way to construct a BigDecimal object to achieve high precision?
+
+1. Using integer literals
+2. Using double literals
+3. Using string literals
+
+_Answer: 3. Using string literals_
+
+**Question 3:** What is the main characteristic of BigDecimal objects?
+
+1. Mutable
+2. Immutable
+3. Synchronized
+
+_Answer: 2. Immutable_
+
+
+### Step 06: BigDecimal Operations
+
+1. Which of the following methods can be used for arithmetic operations on BigDecimal objects?
+
+ - a. `add()`
+ - b. `multiply()`
+ - c. `subtract()`
+ - d. All of the above
+
+
+**Answer: d. All of the above**
+
+2. Can you perform arithmetic operations directly between a BigDecimal object and a primitive data type, like an int or a double?
+
+ - a. Yes
+ - b. No
+
+
+**Answer: b. No**
+
+3. How can you perform an arithmetic operation between a BigDecimal object and a primitive int value?
+
+ - a. Convert the int to a BigDecimal using `BigDecimal.valueOf()`
+ - b. Use a type cast to convert the int to a BigDecimal
+ - c. Perform the operation directly as the BigDecimal class automatically handles primitive types
+
+
+**Answer: a. Convert the int to a BigDecimal using `BigDecimal.valueOf()`**
+
+
+### Step 08: boolean, Relational and Logical Operators
+
+1. Which of the following operators is a logical operator in Java?
+
+ - a) `>`
+ - b) `&&`
+ - c) `<=`
+
+ **Answer: b) `&&`**
+
+2. Given the following code snippet, what will be the value of `result`?
+
+```
+ int a = 10;
+ int b = 5;
+ boolean result = (a > b) && (a < 2 * b);
+```
+
+ - a) `true`
+ - b) `false`
+
+ **Answer: a) `true`**
+
+3. What will the following expression evaluate to?
+
+ ```
+ boolean x = true;
+ boolean y = false;
+ boolean z = !(x || y);
+ ```
+
+ - a) `true`
+ - b) `false`
+
+ **Answer: b) `false`**
+
+
+ ### Step 10: Character Types
+
+
+### Question 1
+
+What is the Unicode representation of the double quotation mark?
+
+1. `\u0021`
+2. `\u0022`
+3. `\u0023`
+
+**Answer:** 2. `\u0022`
+
+### Question 2
+
+What data type in Java is used to store Unicode characters?
+
+1. String
+2. char
+3. int
+
+**Answer:** 2. char
+
+### Question 3
+
+What happens when you perform the following operation in Java: `char cn = 65;`?
+
+1. A character with a Unicode value of 65 is stored in the variable `cn`.
+2. An integer value of 65 is stored in the variable `cn`.
+3. A compilation error occurs.
+
+**Answer:** 1. A character with a Unicode value of 65 is stored in the variable `cn`.
\ No newline at end of file
From 374b3b396781c5cfd2d171bae74c94242a9a74dc Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sat, 15 Apr 2023 23:43:09 +0530
Subject: [PATCH 121/178] .
---
...-IntroductionToObjectOrientedProgrammin.md | 1048 ++++++++------
02-CodeChallenge/05-RENEW.md | 928 -------------
...-IntroductionToObjectOrientedProgrammin.md | 720 ++++++++++
txt_help.md | 1199 -----------------
4 files changed, 1340 insertions(+), 2555 deletions(-)
delete mode 100644 02-CodeChallenge/05-RENEW.md
create mode 100644 Archive/05-IntroductionToObjectOrientedProgrammin.md
diff --git a/02-CodeChallenge/05-IntroductionToObjectOrientedProgrammin.md b/02-CodeChallenge/05-IntroductionToObjectOrientedProgrammin.md
index a2f9495e..f84c05b8 100644
--- a/02-CodeChallenge/05-IntroductionToObjectOrientedProgrammin.md
+++ b/02-CodeChallenge/05-IntroductionToObjectOrientedProgrammin.md
@@ -1,180 +1,209 @@
-## Exercise 1: Implementing Encapsulation Techniques in the VideoGame Class
-
+## Exercise 1: Implementing Encapsulation Techniques in the VideoGame Class Part 1
-### Instructions
+
-#### Task 1: Implement VideoGame class attributes
+## Instructions
-1. In the given `VideoGameRunner` class, add the following attributes to the `VideoGame` class:
- - `title` of type `String`
- - `numberOfCopies` of type `int`
-#### Task 2: Implement methods for VideoGame class
+**Instructions**
-1. Implement the following methods for the `VideoGame` class:
- - `setTitle(String gameTitle)`: Sets the title of the video game.
- - `getTitle()`: Returns the title of the video game.
- - `setNumberOfCopies(int numberOfCopies)`: Sets the number of copies if the provided number is greater than or equal to 0.
- - `getNumberOfCopies()`: Returns the number of copies.
- - `increaseCopies(int howMuch)`: Increases the number of copies by the given amount.
- - `decreaseCopies(int howMuch)`: Decreases the number of copies by the given amount but ensures that the number of copies does not go below 0.
-
+**Task 1: Implement VideoGame class attributes**
-#### Task 3: Test the VideoGame class in the main method
+In the given `VideoGameRunner` class, add the following attributes to the `VideoGame` class:
-1. In the `main` method of the `VideoGameRunner` class, create three instances of the `VideoGame` class and set their titles as follows:
-
- - Create an instance named `rdr2` and set its title to "Red Dead Redemption 2".
- - Create an instance named `tw3` and set its title to "The Witcher 3".
- - Create an instance named `botw` and set its title to "Breath of the Wild".
-2. Print the titles of the three video game instances (`rdr2`, `tw3`, and `botw`).
-
-3. Increase the number of copies for each video game instance as follows:
+- `title` of type `String`
- - Increase the number of copies for `rdr2` by 12.
- - Increase the number of copies for `tw3` by 18.
- - Increase the number of copies for `botw` by 24.
-4. Decrease the number of copies for each video game instance as follows:
+- `numberOfCopies` of type `int`
- - Decrease the number of copies for `rdr2` by 6.
- - Decrease the number of copies for `tw3` by 12.
- - Decrease the number of copies for `botw` by 18.
-5. Print the number of copies for each video game instance (`rdr2`, `tw3`, and `botw`).
-
-
-
-### Hints
-
-#### Task 1: Implement VideoGame class attributes
-**Hint 1:** To add attributes to a class, declare them within the class using the appropriate data type.
+**Task 2: Implement methods for VideoGame class**
-**Hint 2:** You need to add two attributes: a `String` for the `title` and an `int` for the `numberOfCopies`.
+Implement the following methods for the `VideoGame` class:
-#### Task 2: Implement methods for VideoGame class
+- `setTitle(String gameTitle)`: Sets the title of the video game.
+
+- `getTitle()`: Returns the title of the video game.
+
+- `setNumberOfCopies(int numberOfCopies)`: Sets the number of copies if the provided number is greater than or equal to 0.
+
+- `getNumberOfCopies()`: Returns the number of copies.
+
-**Hint 1:** To create a method, use the following syntax: `access_modifier return_type methodName(parameters) { /* method body */ }`.
+**Task 3: Test the VideoGame class in the main method**
-**Hint 2:** For example, the `setTitle` method should have a `void` return type and a single `String` parameter.
+In the `main` method of the `VideoGameRunner` class, do the following:
-**Hint 3:** To set the number of copies only if the provided number is greater than or equal to 0, use an `if` statement in the `setNumberOfCopies` method.
+1. Create three instances of the `VideoGame` class and set their titles as follows:
+
+ - Create an instance named `rdr2` and set its title to "Red Dead Redemption 2".
+
+ - Create an instance named `tw3` and set its title to "The Witcher 3".
+
+ - Create an instance named `botw` and set its title to "Breath of the Wild".
+
+2. Set the number of copies for each video game instance as follows:
+
+ - Set the number of copies for `rdr2` to 5.
+
+ - Set the number of copies for `tw3` to 8.
+
+ - Set the number of copies for `botw` to 10.
+
+3. After setting the number of copies for each video game instance, print the title and number of copies for each video game instance using the following format:
+
+ ```
+ System.out.println(videoGameInstance.getTitle() + " - Number of copies: " + videoGameInstance.getNumberOfCopies());
+```
+
-**Hint 4:** The `increaseCopies` and `decreaseCopies` methods should use the `setNumberOfCopies` method to update the `numberOfCopies` attribute.
+**The output should look like:**
-#### Task 3: Test the VideoGame class in the main method
+
+```
+Red Dead Redemption 2 - Number of copies: 5
+The Witcher 3 - Number of copies: 8
+Breath of the Wild - Number of copies: 10
+```
-**Hint 1:** To create an instance of a class, use the `new` keyword followed by the class name and parentheses.
+## Hints
-**Hint 2:** To call a method on an instance of a class, use the dot (.) operator followed by the method name and its arguments.
+1. Task 1 requires you to add the attributes `title` and `numberOfCopies` to the `VideoGame` class. To do this, you need to declare these attributes as private instance variables in the `VideoGame` class.
+
+2. Task 2 requires you to implement four methods in the `VideoGame` class: `setTitle(String gameTitle)`, `getTitle()`, `setNumberOfCopies(int numberOfCopies)`, and `getNumberOfCopies()`. Remember to use appropriate access modifiers and parameter types for each method.
+
+3. For Task 3, start by creating three instances of the `VideoGame` class: `rdr2`, `tw3`, and `botw`. Then use the `setTitle(String gameTitle)` method to set the title of each instance, and use the `setNumberOfCopies(int numberOfCopies)` method to set the number of copies for each instance.
+
+4. After setting the number of copies for each instance, use the `getTitle()` and `getNumberOfCopies()` methods to print the title and number of copies for each instance using the format shown in the problem statement.
+
-**Hint 3:** Use `System.out.println()` to print the titles and number of copies for each video game instance.
+I hope these hints help you complete the exercise!
-### Solution Explanation
-
+## Solution Explanation
-The given problem code is incomplete and needs to be modified to include the necessary attributes and methods in the `VideoGame` class. Below is the step-by-step explanation of the solution code.
+In this problem, we need to implement a VideoGame class and test it in the main method of the VideoGameRunner class.
-#### Task 1: Implement VideoGame class attributes
+**Task 1: Implement VideoGame class attributes**
-We start by adding the required attributes `title` and `numberOfCopies` to the `VideoGame` class.
+In the VideoGame class, we need to add two attributes: `title` of type `String` and `numberOfCopies` of type `int`.
```
-private String title;
-private int numberOfCopies;
+public class VideoGame {
+ private String title;
+ private int numberOfCopies;
+}
```
-#### Task 2: Implement methods for VideoGame class
+**Task 2: Implement methods for VideoGame class**
-Next, we implement the required methods for the `VideoGame` class.
+In the VideoGame class, we need to implement four methods: `setTitle`, `getTitle`, `setNumberOfCopies`, and `getNumberOfCopies`.
-1. Set and get methods for `title` attribute:
+`setTitle(String gameTitle)`: Sets the title of the video game.
```
public void setTitle(String gameTitle) {
title = gameTitle;
}
+```
+
+`getTitle()`: Returns the title of the video game.
+```
public String getTitle() {
return title;
}
```
-2. Set and get methods for `numberOfCopies` attribute with a condition to ensure the number of copies is non-negative:
+`setNumberOfCopies(int numberOfCopies)`: Sets the number of copies if the provided number is greater than or equal to 0.
```
public void setNumberOfCopies(int numberOfCopies) {
if (numberOfCopies >= 0) {
this.numberOfCopies = numberOfCopies;
}
-}
-
-public int getNumberOfCopies() {
- return numberOfCopies;
-}
+}`
```
-3. Methods to increase and decrease the number of copies:
+`getNumberOfCopies()`: Returns the number of copies.
```
-public void increaseCopies(int howMuch) {
- setNumberOfCopies(numberOfCopies + howMuch);
-}
-
-public void decreaseCopies(int howMuch) {
- setNumberOfCopies(numberOfCopies - howMuch);
+public int getNumberOfCopies() {
+ return numberOfCopies;
}
```
-#### Task 3: Test the VideoGame class in the main method
+**Task 3: Test the VideoGame class in the main method**
-Finally, we test the `VideoGame` class in the `main` method by creating instances, setting titles, increasing and decreasing the number of copies, and printing their titles and number of copies.
+In the main method of the VideoGameRunner class, we need to create three instances of the VideoGame class and set their titles. Then, we need to set the number of copies for each video game instance and print the title and number of copies for each video game instance.
```
public static void main(String[] args) {
VideoGame rdr2 = new VideoGame();
rdr2.setTitle("Red Dead Redemption 2");
+ rdr2.setNumberOfCopies(5);
+
VideoGame tw3 = new VideoGame();
tw3.setTitle("The Witcher 3");
+ tw3.setNumberOfCopies(8);
+
VideoGame botw = new VideoGame();
botw.setTitle("Breath of the Wild");
+ botw.setNumberOfCopies(10);
+
+ System.out.println(rdr2.getTitle() + " - Number of copies: " + rdr2.getNumberOfCopies());
+ System.out.println(tw3.getTitle() + " - Number of copies: " + tw3.getNumberOfCopies());
+ System.out.println(botw.getTitle() + " - Number of copies: " + botw.getNumberOfCopies());
+}
+```
- System.out.println(rdr2.getTitle());
- System.out.println(tw3.getTitle());
- System.out.println(botw.getTitle());
+The above code creates three VideoGame instances `rdr2`, `tw3`, and `botw`. Then, it sets the titles and number of copies for each instance. Finally, it prints the title and number of copies for each video game instance.
- rdr2.increaseCopies(12);
- tw3.increaseCopies(18);
- botw.increaseCopies(24);
- rdr2.decreaseCopies(6);
- tw3.decreaseCopies(12);
- botw.decreaseCopies(18);
+The output of the above code is:
- System.out.println(rdr2.getNumberOfCopies());
- System.out.println(tw3.getNumberOfCopies());
- System.out.println(botw.getNumberOfCopies());
-}
+```
+Red Dead Redemption 2 - Number of copies: 5
+The Witcher 3 - Number of copies: 8
+Breath of the Wild - Number of copies: 10
```
-This solution code demonstrates the proper implementation of encapsulation techniques and completes the `VideoGame` class as required by the problem statement.
+This output matches the expected output mentioned in the problem statement.
+
-### Student File
+## Student File
**VideoGameRunner.java**
```
-
public class VideoGameRunner {
static class VideoGame {
- // Complete the code
+ // Add two private attributes: title (type: String) and numberOfCopies (type: int)
+
+ // Implement setTitle method: public void setTitle(String gameTitle)
+
+ // Implement getTitle method: public String getTitle()
+
+ // Implement setNumberOfCopies method: public void setNumberOfCopies(int numberOfCopies) with a condition to check if numberOfCopies is greater than or equal to 0
+
+ // Implement getNumberOfCopies method: public int getNumberOfCopies()
}
public static void main(String[] args) {
+ // Create a VideoGame instance called rdr2 and set its title to "Red Dead Redemption 2"
+ // Set the number of copies for rdr2 to 5
// VideoGame rdr2 = new VideoGame();
- // rdr2.setTitle("Red Dead Redemption 2");
- // Complete the code
+ // rdr2.setTitle("Red Dead Redemption 2");
+ // rdr2.setNumberOfCopies(5);
+
+ // Create a VideoGame instance called tw3 and set its title to "The Witcher 3"
+ // Set the number of copies for tw3 to 8
+
+ // Create a VideoGame instance called botw and set its title to "Breath of the Wild"
+ // Set the number of copies for botw to 10
+
+ // Print the title and number of copies for each instance in the format: "Title - Number of copies: X"
+ // System.out.println(rdr2.getTitle() + " - Number of copies: " + rdr2.getNumberOfCopies());
}
}
@@ -183,7 +212,7 @@ public class VideoGameRunner {
-### Solution File
+## Solution File
**VideoGameRunner.java**
@@ -211,510 +240,673 @@ public class VideoGameRunner {
public int getNumberOfCopies() {
return numberOfCopies;
}
-
- public void increaseCopies(int howMuch) {
- setNumberOfCopies(numberOfCopies + howMuch);
- }
-
- public void decreaseCopies(int howMuch) {
- setNumberOfCopies(numberOfCopies - howMuch);
- }
}
public static void main(String[] args) {
VideoGame rdr2 = new VideoGame();
rdr2.setTitle("Red Dead Redemption 2");
+ rdr2.setNumberOfCopies(5);
+
VideoGame tw3 = new VideoGame();
tw3.setTitle("The Witcher 3");
+ tw3.setNumberOfCopies(8);
+
VideoGame botw = new VideoGame();
botw.setTitle("Breath of the Wild");
+ botw.setNumberOfCopies(10);
- System.out.println(rdr2.getTitle());
- System.out.println(tw3.getTitle());
- System.out.println(botw.getTitle());
-
- rdr2.increaseCopies(12);
- tw3.increaseCopies(18);
- botw.increaseCopies(24);
- rdr2.decreaseCopies(6);
- tw3.decreaseCopies(12);
- botw.decreaseCopies(18);
-
- System.out.println(rdr2.getNumberOfCopies());
- System.out.println(tw3.getNumberOfCopies());
- System.out.println(botw.getNumberOfCopies());
+ System.out.println(rdr2.getTitle() + " - Number of copies: " + rdr2.getNumberOfCopies());
+ System.out.println(tw3.getTitle() + " - Number of copies: " + tw3.getNumberOfCopies());
+ System.out.println(botw.getTitle() + " - Number of copies: " + botw.getNumberOfCopies());
}
}
```
+
-### Evaluation File
+## Evaluation File
**Evaluate.java**
```
+import com.udemy.ucp.IOHelper;
+
+import com.udemy.ucp.EvaluationHelper;
-import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.logging.Logger;
import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import static org.junit.jupiter.api.Assertions.fail;
+
+
+
public class Evaluate {
- private VideoGameRunner.VideoGame videoGame;
+
+
+ IOHelper helper = new IOHelper();
+
+ EvaluationHelper evaluationHelper = new EvaluationHelper();
+
+ VideoGameRunner.VideoGame videoGame = new VideoGameRunner.VideoGame();
+
+
+
private static final Logger LOGGER = Logger.getLogger(Evaluate.class.getName());
- @BeforeEach
- public void setUp() {
- LOGGER.info("Setting up a new VideoGame instance for the tests...");
- videoGame = new VideoGameRunner.VideoGame();
- }
+
@Test
- public void testSetTitleAndGetTitle() {
- LOGGER.info("Running testSetTitleAndGetTitle...");
- String testTitle = "Test Game";
- LOGGER.info("Setting title to: " + testTitle);
- videoGame.setTitle(testTitle);
- LOGGER.info("Getting the title and checking if it matches the expected value...");
- assertEquals(testTitle, videoGame.getTitle());
- LOGGER.info("testSetTitleAndGetTitle passed.");
+
+ public void testMainMethod() {
+
+ helper.resetStdOut(); // clean stdout
+
+ VideoGameRunner.main(new String[] {});
+
+ String actualOutput = helper.getOutput();
+
+ String refinedActualOutput = helper.getOutput().replace("\n", " ");
+
+
+
+ String expectedOutput = "Red Dead Redemption 2 - Number of copies: 5\n" +
+
+ "The Witcher 3 - Number of copies: 8\n" +
+
+ "Breath of the Wild - Number of copies: 10\n";
+
+ LOGGER.info("Expected Output: " + expectedOutput);
+
+ LOGGER.info("Actual Output: " + actualOutput);
+
+ assertEquals(expectedOutput, actualOutput, "Output does not match the expected value. Please check user logs for more detailed view. Expected: Red Dead Redemption 2 - Number of copies: 5 " +
+
+ "The Witcher 3 - Number of copies: 8 " +
+
+ "Breath of the Wild - Number of copies: 10 " + ", actual: " + refinedActualOutput);
+
}
@Test
- public void testSetNumberOfCopiesAndGetNumberOfCopies() {
- LOGGER.info("Running testSetNumberOfCopiesAndGetNumberOfCopies...");
- int testCopies = 10;
- LOGGER.info("Setting number of copies to: " + testCopies);
- videoGame.setNumberOfCopies(testCopies);
- LOGGER.info("Getting the number of copies and checking if it matches the expected value...");
- assertEquals(testCopies, videoGame.getNumberOfCopies());
- LOGGER.info("testSetNumberOfCopiesAndGetNumberOfCopies passed.");
+
+ public void testRdr2Output() {
+
+ helper.resetStdOut(); // clean stdout
+
+ VideoGameRunner.main(new String[] {});
+
+ String actualOutput = helper.getOutput();
+
+ assertTrue(actualOutput.contains("Red Dead Redemption 2 - Number of copies: 5"), "Output does not contain expected string: Red Dead Redemption 2 - Number of copies: 5");
+
}
+
+
@Test
- public void testIncreaseCopies() {
- LOGGER.info("Running testIncreaseCopies...");
- int initialCopies = 5;
- int increaseCopiesBy = 5;
- LOGGER.info("Setting initial number of copies to: " + initialCopies);
- videoGame.setNumberOfCopies(initialCopies);
- LOGGER.info("Increasing number of copies by: " + increaseCopiesBy);
- videoGame.increaseCopies(increaseCopiesBy);
- LOGGER.info("Getting the number of copies and checking if it matches the expected value...");
- assertEquals(initialCopies + increaseCopiesBy, videoGame.getNumberOfCopies());
- LOGGER.info("testIncreaseCopies passed.");
+
+ public void testTw3Output() {
+
+ helper.resetStdOut(); // clean stdout
+
+ VideoGameRunner.main(new String[] {});
+
+ String actualOutput = helper.getOutput();
+
+ assertTrue(actualOutput.contains("The Witcher 3 - Number of copies: 8"), "Output does not contain expected string: The Witcher 3 - Number of copies: 8");
+
}
+
+
@Test
- public void testDecreaseCopies() {
- LOGGER.info("Running testDecreaseCopies...");
- int initialCopies = 10;
- int decreaseCopiesBy = 5;
- LOGGER.info("Setting initial number of copies to: " + initialCopies);
- videoGame.setNumberOfCopies(initialCopies);
- LOGGER.info("Decreasing number of copies by: " + decreaseCopiesBy);
- videoGame.decreaseCopies(decreaseCopiesBy);
- LOGGER.info("Getting the number of copies and checking if it matches the expected value...");
- assertEquals(initialCopies - decreaseCopiesBy, videoGame.getNumberOfCopies());
- LOGGER.info("testDecreaseCopies passed.");
+
+ public void testBotwOutput() {
+
+ helper.resetStdOut(); // clean stdout
+
+ VideoGameRunner.main(new String[] {});
+
+ String actualOutput = helper.getOutput();
+
+ assertTrue(actualOutput.contains("Breath of the Wild - Number of copies: 10"), "Output does not contain expected string: Breath of the Wild - Number of copies: 10");
+
}
-}
-```
+ @Test
+ public void testFieldsAndMethods() {
+ if (!evaluationHelper.isFieldDeclared(videoGame, "title", String.class)) {
+ fail("'title' field is not declared.");
+ }
+ if (!evaluationHelper.isFieldDeclared(videoGame, "numberOfCopies", int.class)) {
-## Exercise 2: Implementing Vehicle Engine Control and Speed Tracking
+ fail("'numberOfCopies' field is not declared.");
-
+ }
-### Instructions
+ if (!evaluationHelper.isMethodDeclared(videoGame, "setTitle", String.class)) {
+ fail("'setTitle' method is not declared.");
-#### Objective
+ }
-In this exercise, you are asked to complete the implementation of a simple `Vehicle` class and a `VehicleRunner` class that demonstrates its usage.
+ if (!evaluationHelper.isMethodDeclared(videoGame, "getTitle")) {
-#### Instructions
+ fail("'getTitle' method is not declared.");
-1. Complete the implementation of the `Vehicle` class inside the `VehicleRunner` class. The `Vehicle` class should have the following properties:
-
- - `speed`: An integer representing the speed of the vehicle.
- - `type`: A string representing the type of the vehicle, e.g., "Car", "Truck", "Bike".
-2. Implement two constructors for the `Vehicle` class:
-
- - A constructor that takes two parameters: `speed` and `type`. The `speed` should be set only if the value is greater than 0. Otherwise, the default speed should be 10. The `type` should always be set.
- - A default constructor that sets the `speed` to 10 and the `type` to "Bike".
-3. Implement the following methods for the `Vehicle` class:
-
- - `startEngine()`: This method should print "Engine started!".
- - `stopEngine()`: This method should print "Engine stopped!" and set the `speed` to 0.
- - `getSpeed()`: This method should return the current `speed` of the vehicle.
- - `getType()`: This method should return the current `type` of the vehicle.
-4. In the `main()` method of the `VehicleRunner` class, create three `Vehicle` instances with different speed and type values:
-
- - `car`: Speed 30, Type "Car".
- - `truck`: Speed 20, Type "Truck".
- - `bike`: Default constructor.
-5. Start the engine of all three vehicles and print their initial speed and type.
-
-6. Stop the engine of all three vehicles and print their final speed.
-
+ }
-#### Example
+ if (!evaluationHelper.isMethodDeclared(videoGame, "setNumberOfCopies", int.class)) {
-Below is an example of the incomplete code provided to the student:
+ fail("'setNumberOfCopies' method is not declared.");
+
+ }
+
+ if (!evaluationHelper.isMethodDeclared(videoGame, "getNumberOfCopies")) {
+
+ fail("'getNumberOfCopies' method is not declared.");
+
+ }
-```
-public class VehicleRunner {
- public static class Vehicle {
- // Write your code
- }
-
- public static void main(String[] args) {
- // Vehicle car = new Vehicle(30, "Car");
- // Write your code
}
+
}
-```
-After completing the exercise, the output should look like this:
-```
-Engine started!
-Engine started!
-Engine started!
-Earlier Car Speed is : 30, Type: Car
-Earlier Truck Speed is : 20, Type: Truck
-Earlier Bike Speed is : 10, Type: Bike
-Engine stopped!
-Engine stopped!
-Engine stopped!
-Stopped Car Speed is : 0
-Stopped Truck Speed is : 0
-Stopped Bike Speed is : 0
```
-### Hints
-Here are some hints for completing the given incomplete exercise code:
-1. Inside the `Vehicle` class, you need to declare two instance variables:
+
+
+## Exercise 2: Implementing Encapsulation Techniques in the VideoGame Class Part 2
+
+
+
+## Instructions
+
+
+You are asked to implement methods for the `VideoGame` class and perform some operations in the `main` method of the `VideoGameRunner` class.
+
+### Task 1: Implement methods for VideoGame class
+
+Implement the following methods for the `VideoGame` class:
+
+1. `increaseCopies(int howMuch)`: Increases the number of copies of the video game instance by the provided integer value, only if the value is greater than 0.
- - `speed` of type `int`
- - `type` of type `String`
-2. Create a constructor for the `Vehicle` class that takes two parameters:
+2. `decreaseCopies(int howMuch)`: Decreases the number of copies of the video game instance by the provided integer value, only if the value is greater than 0 and the resulting value is not negative. If the resulting value is negative, then the `numberOfCopies` attribute is set to 0.
- - `int speed`
- - `String type` Inside the constructor, initialize the instance variables with the given parameters.
-3. Create a default constructor for the `Vehicle` class. In this constructor, set default values for the instance variables:
+
+### Task 2: Perform operations in the main method of VideoGameRunner class
+
+In the `main` method of the `VideoGameRunner` class, do the following:
+
+1. Increase the number of copies for each video game instance as follows:
- - Set `speed` to `10`
- - Set `type` to `"Bike"`
-4. Add a method `startEngine()` to the `Vehicle` class that prints "Engine started!" when called.
+ - Increase the number of copies for `rdr2` by 12.
+ - Increase the number of copies for `tw3` by 18.
+ - Increase the number of copies for `botw` by 24.
+2. After increasing the number of copies for each video game instance, print the title and number of copies for each video game instance using the following format:
-5. Add a method `stopEngine()` to the `Vehicle` class that prints "Engine stopped!" when called and sets the `speed` of the vehicle to `0`.
+ ```
+ System.out.println(videoGameInstance.getTitle() + " - Number of copies after increasing copies : " + videoGameInstance.getNumberOfCopies());
+ ```
-6. Create getter methods for the `speed` and `type` instance variables in the `Vehicle` class:
+3. Decrease the number of copies for each video game instance as follows:
- - `public int getSpeed()`
- - `public String getType()`
-7. In the `main` method of the `VehicleRunner` class, create three instances of the `Vehicle` class:
+ - Decrease the number of copies for `rdr2` by 6.
+ - Decrease the number of copies for `tw3` by 12.
+ - Decrease the number of copies for `botw` by 18.
+4. After decreasing the number of copies for each video game instance, print the title and number of copies for each video game instance using the following format:
- - `Vehicle car = new Vehicle(30, "Car");`
- - `Vehicle truck = new Vehicle(20, "Truck");`
- - `Vehicle bike = new Vehicle();`
-8. Start the engine of each vehicle by calling the `startEngine()` method on each instance.
+ ```
+ System.out.println(videoGameInstance.getTitle() + " - Number of copies after decreasing copies : " + videoGameInstance.getNumberOfCopies());
+ ```
-9. Print the initial speed and type of each vehicle by calling the `getSpeed()` and `getType()` methods.
+
+The output should look like this:
+
+```
+Red Dead Redemption 2 - Number of copies: 5
+The Witcher 3 - Number of copies: 8
+Breath of the Wild - Number of copies: 10
+Red Dead Redemption 2 - Number of copies after increasing copies : 17
+The Witcher 3 - Number of copies after increasing copies : 26
+Breath of the Wild - Number of copies after increasing copies : 34
+Red Dead Redemption 2 - Number of copies after decreasing copies : 11
+The Witcher 3 - Number of copies after decreasing copies : 14
+Breath of the Wild - Number of copies after decreasing copies : 16
+```
+
+## Hints
+
+
+1. **Hint 1**: To implement the `increaseCopies()` method, first create a public method with the signature `public void increaseCopies(int howMuch)`. Inside the method, check if `howMuch` is greater than 0, and if it is, add `howMuch` to `numberOfCopies`.
-10. Stop the engine of each vehicle by calling the `stopEngine()` method on each instance.
+2. **Hint 2**: To implement the `decreaseCopies()` method, first create a public method with the signature `public void decreaseCopies(int howMuch)`. Inside the method, check if `howMuch` is greater than 0 and if the result of `numberOfCopies - howMuch` is greater than or equal to 0. If both conditions are true, subtract `howMuch` from `numberOfCopies`. If the resulting value is negative, set `numberOfCopies` to 0.
-11. Print the final speed of each vehicle after stopping the engine by calling the `getSpeed()` method.
+3. **Hint 3**: After implementing the `increaseCopies()` and `decreaseCopies()` methods, use them to increase and decrease the number of copies for each video game instance, as specified in the instructions.
+
+4. **Hint 4**: To print the updated number of copies after increasing and decreasing the copies, use the given format `System.out.println(videoGameInstance.getTitle() + " - Number of copies after (increasing/decreasing) copies : " + videoGameInstance.getNumberOfCopies());` after calling the respective methods.
-### Solution Explanation
-
+## Solution Explanation
-In this exercise, we're asked to complete the given incomplete `VehicleRunner` class by implementing the `Vehicle` class, its methods, and then creating instances of the `Vehicle` class in the `main` method. Here's the step-by-step explanation of the solution:
+The solution to this task can be broken down into two parts: implementing the `increaseCopies` and `decreaseCopies` methods for the `VideoGame` class, and then calling these methods in the `main` method of the `VideoGameRunner` class as instructed.
-### Implementing the Vehicle class
+### Implementing the increaseCopies and decreaseCopies methods
-1. First, we declare two instance variables for the `Vehicle` class:
- - `speed` of type `int`
- - `type` of type `String`
+First, we need to implement the `increaseCopies` and `decreaseCopies` methods inside the `VideoGame` class:
```
-private int speed;
-private String type;
-```
-
-2. Next, we create a constructor for the `Vehicle` class that takes two parameters:
- - `int speed`
- - `String type` Inside the constructor, we initialize the instance variables with the given parameters.
+public void increaseCopies(int howMuch) {
+ if (howMuch > 0) {
+ numberOfCopies += howMuch;
+ }
+}
-```
-public Vehicle(int speed, String type) {
- if (speed > 0) {
- this.speed = speed;
+public void decreaseCopies(int howMuch) {
+ if (howMuch > 0 && numberOfCopies >= howMuch) {
+ numberOfCopies -= howMuch;
+ } else {
+ numberOfCopies = 0;
}
- this.type = type;
}
```
-3. We then create a default constructor for the `Vehicle` class. In this constructor, we set default values for the instance variables:
- - Set `speed` to `10`
- - Set `type` to `"Bike"`
+In the `increaseCopies` method, we check if the provided integer value `howMuch` is greater than 0. If it is, we increase the `numberOfCopies` attribute by `howMuch`.
-```
-public Vehicle() {
- this.speed = 10;
- this.type = "Bike";
-}
-```
+In the `decreaseCopies` method, we again check if the provided integer value `howMuch` is greater than 0, and also if the `numberOfCopies` attribute is greater than or equal to `howMuch`. If both conditions are satisfied, we decrease the `numberOfCopies` attribute by `howMuch`. Otherwise, we set the `numberOfCopies` attribute to 0.
-4. We add a method `startEngine()` to the `Vehicle` class that prints "Engine started!" when called.
+### Calling the increaseCopies and decreaseCopies methods in the main method
+
+Next, we need to call the `increaseCopies` and `decreaseCopies` methods for each video game instance as instructed, and print the number of copies after each operation:
```
-public void startEngine() {
- System.out.println("Engine started!");
-}
-```
+// Increase the number of copies
+rdr2.increaseCopies(12);
+tw3.increaseCopies(18);
+botw.increaseCopies(24);
-5. We add another method `stopEngine()` to the `Vehicle` class that prints "Engine stopped!" when called and sets the `speed` of the vehicle to `0`.
+// Print number of copies after increasing copies
+System.out.println(rdr2.getTitle() + " - Number of copies after increasing copies : " + rdr2.getNumberOfCopies());
+System.out.println(tw3.getTitle() + " - Number of copies after increasing copies : " + tw3.getNumberOfCopies());
+System.out.println(botw.getTitle() + " - Number of copies after increasing copies : " + botw.getNumberOfCopies());
-```
-public void stopEngine() {
- System.out.println("Engine stopped!");
- this.speed = 0;
-}
+// Decrease the number of copies
+rdr2.decreaseCopies(6);
+tw3.decreaseCopies(12);
+botw.decreaseCopies(18);
+
+// Print number of copies after decreasing copies
+System.out.println(rdr2.getTitle() + " - Number of copies after decreasing copies : " + rdr2.getNumberOfCopies());
+System.out.println(tw3.getTitle() + " - Number of copies after decreasing copies : " + tw3.getNumberOfCopies());
+System.out.println(botw.getTitle() + " - Number of copies after decreasing copies : " + botw.getNumberOfCopies());
```
-6. We create getter methods for the `speed` and `type` instance variables in the `Vehicle` class:
- - `public int getSpeed()`
- - `public String getType()`
+We first increase the number of copies for each video game instance by calling the `increaseCopies` method with the specified values (12 for `rdr2`, 18 for `tw3`, and 24 for `botw`). Then, we print the number of copies after increasing copies using the provided format.
-```
-public int getSpeed() {
- return speed;
-}
+Next, we decrease the number of copies for each video game instance by calling the `decreaseCopies` method with the specified values (6 for `rdr2`, 12 for `tw3`, and 18 for `botw`). Finally, we print the number of copies after decreasing copies using the provided format.
+
+After incorporating these changes, the main method of the `VideoGameRunner` class should look like this:
-public String getType() {
- return type;
-}
```
+public static void main(String[] args) {
+ VideoGame rdr2 = new VideoGame();
+ rdr2.setTitle("Red Dead Redemption 2");
+ rdr2.setNumberOfCopies(5);
-### Creating instances and calling methods in the main method
+ VideoGame tw3 = new VideoGame();
+ tw3.setTitle("The Witcher 3");
+ tw3.setNumberOfCopies(8);
-7. In the `main` method of the `VehicleRunner` class, we create three instances of the `Vehicle` class:
+ VideoGame botw = new VideoGame();
+ botw.setTitle("Breath of the Wild");
+ botw.setNumberOfCopies(10);
-```
-Vehicle car = new Vehicle(30, "Car");
-Vehicle truck = new Vehicle(20, "Truck");
-Vehicle bike = new Vehicle();
-```
+ System.out.println(rdr2.getTitle() + " - Number of copies: " + rdr2.getNumberOfCopies());
+ System.out.println(tw3.getTitle() + " - Number of copies: " + tw3.getNumberOfCopies());
+ System.out.println(botw.getTitle() + " - Number of copies: " + botw.getNumberOfCopies());
-8. We start the engine of each vehicle by calling the `startEngine()` method on each instance:
+ // Increase the number of copies
+ rdr2.increaseCopies(12);
+ tw3.increaseCopies(18);
+ botw.increaseCopies(24);
-```
-car.startEngine();
-truck.startEngine();
-bike.startEngine();
-```
+ // Print number of copies after increasing copies
+ System.out.println(rdr2.getTitle() + " - Number of copies after increasing copies : " + rdr2.getNumberOfCopies());
+ System.out.println(tw3.getTitle() + " - Number of copies after increasing copies : " + tw3.getNumberOfCopies());
+ System.out.println(botw.getTitle() + " - Number of copies after increasing copies : " + botw.getNumberOfCopies());
-9. We print the initial speed and type of each vehicle by calling the `getSpeed()` and `getType()` methods:
+ // Decrease the number of copies
+ rdr2.decreaseCopies(6);
+ tw3.decreaseCopies(12);
+ botw.decreaseCopies(18);
-```
-System.out.println("Earlier Car Speed is : " + car.getSpeed() + ", Type: " + car.getType());
-System.out.println("Earlier Truck Speed is : " + truck.getSpeed() + ", Type: " + truck.getType());
-System.out.println("Earlier Bike Speed is : " + bike.getSpeed() + ", Type: " + bike.getType());
+ // Print number of copies after decreasing copies
+ System.out.println(rdr2.getTitle() + " - Number of copies after decreasing copies : " + rdr2.getNumberOfCopies());
+ System.out.println(tw3.getTitle() + " - Number of copies after decreasing copies : " + tw3.getNumberOfCopies());
+ System.out.println(botw.getTitle() + " - Number of copies after decreasing copies : " + botw.getNumberOfCopies());
+}
```
-10. We stop the engine of each vehicle by calling the `stopEngine()` method on each instance:
+When executed, this code will produce the expected output:
```
-car.stopEngine();
-truck.stopEngine();
-bike.stopEngine();
+Red Dead Redemption 2 - Number of copies: 5
+The Witcher 3 - Number of copies: 8
+Breath of the Wild - Number of copies: 10
+Red Dead Redemption 2 - Number of copies after increasing copies : 17
+The Witcher 3 - Number of copies after increasing copies : 26
+Breath of the Wild - Number of copies after increasing copies : 34
+Red Dead Redemption 2 - Number of copies after decreasing copies : 11
+The Witcher 3 - Number of copies after decreasing copies : 14
+Breath of the Wild - Number of copies after decreasing copies : 16`
```
-11. Finally, we print the final speed of each vehicle after stopping the engine by calling the `getSpeed()` method:
+This solution implements the required methods for the `VideoGame` class and demonstrates their functionality within the `main` method of the `VideoGameRunner` class.
+
+
+## Student File
+
+**VideoGameRunner.java**
```
-System.out.println("Stopped Car Speed is : " + car.getSpeed());
-System.out.println("Stopped Truck Speed is : " + truck.getSpeed());
-System.out.println("Stopped Bike Speed is : " + bike.getSpeed());
-```
+public class VideoGameRunner {
+
+ static class VideoGame {
+ private String title;
+ private int numberOfCopies;
-With this, we have successfully completed the implementation of the `VehicleRunner` class and its inner `Vehicle` class.
+ public void setTitle(String gameTitle) {
+ title = gameTitle;
+ }
-### Student File
+ public String getTitle() {
+ return title;
+ }
-**VehicleRunner.java**
+ public void setNumberOfCopies(int numberOfCopies) {
+ if (numberOfCopies >= 0) {
+ this.numberOfCopies = numberOfCopies;
+ }
+ }
-```
+ public int getNumberOfCopies() {
+ return numberOfCopies;
+ }
+
+ // TODO: Implement the increaseCopies() and decreaseCopies() methods for the VideoGame class
-public class VehicleRunner {
- public static class Vehicle {
- // Write your code
}
-
+
public static void main(String[] args) {
- // Vehicle car = new Vehicle(30, "Car");
- // Write your code
- }
+ VideoGame rdr2 = new VideoGame();
+ rdr2.setTitle("Red Dead Redemption 2");
+ rdr2.setNumberOfCopies(5);
-
+ VideoGame tw3 = new VideoGame();
+ tw3.setTitle("The Witcher 3");
+ tw3.setNumberOfCopies(8);
+
+ VideoGame botw = new VideoGame();
+ botw.setTitle("Breath of the Wild");
+ botw.setNumberOfCopies(10);
+
+ // Print initial number of copies for each video game
+ System.out.println(rdr2.getTitle() + " - Number of copies: " + rdr2.getNumberOfCopies());
+ System.out.println(tw3.getTitle() + " - Number of copies: " + tw3.getNumberOfCopies());
+ System.out.println(botw.getTitle() + " - Number of copies: " + botw.getNumberOfCopies());
+
+ // TODO: Increase the number of copies for each video game instance and print the updated number of copies
+
+ rdr2.increaseCopies(12);
+
+ // TODO: Print the updated number of copies for rdr2 after increasing copies
+
+ System.out.println(rdr2.getTitle() + " - Number of copies after increasing copies : " + rdr2.getNumberOfCopies());
+
+ // TODO: Decrease the number of copies for each video game instance and print the updated number of copies
+
+ rdr2.decreaseCopies(6);
+
+ // TODO: Print the updated number of copies for rdr2 after decreasing copies
+ System.out.println(rdr2.getTitle() + " - Number of copies after decreasing copies : " + rdr2.getNumberOfCopies());
+ }
}
+
```
-### Solution File
+## Solution File
-**VehicleRunner.java**
+**VideoGameRunner.java**
```
-public class VehicleRunner {
- public static class Vehicle {
- private int speed;
- private String type;
+public class VideoGameRunner {
- public Vehicle(int speed, String type) {
- if (speed > 0) {
- this.speed = speed;
- }
- this.type = type;
- }
+ static class VideoGame {
+ private String title;
+ private int numberOfCopies;
- public Vehicle() {
- this.speed = 10;
- this.type = "Bike";
+ public void setTitle(String gameTitle) {
+ title = gameTitle;
}
- public void startEngine() {
- System.out.println("Engine started!");
+ public String getTitle() {
+ return title;
}
- public void stopEngine() {
- System.out.println("Engine stopped!");
- this.speed = 0;
+ public void setNumberOfCopies(int numberOfCopies) {
+ if (numberOfCopies >= 0) {
+ this.numberOfCopies = numberOfCopies;
+ }
}
- public int getSpeed() {
- return speed;
+ public int getNumberOfCopies() {
+ return numberOfCopies;
}
-
- public String getType() {
- return type;
+
+ public void increaseCopies(int howMuch) {
+ if (howMuch > 0) {
+ numberOfCopies += howMuch;
}
}
-
- public static void main(String[] args) {
- Vehicle car = new Vehicle(30, "Car");
- Vehicle truck = new Vehicle(20, "Truck");
- Vehicle bike = new Vehicle();
- car.startEngine();
- truck.startEngine();
- bike.startEngine();
+ public void decreaseCopies(int howMuch) {
+ if (howMuch > 0 && numberOfCopies >= howMuch) {
+ numberOfCopies -= howMuch;
+ } else {
+ numberOfCopies = 0;
+ }
+ }
- System.out.println("Earlier Car Speed is : " + car.getSpeed() + ", Type: " + car.getType());
- System.out.println("Earlier Truck Speed is : " + truck.getSpeed() + ", Type: " + truck.getType());
- System.out.println("Earlier Bike Speed is : " + bike.getSpeed() + ", Type: " + bike.getType());
+ }
+
+ public static void main(String[] args) {
+ VideoGame rdr2 = new VideoGame();
+ rdr2.setTitle("Red Dead Redemption 2");
+ rdr2.setNumberOfCopies(5);
- car.stopEngine();
- truck.stopEngine();
- bike.stopEngine();
+ VideoGame tw3 = new VideoGame();
+ tw3.setTitle("The Witcher 3");
+ tw3.setNumberOfCopies(8);
- System.out.println("Stopped Car Speed is : " + car.getSpeed());
- System.out.println("Stopped Truck Speed is : " + truck.getSpeed());
- System.out.println("Stopped Bike Speed is : " + bike.getSpeed());
- }
+ VideoGame botw = new VideoGame();
+ botw.setTitle("Breath of the Wild");
+ botw.setNumberOfCopies(10);
-
+ System.out.println(rdr2.getTitle() + " - Number of copies: " + rdr2.getNumberOfCopies());
+ System.out.println(tw3.getTitle() + " - Number of copies: " + tw3.getNumberOfCopies());
+ System.out.println(botw.getTitle() + " - Number of copies: " + botw.getNumberOfCopies());
+
+
+ rdr2.increaseCopies(12);
+ tw3.increaseCopies(18);
+ botw.increaseCopies(24);
+
+ System.out.println(rdr2.getTitle() + " - Number of copies after increasing copies : " + rdr2.getNumberOfCopies());
+ System.out.println(tw3.getTitle() + " - Number of copies after increasing copies : " + tw3.getNumberOfCopies());
+ System.out.println(botw.getTitle() + " - Number of copies after increasing copies : " + botw.getNumberOfCopies());
+
+ rdr2.decreaseCopies(6);
+ tw3.decreaseCopies(12);
+ botw.decreaseCopies(18);
+
+ System.out.println(rdr2.getTitle() + " - Number of copies after decreasing copies : " + rdr2.getNumberOfCopies());
+ System.out.println(tw3.getTitle() + " - Number of copies after decreasing copies : " + tw3.getNumberOfCopies());
+ System.out.println(botw.getTitle() + " - Number of copies after decreasing copies : " + botw.getNumberOfCopies());
+ }
}
```
+
-### Evaluation File
+## Evaluation File
**Evaluate.java**
```
-
+import com.udemy.ucp.IOHelper;
import org.junit.jupiter.api.Test;
-import static org.junit.jupiter.api.Assertions.*;
+import java.util.logging.Logger;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import org.junit.jupiter.api.Assertions;
+import com.udemy.ucp.EvaluationHelper;
+import static org.junit.jupiter.api.Assertions.fail;
public class Evaluate {
+
+ IOHelper helper = new IOHelper();
+ private static final Logger LOGGER = Logger.getLogger(Evaluate.class.getName());
+ EvaluationHelper evaluationHelper = new EvaluationHelper();
+ VideoGameRunner.VideoGame videoGame = new VideoGameRunner.VideoGame();
+
+
+ @Test
+ public void testFieldsAndMethods() {
+ if (!evaluationHelper.isFieldDeclared(videoGame, "title", String.class)) {
+ fail("'title' field is not declared.");
+ }
+
+ if (!evaluationHelper.isFieldDeclared(videoGame, "numberOfCopies", int.class)) {
+ fail("'numberOfCopies' field is not declared.");
+ }
+
+ if (!evaluationHelper.isMethodDeclared(videoGame, "setTitle", String.class)) {
+ fail("'setTitle' method is not declared.");
+ }
+
+ if (!evaluationHelper.isMethodDeclared(videoGame, "getTitle")) {
+ fail("'getTitle' method is not declared.");
+ }
+
+ if (!evaluationHelper.isMethodDeclared(videoGame, "setNumberOfCopies", int.class)) {
+ fail("'setNumberOfCopies' method is not declared.");
+ }
+
+ if (!evaluationHelper.isMethodDeclared(videoGame, "getNumberOfCopies")) {
+ fail("'getNumberOfCopies' method is not declared.");
+ }
+ }
+
+
@Test
- public void testStartEngine() {
- VehicleRunner.Vehicle car = new VehicleRunner.Vehicle(30, "Car");
- VehicleRunner.Vehicle truck = new VehicleRunner.Vehicle(20, "Truck");
- VehicleRunner.Vehicle bike = new VehicleRunner.Vehicle();
-
- car.startEngine();
- truck.startEngine();
- bike.startEngine();
-
- System.out.println("Car Speed after starting engine: " + car.getSpeed());
- System.out.println("Truck Speed after starting engine: " + truck.getSpeed());
- System.out.println("Bike Speed after starting engine: " + bike.getSpeed());
-
- assertEquals(30, car.getSpeed());
- assertEquals(20, truck.getSpeed());
- assertEquals(10, bike.getSpeed());
+ public void testMainMethod() {
+ helper.resetStdOut(); // clean stdout
+ VideoGameRunner.main(new String[] {});
+ String actualOutput = helper.getOutput().trim(); // remove leading/trailing whitespaces
+ String[] lines = actualOutput.split("\n"); // split by line
+
+ // check each line to match expected format
+ assertEquals("Red Dead Redemption 2 - Number of copies: 5", lines[0]);
+ assertEquals("The Witcher 3 - Number of copies: 8", lines[1]);
+ assertEquals("Breath of the Wild - Number of copies: 10", lines[2]);
+ assertTrue(lines[3].startsWith("Red Dead Redemption 2 - Number of copies after increasing copies : "));
+ assertTrue(lines[4].startsWith("The Witcher 3 - Number of copies after increasing copies : "));
+ assertTrue(lines[5].startsWith("Breath of the Wild - Number of copies after increasing copies : "));
+ assertTrue(lines[6].startsWith("Red Dead Redemption 2 - Number of copies after decreasing copies : "));
+ assertTrue(lines[7].startsWith("The Witcher 3 - Number of copies after decreasing copies : "));
+ assertTrue(lines[8].startsWith("Breath of the Wild - Number of copies after decreasing copies : "));
}
+
@Test
- public void testStopEngine() {
- VehicleRunner.Vehicle car = new VehicleRunner.Vehicle(30, "Car");
- VehicleRunner.Vehicle truck = new VehicleRunner.Vehicle(20, "Truck");
- VehicleRunner.Vehicle bike = new VehicleRunner.Vehicle();
-
- car.startEngine();
- truck.startEngine();
- bike.startEngine();
-
- car.stopEngine();
- truck.stopEngine();
- bike.stopEngine();
-
- System.out.println("Car Speed after stopping engine: " + car.getSpeed());
- System.out.println("Truck Speed after stopping engine: " + truck.getSpeed());
- System.out.println("Bike Speed after stopping engine: " + bike.getSpeed());
-
- assertEquals(0, car.getSpeed());
- assertEquals(0, truck.getSpeed());
- assertEquals(0, bike.getSpeed());
+ public void testRdr2Output() {
+ helper.resetStdOut(); // clean stdout
+ VideoGameRunner.main(new String[] {});
+ String actualOutput = helper.getOutput();
+ assertTrue(actualOutput.contains("Red Dead Redemption 2 - Number of copies: 5"), "Output does not contain expected string: Red Dead Redemption 2 - Number of copies: 5");
}
@Test
- public void testGetType() {
- VehicleRunner.Vehicle car = new VehicleRunner.Vehicle(30, "Car");
- VehicleRunner.Vehicle truck = new VehicleRunner.Vehicle(20, "Truck");
- VehicleRunner.Vehicle bike = new VehicleRunner.Vehicle();
-
- System.out.println("Car type: " + car.getType());
- System.out.println("Truck type: " + truck.getType());
- System.out.println("Bike type: " + bike.getType());
-
- assertEquals("Car", car.getType());
- assertEquals("Truck", truck.getType());
- assertEquals("Bike", bike.getType());
+ public void testTw3Output() {
+ helper.resetStdOut(); // clean stdout
+ VideoGameRunner.main(new String[] {});
+ String actualOutput = helper.getOutput();
+ assertTrue(actualOutput.contains("The Witcher 3 - Number of copies: 8"), "Output does not contain expected string: The Witcher 3 - Number of copies: 8");
+ }
+
+ @Test
+ public void testBotwOutput() {
+ helper.resetStdOut(); // clean stdout
+ VideoGameRunner.main(new String[] {});
+ String actualOutput = helper.getOutput();
+ assertTrue(actualOutput.contains("Breath of the Wild - Number of copies: 10"), "Output does not contain expected string: Breath of the Wild - Number of copies: 10");
+ }
+
+ @Test
+ public void testIncreaseCopies() {
+ VideoGameRunner.VideoGame game = new VideoGameRunner.VideoGame();
+ game.setNumberOfCopies(10);
+ game.increaseCopies(5);
+ assertEquals(15, game.getNumberOfCopies(), "Number of copies did not increase by the expected amount.");
}
-}
+ @Test
+ public void testDecreaseCopies() {
+ VideoGameRunner.VideoGame game = new VideoGameRunner.VideoGame();
+ game.setNumberOfCopies(10);
+ game.decreaseCopies(5);
+ assertEquals(5, game.getNumberOfCopies(), "Number of copies did not decrease by the expected amount.");
+ }
+ @Test
+ public void testIncreaseCopiesOutput() {
+ helper.resetStdOut(); // clean stdout
+ VideoGameRunner.main(new String[] {});
+ String actualOutput = helper.getOutput();
+ assertTrue(actualOutput.contains("Red Dead Redemption 2 - Number of copies after increasing copies : 17"), "Output does not contain expected string: Red Dead Redemption 2 - Number of copies after increasing copies : 17");
+ assertTrue(actualOutput.contains("The Witcher 3 - Number of copies after increasing copies : 26"), "Output does not contain expected string: The Witcher 3 - Number of copies after increasing copies : 26");
+ assertTrue(actualOutput.contains("Breath of the Wild - Number of copies after increasing copies : 34"), "Output does not contain expected string: Breath of the Wild - Number of copies after increasing copies : 34");
+ }
+
+ @Test
+ public void testDecreaseCopiesOutput() {
+ helper.resetStdOut(); // clean stdout
+ VideoGameRunner.main(new String[] {});
+ String actualOutput = helper.getOutput();
+ assertTrue(actualOutput.contains("Red Dead Redemption 2 - Number of copies after decreasing copies : 11"), "Output does not contain expected string: Red Dead Redemption 2 - Number of copies after decreasing copies : 11");
+ assertTrue(actualOutput.contains("The Witcher 3 - Number of copies after decreasing copies : 14"), "Output does not contain expected string: The Witcher 3 - Number of copies after decreasing copies : 14");
+ assertTrue(actualOutput.contains("Breath of the Wild - Number of copies after decreasing copies : 16"), "Output does not contain expected string: Breath of the Wild - Number of copies after decreasing copies : 16");
+ }
+}
```
\ No newline at end of file
diff --git a/02-CodeChallenge/05-RENEW.md b/02-CodeChallenge/05-RENEW.md
deleted file mode 100644
index e70d4274..00000000
--- a/02-CodeChallenge/05-RENEW.md
+++ /dev/null
@@ -1,928 +0,0 @@
-
-## Exercise 1: Implementing Encapsulation Techniques in the VideoGame Class Part 1
-
-
-
-## Instructions
-
-
-**Instructions**
-
-**Task 1: Implement VideoGame class attributes**
-
-In the given `VideoGameRunner` class, add the following attributes to the `VideoGame` class:
-
-- `title` of type `String`
-
-- `numberOfCopies` of type `int`
-
-
-**Task 2: Implement methods for VideoGame class**
-
-Implement the following methods for the `VideoGame` class:
-
-- `setTitle(String gameTitle)`: Sets the title of the video game.
-
-- `getTitle()`: Returns the title of the video game.
-
-- `setNumberOfCopies(int numberOfCopies)`: Sets the number of copies if the provided number is greater than or equal to 0.
-
-- `getNumberOfCopies()`: Returns the number of copies.
-
-
-**Task 3: Test the VideoGame class in the main method**
-
-In the `main` method of the `VideoGameRunner` class, do the following:
-
-1. Create three instances of the `VideoGame` class and set their titles as follows:
-
- - Create an instance named `rdr2` and set its title to "Red Dead Redemption 2".
-
- - Create an instance named `tw3` and set its title to "The Witcher 3".
-
- - Create an instance named `botw` and set its title to "Breath of the Wild".
-
-2. Set the number of copies for each video game instance as follows:
-
- - Set the number of copies for `rdr2` to 5.
-
- - Set the number of copies for `tw3` to 8.
-
- - Set the number of copies for `botw` to 10.
-
-3. After setting the number of copies for each video game instance, print the title and number of copies for each video game instance using the following format:
-
- ```
- System.out.println(videoGameInstance.getTitle() + " - Number of copies: " + videoGameInstance.getNumberOfCopies());
-```
-
-
-**The output should look like:**
-
-
-```
-Red Dead Redemption 2 - Number of copies: 5
-The Witcher 3 - Number of copies: 8
-Breath of the Wild - Number of copies: 10
-```
-
-## Hints
-
-1. Task 1 requires you to add the attributes `title` and `numberOfCopies` to the `VideoGame` class. To do this, you need to declare these attributes as private instance variables in the `VideoGame` class.
-
-2. Task 2 requires you to implement four methods in the `VideoGame` class: `setTitle(String gameTitle)`, `getTitle()`, `setNumberOfCopies(int numberOfCopies)`, and `getNumberOfCopies()`. Remember to use appropriate access modifiers and parameter types for each method.
-
-3. For Task 3, start by creating three instances of the `VideoGame` class: `rdr2`, `tw3`, and `botw`. Then use the `setTitle(String gameTitle)` method to set the title of each instance, and use the `setNumberOfCopies(int numberOfCopies)` method to set the number of copies for each instance.
-
-4. After setting the number of copies for each instance, use the `getTitle()` and `getNumberOfCopies()` methods to print the title and number of copies for each instance using the format shown in the problem statement.
-
-
-I hope these hints help you complete the exercise!
-
-
-## Solution Explanation
-
-In this problem, we need to implement a VideoGame class and test it in the main method of the VideoGameRunner class.
-
-**Task 1: Implement VideoGame class attributes**
-
-In the VideoGame class, we need to add two attributes: `title` of type `String` and `numberOfCopies` of type `int`.
-
-```
-public class VideoGame {
- private String title;
- private int numberOfCopies;
-}
-```
-
-**Task 2: Implement methods for VideoGame class**
-
-In the VideoGame class, we need to implement four methods: `setTitle`, `getTitle`, `setNumberOfCopies`, and `getNumberOfCopies`.
-
-`setTitle(String gameTitle)`: Sets the title of the video game.
-
-```
-public void setTitle(String gameTitle) {
- title = gameTitle;
-}
-```
-
-`getTitle()`: Returns the title of the video game.
-
-```
-public String getTitle() {
- return title;
-}
-```
-
-`setNumberOfCopies(int numberOfCopies)`: Sets the number of copies if the provided number is greater than or equal to 0.
-
-```
-public void setNumberOfCopies(int numberOfCopies) {
- if (numberOfCopies >= 0) {
- this.numberOfCopies = numberOfCopies;
- }
-}`
-```
-
-`getNumberOfCopies()`: Returns the number of copies.
-
-```
-public int getNumberOfCopies() {
- return numberOfCopies;
-}
-```
-
-**Task 3: Test the VideoGame class in the main method**
-
-In the main method of the VideoGameRunner class, we need to create three instances of the VideoGame class and set their titles. Then, we need to set the number of copies for each video game instance and print the title and number of copies for each video game instance.
-
-```
-public static void main(String[] args) {
- VideoGame rdr2 = new VideoGame();
- rdr2.setTitle("Red Dead Redemption 2");
- rdr2.setNumberOfCopies(5);
-
- VideoGame tw3 = new VideoGame();
- tw3.setTitle("The Witcher 3");
- tw3.setNumberOfCopies(8);
-
- VideoGame botw = new VideoGame();
- botw.setTitle("Breath of the Wild");
- botw.setNumberOfCopies(10);
-
- System.out.println(rdr2.getTitle() + " - Number of copies: " + rdr2.getNumberOfCopies());
- System.out.println(tw3.getTitle() + " - Number of copies: " + tw3.getNumberOfCopies());
- System.out.println(botw.getTitle() + " - Number of copies: " + botw.getNumberOfCopies());
-}
-```
-
-The above code creates three VideoGame instances `rdr2`, `tw3`, and `botw`. Then, it sets the titles and number of copies for each instance. Finally, it prints the title and number of copies for each video game instance.
-
-The output of the above code is:
-
-```
-Red Dead Redemption 2 - Number of copies: 5
-The Witcher 3 - Number of copies: 8
-Breath of the Wild - Number of copies: 10
-```
-
-This output matches the expected output mentioned in the problem statement.
-
-
-## Student File
-
-**VideoGameRunner.java**
-
-```
-public class VideoGameRunner {
-
- static class VideoGame {
- // Add two private attributes: title (type: String) and numberOfCopies (type: int)
-
- // Implement setTitle method: public void setTitle(String gameTitle)
-
- // Implement getTitle method: public String getTitle()
-
- // Implement setNumberOfCopies method: public void setNumberOfCopies(int numberOfCopies) with a condition to check if numberOfCopies is greater than or equal to 0
-
- // Implement getNumberOfCopies method: public int getNumberOfCopies()
- }
-
- public static void main(String[] args) {
- // Create a VideoGame instance called rdr2 and set its title to "Red Dead Redemption 2"
- // Set the number of copies for rdr2 to 5
- // VideoGame rdr2 = new VideoGame();
- // rdr2.setTitle("Red Dead Redemption 2");
- // rdr2.setNumberOfCopies(5);
-
- // Create a VideoGame instance called tw3 and set its title to "The Witcher 3"
- // Set the number of copies for tw3 to 8
-
- // Create a VideoGame instance called botw and set its title to "Breath of the Wild"
- // Set the number of copies for botw to 10
-
- // Print the title and number of copies for each instance in the format: "Title - Number of copies: X"
- // System.out.println(rdr2.getTitle() + " - Number of copies: " + rdr2.getNumberOfCopies());
- }
-}
-
-```
-
-
-
-
-## Solution File
-
-**VideoGameRunner.java**
-
-```
-public class VideoGameRunner {
-
- static class VideoGame {
- private String title;
- private int numberOfCopies;
-
- public void setTitle(String gameTitle) {
- title = gameTitle;
- }
-
- public String getTitle() {
- return title;
- }
-
- public void setNumberOfCopies(int numberOfCopies) {
- if (numberOfCopies >= 0) {
- this.numberOfCopies = numberOfCopies;
- }
- }
-
- public int getNumberOfCopies() {
- return numberOfCopies;
- }
- }
-
- public static void main(String[] args) {
- VideoGame rdr2 = new VideoGame();
- rdr2.setTitle("Red Dead Redemption 2");
- rdr2.setNumberOfCopies(5);
-
- VideoGame tw3 = new VideoGame();
- tw3.setTitle("The Witcher 3");
- tw3.setNumberOfCopies(8);
-
- VideoGame botw = new VideoGame();
- botw.setTitle("Breath of the Wild");
- botw.setNumberOfCopies(10);
-
- System.out.println(rdr2.getTitle() + " - Number of copies: " + rdr2.getNumberOfCopies());
- System.out.println(tw3.getTitle() + " - Number of copies: " + tw3.getNumberOfCopies());
- System.out.println(botw.getTitle() + " - Number of copies: " + botw.getNumberOfCopies());
- }
-}
-
-```
-
-
-
-## Evaluation File
-
-**Evaluate.java**
-
-```
-import com.udemy.ucp.IOHelper;
-
-import com.udemy.ucp.EvaluationHelper;
-
-import org.junit.jupiter.api.Test;
-
-import java.util.logging.Logger;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import static org.junit.jupiter.api.Assertions.fail;
-
-
-
-public class Evaluate {
-
-
-
- IOHelper helper = new IOHelper();
-
- EvaluationHelper evaluationHelper = new EvaluationHelper();
-
- VideoGameRunner.VideoGame videoGame = new VideoGameRunner.VideoGame();
-
-
-
- private static final Logger LOGGER = Logger.getLogger(Evaluate.class.getName());
-
-
-
- @Test
-
- public void testMainMethod() {
-
- helper.resetStdOut(); // clean stdout
-
- VideoGameRunner.main(new String[] {});
-
- String actualOutput = helper.getOutput();
-
- String refinedActualOutput = helper.getOutput().replace("\n", " ");
-
-
-
- String expectedOutput = "Red Dead Redemption 2 - Number of copies: 5\n" +
-
- "The Witcher 3 - Number of copies: 8\n" +
-
- "Breath of the Wild - Number of copies: 10\n";
-
- LOGGER.info("Expected Output: " + expectedOutput);
-
- LOGGER.info("Actual Output: " + actualOutput);
-
- assertEquals(expectedOutput, actualOutput, "Output does not match the expected value. Please check user logs for more detailed view. Expected: Red Dead Redemption 2 - Number of copies: 5 " +
-
- "The Witcher 3 - Number of copies: 8 " +
-
- "Breath of the Wild - Number of copies: 10 " + ", actual: " + refinedActualOutput);
-
- }
-
- @Test
-
- public void testRdr2Output() {
-
- helper.resetStdOut(); // clean stdout
-
- VideoGameRunner.main(new String[] {});
-
- String actualOutput = helper.getOutput();
-
- assertTrue(actualOutput.contains("Red Dead Redemption 2 - Number of copies: 5"), "Output does not contain expected string: Red Dead Redemption 2 - Number of copies: 5");
-
- }
-
-
-
- @Test
-
- public void testTw3Output() {
-
- helper.resetStdOut(); // clean stdout
-
- VideoGameRunner.main(new String[] {});
-
- String actualOutput = helper.getOutput();
-
- assertTrue(actualOutput.contains("The Witcher 3 - Number of copies: 8"), "Output does not contain expected string: The Witcher 3 - Number of copies: 8");
-
- }
-
-
-
- @Test
-
- public void testBotwOutput() {
-
- helper.resetStdOut(); // clean stdout
-
- VideoGameRunner.main(new String[] {});
-
- String actualOutput = helper.getOutput();
-
- assertTrue(actualOutput.contains("Breath of the Wild - Number of copies: 10"), "Output does not contain expected string: Breath of the Wild - Number of copies: 10");
-
- }
-
- @Test
-
- public void testFieldsAndMethods() {
-
- if (!evaluationHelper.isFieldDeclared(videoGame, "title", String.class)) {
-
- fail("'title' field is not declared.");
-
- }
-
- if (!evaluationHelper.isFieldDeclared(videoGame, "numberOfCopies", int.class)) {
-
- fail("'numberOfCopies' field is not declared.");
-
- }
-
- if (!evaluationHelper.isMethodDeclared(videoGame, "setTitle", String.class)) {
-
- fail("'setTitle' method is not declared.");
-
- }
-
- if (!evaluationHelper.isMethodDeclared(videoGame, "getTitle")) {
-
- fail("'getTitle' method is not declared.");
-
- }
-
- if (!evaluationHelper.isMethodDeclared(videoGame, "setNumberOfCopies", int.class)) {
-
- fail("'setNumberOfCopies' method is not declared.");
-
- }
-
- if (!evaluationHelper.isMethodDeclared(videoGame, "getNumberOfCopies")) {
-
- fail("'getNumberOfCopies' method is not declared.");
-
- }
-
- }
-
-}
-
-```
-
-
-
-
-
-
-
-## Exercise 2: Implementing Encapsulation Techniques in the VideoGame Class Part 2
-
-
-
-## Instructions
-
-
-You are asked to implement methods for the `VideoGame` class and perform some operations in the `main` method of the `VideoGameRunner` class.
-
-### Task 1: Implement methods for VideoGame class
-
-Implement the following methods for the `VideoGame` class:
-
-1. `increaseCopies(int howMuch)`: Increases the number of copies of the video game instance by the provided integer value, only if the value is greater than 0.
-
-2. `decreaseCopies(int howMuch)`: Decreases the number of copies of the video game instance by the provided integer value, only if the value is greater than 0 and the resulting value is not negative. If the resulting value is negative, then the `numberOfCopies` attribute is set to 0.
-
-
-### Task 2: Perform operations in the main method of VideoGameRunner class
-
-In the `main` method of the `VideoGameRunner` class, do the following:
-
-1. Increase the number of copies for each video game instance as follows:
-
- - Increase the number of copies for `rdr2` by 12.
- - Increase the number of copies for `tw3` by 18.
- - Increase the number of copies for `botw` by 24.
-2. After increasing the number of copies for each video game instance, print the title and number of copies for each video game instance using the following format:
-
- ```
- System.out.println(videoGameInstance.getTitle() + " - Number of copies after increasing copies : " + videoGameInstance.getNumberOfCopies());
- ```
-
-3. Decrease the number of copies for each video game instance as follows:
-
- - Decrease the number of copies for `rdr2` by 6.
- - Decrease the number of copies for `tw3` by 12.
- - Decrease the number of copies for `botw` by 18.
-4. After decreasing the number of copies for each video game instance, print the title and number of copies for each video game instance using the following format:
-
- ```
- System.out.println(videoGameInstance.getTitle() + " - Number of copies after decreasing copies : " + videoGameInstance.getNumberOfCopies());
- ```
-
-
-The output should look like this:
-
-```
-Red Dead Redemption 2 - Number of copies: 5
-The Witcher 3 - Number of copies: 8
-Breath of the Wild - Number of copies: 10
-Red Dead Redemption 2 - Number of copies after increasing copies : 17
-The Witcher 3 - Number of copies after increasing copies : 26
-Breath of the Wild - Number of copies after increasing copies : 34
-Red Dead Redemption 2 - Number of copies after decreasing copies : 11
-The Witcher 3 - Number of copies after decreasing copies : 14
-Breath of the Wild - Number of copies after decreasing copies : 16
-```
-
-## Hints
-
-
-1. **Hint 1**: To implement the `increaseCopies()` method, first create a public method with the signature `public void increaseCopies(int howMuch)`. Inside the method, check if `howMuch` is greater than 0, and if it is, add `howMuch` to `numberOfCopies`.
-
-2. **Hint 2**: To implement the `decreaseCopies()` method, first create a public method with the signature `public void decreaseCopies(int howMuch)`. Inside the method, check if `howMuch` is greater than 0 and if the result of `numberOfCopies - howMuch` is greater than or equal to 0. If both conditions are true, subtract `howMuch` from `numberOfCopies`. If the resulting value is negative, set `numberOfCopies` to 0.
-
-3. **Hint 3**: After implementing the `increaseCopies()` and `decreaseCopies()` methods, use them to increase and decrease the number of copies for each video game instance, as specified in the instructions.
-
-4. **Hint 4**: To print the updated number of copies after increasing and decreasing the copies, use the given format `System.out.println(videoGameInstance.getTitle() + " - Number of copies after (increasing/decreasing) copies : " + videoGameInstance.getNumberOfCopies());` after calling the respective methods.
-
-
-## Solution Explanation
-
-
-The solution to this task can be broken down into two parts: implementing the `increaseCopies` and `decreaseCopies` methods for the `VideoGame` class, and then calling these methods in the `main` method of the `VideoGameRunner` class as instructed.
-
-### Implementing the increaseCopies and decreaseCopies methods
-
-First, we need to implement the `increaseCopies` and `decreaseCopies` methods inside the `VideoGame` class:
-
-```
-public void increaseCopies(int howMuch) {
- if (howMuch > 0) {
- numberOfCopies += howMuch;
- }
-}
-
-public void decreaseCopies(int howMuch) {
- if (howMuch > 0 && numberOfCopies >= howMuch) {
- numberOfCopies -= howMuch;
- } else {
- numberOfCopies = 0;
- }
-}
-```
-
-In the `increaseCopies` method, we check if the provided integer value `howMuch` is greater than 0. If it is, we increase the `numberOfCopies` attribute by `howMuch`.
-
-In the `decreaseCopies` method, we again check if the provided integer value `howMuch` is greater than 0, and also if the `numberOfCopies` attribute is greater than or equal to `howMuch`. If both conditions are satisfied, we decrease the `numberOfCopies` attribute by `howMuch`. Otherwise, we set the `numberOfCopies` attribute to 0.
-
-### Calling the increaseCopies and decreaseCopies methods in the main method
-
-Next, we need to call the `increaseCopies` and `decreaseCopies` methods for each video game instance as instructed, and print the number of copies after each operation:
-
-```
-// Increase the number of copies
-rdr2.increaseCopies(12);
-tw3.increaseCopies(18);
-botw.increaseCopies(24);
-
-// Print number of copies after increasing copies
-System.out.println(rdr2.getTitle() + " - Number of copies after increasing copies : " + rdr2.getNumberOfCopies());
-System.out.println(tw3.getTitle() + " - Number of copies after increasing copies : " + tw3.getNumberOfCopies());
-System.out.println(botw.getTitle() + " - Number of copies after increasing copies : " + botw.getNumberOfCopies());
-
-// Decrease the number of copies
-rdr2.decreaseCopies(6);
-tw3.decreaseCopies(12);
-botw.decreaseCopies(18);
-
-// Print number of copies after decreasing copies
-System.out.println(rdr2.getTitle() + " - Number of copies after decreasing copies : " + rdr2.getNumberOfCopies());
-System.out.println(tw3.getTitle() + " - Number of copies after decreasing copies : " + tw3.getNumberOfCopies());
-System.out.println(botw.getTitle() + " - Number of copies after decreasing copies : " + botw.getNumberOfCopies());
-```
-
-We first increase the number of copies for each video game instance by calling the `increaseCopies` method with the specified values (12 for `rdr2`, 18 for `tw3`, and 24 for `botw`). Then, we print the number of copies after increasing copies using the provided format.
-
-Next, we decrease the number of copies for each video game instance by calling the `decreaseCopies` method with the specified values (6 for `rdr2`, 12 for `tw3`, and 18 for `botw`). Finally, we print the number of copies after decreasing copies using the provided format.
-
-After incorporating these changes, the main method of the `VideoGameRunner` class should look like this:
-
-```
-public static void main(String[] args) {
- VideoGame rdr2 = new VideoGame();
- rdr2.setTitle("Red Dead Redemption 2");
- rdr2.setNumberOfCopies(5);
-
- VideoGame tw3 = new VideoGame();
- tw3.setTitle("The Witcher 3");
- tw3.setNumberOfCopies(8);
-
- VideoGame botw = new VideoGame();
- botw.setTitle("Breath of the Wild");
- botw.setNumberOfCopies(10);
-
- System.out.println(rdr2.getTitle() + " - Number of copies: " + rdr2.getNumberOfCopies());
- System.out.println(tw3.getTitle() + " - Number of copies: " + tw3.getNumberOfCopies());
- System.out.println(botw.getTitle() + " - Number of copies: " + botw.getNumberOfCopies());
-
- // Increase the number of copies
- rdr2.increaseCopies(12);
- tw3.increaseCopies(18);
- botw.increaseCopies(24);
-
- // Print number of copies after increasing copies
- System.out.println(rdr2.getTitle() + " - Number of copies after increasing copies : " + rdr2.getNumberOfCopies());
- System.out.println(tw3.getTitle() + " - Number of copies after increasing copies : " + tw3.getNumberOfCopies());
- System.out.println(botw.getTitle() + " - Number of copies after increasing copies : " + botw.getNumberOfCopies());
-
- // Decrease the number of copies
- rdr2.decreaseCopies(6);
- tw3.decreaseCopies(12);
- botw.decreaseCopies(18);
-
- // Print number of copies after decreasing copies
- System.out.println(rdr2.getTitle() + " - Number of copies after decreasing copies : " + rdr2.getNumberOfCopies());
- System.out.println(tw3.getTitle() + " - Number of copies after decreasing copies : " + tw3.getNumberOfCopies());
- System.out.println(botw.getTitle() + " - Number of copies after decreasing copies : " + botw.getNumberOfCopies());
-}
-```
-
-When executed, this code will produce the expected output:
-
-```
-Red Dead Redemption 2 - Number of copies: 5
-The Witcher 3 - Number of copies: 8
-Breath of the Wild - Number of copies: 10
-Red Dead Redemption 2 - Number of copies after increasing copies : 17
-The Witcher 3 - Number of copies after increasing copies : 26
-Breath of the Wild - Number of copies after increasing copies : 34
-Red Dead Redemption 2 - Number of copies after decreasing copies : 11
-The Witcher 3 - Number of copies after decreasing copies : 14
-Breath of the Wild - Number of copies after decreasing copies : 16`
-```
-
-This solution implements the required methods for the `VideoGame` class and demonstrates their functionality within the `main` method of the `VideoGameRunner` class.
-
-
-## Student File
-
-**VideoGameRunner.java**
-
-```
-public class VideoGameRunner {
-
- static class VideoGame {
- private String title;
- private int numberOfCopies;
-
- public void setTitle(String gameTitle) {
- title = gameTitle;
- }
-
- public String getTitle() {
- return title;
- }
-
- public void setNumberOfCopies(int numberOfCopies) {
- if (numberOfCopies >= 0) {
- this.numberOfCopies = numberOfCopies;
- }
- }
-
- public int getNumberOfCopies() {
- return numberOfCopies;
- }
-
- // TODO: Implement the increaseCopies() and decreaseCopies() methods for the VideoGame class
-
- }
-
- public static void main(String[] args) {
- VideoGame rdr2 = new VideoGame();
- rdr2.setTitle("Red Dead Redemption 2");
- rdr2.setNumberOfCopies(5);
-
- VideoGame tw3 = new VideoGame();
- tw3.setTitle("The Witcher 3");
- tw3.setNumberOfCopies(8);
-
- VideoGame botw = new VideoGame();
- botw.setTitle("Breath of the Wild");
- botw.setNumberOfCopies(10);
-
- // Print initial number of copies for each video game
- System.out.println(rdr2.getTitle() + " - Number of copies: " + rdr2.getNumberOfCopies());
- System.out.println(tw3.getTitle() + " - Number of copies: " + tw3.getNumberOfCopies());
- System.out.println(botw.getTitle() + " - Number of copies: " + botw.getNumberOfCopies());
-
- // TODO: Increase the number of copies for each video game instance and print the updated number of copies
-
- rdr2.increaseCopies(12);
-
- // TODO: Print the updated number of copies for rdr2 after increasing copies
-
- System.out.println(rdr2.getTitle() + " - Number of copies after increasing copies : " + rdr2.getNumberOfCopies());
-
- // TODO: Decrease the number of copies for each video game instance and print the updated number of copies
-
- rdr2.decreaseCopies(6);
-
- // TODO: Print the updated number of copies for rdr2 after decreasing copies
- System.out.println(rdr2.getTitle() + " - Number of copies after decreasing copies : " + rdr2.getNumberOfCopies());
- }
-}
-
-```
-
-
-
-
-## Solution File
-
-**VideoGameRunner.java**
-
-```
-public class VideoGameRunner {
-
- static class VideoGame {
- private String title;
- private int numberOfCopies;
-
- public void setTitle(String gameTitle) {
- title = gameTitle;
- }
-
- public String getTitle() {
- return title;
- }
-
- public void setNumberOfCopies(int numberOfCopies) {
- if (numberOfCopies >= 0) {
- this.numberOfCopies = numberOfCopies;
- }
- }
-
- public int getNumberOfCopies() {
- return numberOfCopies;
- }
-
- public void increaseCopies(int howMuch) {
- if (howMuch > 0) {
- numberOfCopies += howMuch;
- }
- }
-
- public void decreaseCopies(int howMuch) {
- if (howMuch > 0 && numberOfCopies >= howMuch) {
- numberOfCopies -= howMuch;
- } else {
- numberOfCopies = 0;
- }
- }
-
- }
-
- public static void main(String[] args) {
- VideoGame rdr2 = new VideoGame();
- rdr2.setTitle("Red Dead Redemption 2");
- rdr2.setNumberOfCopies(5);
-
- VideoGame tw3 = new VideoGame();
- tw3.setTitle("The Witcher 3");
- tw3.setNumberOfCopies(8);
-
- VideoGame botw = new VideoGame();
- botw.setTitle("Breath of the Wild");
- botw.setNumberOfCopies(10);
-
- System.out.println(rdr2.getTitle() + " - Number of copies: " + rdr2.getNumberOfCopies());
- System.out.println(tw3.getTitle() + " - Number of copies: " + tw3.getNumberOfCopies());
- System.out.println(botw.getTitle() + " - Number of copies: " + botw.getNumberOfCopies());
-
-
- rdr2.increaseCopies(12);
- tw3.increaseCopies(18);
- botw.increaseCopies(24);
-
- System.out.println(rdr2.getTitle() + " - Number of copies after increasing copies : " + rdr2.getNumberOfCopies());
- System.out.println(tw3.getTitle() + " - Number of copies after increasing copies : " + tw3.getNumberOfCopies());
- System.out.println(botw.getTitle() + " - Number of copies after increasing copies : " + botw.getNumberOfCopies());
-
- rdr2.decreaseCopies(6);
- tw3.decreaseCopies(12);
- botw.decreaseCopies(18);
-
- System.out.println(rdr2.getTitle() + " - Number of copies after decreasing copies : " + rdr2.getNumberOfCopies());
- System.out.println(tw3.getTitle() + " - Number of copies after decreasing copies : " + tw3.getNumberOfCopies());
- System.out.println(botw.getTitle() + " - Number of copies after decreasing copies : " + botw.getNumberOfCopies());
- }
-}
-
-```
-
-
-
-## Evaluation File
-
-**Evaluate.java**
-
-```
-import com.udemy.ucp.IOHelper;
-import org.junit.jupiter.api.Test;
-import java.util.logging.Logger;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-import org.junit.jupiter.api.Assertions;
-import com.udemy.ucp.EvaluationHelper;
-import static org.junit.jupiter.api.Assertions.fail;
-
-public class Evaluate {
-
- IOHelper helper = new IOHelper();
- private static final Logger LOGGER = Logger.getLogger(Evaluate.class.getName());
- EvaluationHelper evaluationHelper = new EvaluationHelper();
- VideoGameRunner.VideoGame videoGame = new VideoGameRunner.VideoGame();
-
-
- @Test
- public void testFieldsAndMethods() {
- if (!evaluationHelper.isFieldDeclared(videoGame, "title", String.class)) {
- fail("'title' field is not declared.");
- }
-
- if (!evaluationHelper.isFieldDeclared(videoGame, "numberOfCopies", int.class)) {
- fail("'numberOfCopies' field is not declared.");
- }
-
- if (!evaluationHelper.isMethodDeclared(videoGame, "setTitle", String.class)) {
- fail("'setTitle' method is not declared.");
- }
-
- if (!evaluationHelper.isMethodDeclared(videoGame, "getTitle")) {
- fail("'getTitle' method is not declared.");
- }
-
- if (!evaluationHelper.isMethodDeclared(videoGame, "setNumberOfCopies", int.class)) {
- fail("'setNumberOfCopies' method is not declared.");
- }
-
- if (!evaluationHelper.isMethodDeclared(videoGame, "getNumberOfCopies")) {
- fail("'getNumberOfCopies' method is not declared.");
- }
- }
-
- @Test
- public void testSetAndGetMethods() {
- try {
- assertTrue(VideoGameRunner.VideoGame.class.getDeclaredMethod("setTitle", String.class) != null, "Method setTitle is not declared in VideoGame class.");
- assertTrue(VideoGameRunner.VideoGame.class.getDeclaredMethod("getTitle") != null, "Method getTitle is not declared in VideoGame class.");
- assertTrue(VideoGameRunner.VideoGame.class.getDeclaredMethod("setNumberOfCopies", int.class) != null, "Method setNumberOfCopies is not declared in VideoGame class.");
- assertTrue(VideoGameRunner.VideoGame.class.getDeclaredMethod("getNumberOfCopies") != null, "Method getNumberOfCopies is not declared in VideoGame class.");
- assertTrue(VideoGameRunner.VideoGame.class.getDeclaredMethod("increaseCopies", int.class) != null, "Method increaseCopies is not declared in VideoGame class.");
- assertTrue(VideoGameRunner.VideoGame.class.getDeclaredMethod("decreaseCopies", int.class) != null, "Method decreaseCopies is not declared in VideoGame class.");
-
- assertTrue(VideoGameRunner.VideoGame.class.getDeclaredField("title") != null, "Field title is not declared in VideoGame class.");
- assertTrue(VideoGameRunner.VideoGame.class.getDeclaredField("numberOfCopies") != null, "Field numberOfCopies is not declared in VideoGame class.");
- } catch (NoSuchMethodException | NoSuchFieldException e) {
- LOGGER.severe("Error: " + e.getMessage());
- }
- }
-
- @Test
- public void testMainMethod() {
- helper.resetStdOut(); // clean stdout
- VideoGameRunner.main(new String[] {});
- String actualOutput = helper.getOutput().trim(); // remove leading/trailing whitespaces
- String[] lines = actualOutput.split("\n"); // split by line
-
- // check each line to match expected format
- assertEquals("Red Dead Redemption 2 - Number of copies: 5", lines[0]);
- assertEquals("The Witcher 3 - Number of copies: 8", lines[1]);
- assertEquals("Breath of the Wild - Number of copies: 10", lines[2]);
- assertTrue(lines[3].startsWith("Red Dead Redemption 2 - Number of copies after increasing copies : "));
- assertTrue(lines[4].startsWith("The Witcher 3 - Number of copies after increasing copies : "));
- assertTrue(lines[5].startsWith("Breath of the Wild - Number of copies after increasing copies : "));
- assertTrue(lines[6].startsWith("Red Dead Redemption 2 - Number of copies after decreasing copies : "));
- assertTrue(lines[7].startsWith("The Witcher 3 - Number of copies after decreasing copies : "));
- assertTrue(lines[8].startsWith("Breath of the Wild - Number of copies after decreasing copies : "));
- }
-
-
- @Test
- public void testRdr2Output() {
- helper.resetStdOut(); // clean stdout
- VideoGameRunner.main(new String[] {});
- String actualOutput = helper.getOutput();
- assertTrue(actualOutput.contains("Red Dead Redemption 2 - Number of copies: 5"), "Output does not contain expected string: Red Dead Redemption 2 - Number of copies: 5");
- }
-
- @Test
- public void testTw3Output() {
- helper.resetStdOut(); // clean stdout
- VideoGameRunner.main(new String[] {});
- String actualOutput = helper.getOutput();
- assertTrue(actualOutput.contains("The Witcher 3 - Number of copies: 8"), "Output does not contain expected string: The Witcher 3 - Number of copies: 8");
- }
-
- @Test
- public void testBotwOutput() {
- helper.resetStdOut(); // clean stdout
- VideoGameRunner.main(new String[] {});
- String actualOutput = helper.getOutput();
- assertTrue(actualOutput.contains("Breath of the Wild - Number of copies: 10"), "Output does not contain expected string: Breath of the Wild - Number of copies: 10");
- }
-
- @Test
- public void testIncreaseCopies() {
- VideoGameRunner.VideoGame game = new VideoGameRunner.VideoGame();
- game.setNumberOfCopies(10);
- game.increaseCopies(5);
- assertEquals(15, game.getNumberOfCopies(), "Number of copies did not increase by the expected amount.");
- }
-
- @Test
- public void testDecreaseCopies() {
- VideoGameRunner.VideoGame game = new VideoGameRunner.VideoGame();
- game.setNumberOfCopies(10);
- game.decreaseCopies(5);
- assertEquals(5, game.getNumberOfCopies(), "Number of copies did not decrease by the expected amount.");
- }
-
- @Test
- public void testIncreaseCopiesOutput() {
- helper.resetStdOut(); // clean stdout
- VideoGameRunner.main(new String[] {});
- String actualOutput = helper.getOutput();
- assertTrue(actualOutput.contains("Red Dead Redemption 2 - Number of copies after increasing copies : 17"), "Output does not contain expected string: Red Dead Redemption 2 - Number of copies after increasing copies : 17");
- assertTrue(actualOutput.contains("The Witcher 3 - Number of copies after increasing copies : 26"), "Output does not contain expected string: The Witcher 3 - Number of copies after increasing copies : 26");
- assertTrue(actualOutput.contains("Breath of the Wild - Number of copies after increasing copies : 34"), "Output does not contain expected string: Breath of the Wild - Number of copies after increasing copies : 34");
- }
-
- @Test
- public void testDecreaseCopiesOutput() {
- helper.resetStdOut(); // clean stdout
- VideoGameRunner.main(new String[] {});
- String actualOutput = helper.getOutput();
- assertTrue(actualOutput.contains("Red Dead Redemption 2 - Number of copies after decreasing copies : 11"), "Output does not contain expected string: Red Dead Redemption 2 - Number of copies after decreasing copies : 11");
- assertTrue(actualOutput.contains("The Witcher 3 - Number of copies after decreasing copies : 14"), "Output does not contain expected string: The Witcher 3 - Number of copies after decreasing copies : 14");
- assertTrue(actualOutput.contains("Breath of the Wild - Number of copies after decreasing copies : 16"), "Output does not contain expected string: Breath of the Wild - Number of copies after decreasing copies : 16");
- }
-}
-```
\ No newline at end of file
diff --git a/Archive/05-IntroductionToObjectOrientedProgrammin.md b/Archive/05-IntroductionToObjectOrientedProgrammin.md
new file mode 100644
index 00000000..a2f9495e
--- /dev/null
+++ b/Archive/05-IntroductionToObjectOrientedProgrammin.md
@@ -0,0 +1,720 @@
+## Exercise 1: Implementing Encapsulation Techniques in the VideoGame Class
+
+
+
+### Instructions
+
+#### Task 1: Implement VideoGame class attributes
+
+1. In the given `VideoGameRunner` class, add the following attributes to the `VideoGame` class:
+ - `title` of type `String`
+ - `numberOfCopies` of type `int`
+
+#### Task 2: Implement methods for VideoGame class
+
+1. Implement the following methods for the `VideoGame` class:
+ - `setTitle(String gameTitle)`: Sets the title of the video game.
+ - `getTitle()`: Returns the title of the video game.
+ - `setNumberOfCopies(int numberOfCopies)`: Sets the number of copies if the provided number is greater than or equal to 0.
+ - `getNumberOfCopies()`: Returns the number of copies.
+ - `increaseCopies(int howMuch)`: Increases the number of copies by the given amount.
+ - `decreaseCopies(int howMuch)`: Decreases the number of copies by the given amount but ensures that the number of copies does not go below 0.
+
+
+#### Task 3: Test the VideoGame class in the main method
+
+1. In the `main` method of the `VideoGameRunner` class, create three instances of the `VideoGame` class and set their titles as follows:
+
+ - Create an instance named `rdr2` and set its title to "Red Dead Redemption 2".
+ - Create an instance named `tw3` and set its title to "The Witcher 3".
+ - Create an instance named `botw` and set its title to "Breath of the Wild".
+2. Print the titles of the three video game instances (`rdr2`, `tw3`, and `botw`).
+
+3. Increase the number of copies for each video game instance as follows:
+
+ - Increase the number of copies for `rdr2` by 12.
+ - Increase the number of copies for `tw3` by 18.
+ - Increase the number of copies for `botw` by 24.
+4. Decrease the number of copies for each video game instance as follows:
+
+ - Decrease the number of copies for `rdr2` by 6.
+ - Decrease the number of copies for `tw3` by 12.
+ - Decrease the number of copies for `botw` by 18.
+5. Print the number of copies for each video game instance (`rdr2`, `tw3`, and `botw`).
+
+
+
+### Hints
+
+#### Task 1: Implement VideoGame class attributes
+
+**Hint 1:** To add attributes to a class, declare them within the class using the appropriate data type.
+
+**Hint 2:** You need to add two attributes: a `String` for the `title` and an `int` for the `numberOfCopies`.
+
+#### Task 2: Implement methods for VideoGame class
+
+**Hint 1:** To create a method, use the following syntax: `access_modifier return_type methodName(parameters) { /* method body */ }`.
+
+**Hint 2:** For example, the `setTitle` method should have a `void` return type and a single `String` parameter.
+
+**Hint 3:** To set the number of copies only if the provided number is greater than or equal to 0, use an `if` statement in the `setNumberOfCopies` method.
+
+**Hint 4:** The `increaseCopies` and `decreaseCopies` methods should use the `setNumberOfCopies` method to update the `numberOfCopies` attribute.
+
+#### Task 3: Test the VideoGame class in the main method
+
+**Hint 1:** To create an instance of a class, use the `new` keyword followed by the class name and parentheses.
+
+**Hint 2:** To call a method on an instance of a class, use the dot (.) operator followed by the method name and its arguments.
+
+**Hint 3:** Use `System.out.println()` to print the titles and number of copies for each video game instance.
+
+
+### Solution Explanation
+
+
+The given problem code is incomplete and needs to be modified to include the necessary attributes and methods in the `VideoGame` class. Below is the step-by-step explanation of the solution code.
+
+#### Task 1: Implement VideoGame class attributes
+
+We start by adding the required attributes `title` and `numberOfCopies` to the `VideoGame` class.
+
+```
+private String title;
+private int numberOfCopies;
+```
+
+#### Task 2: Implement methods for VideoGame class
+
+Next, we implement the required methods for the `VideoGame` class.
+
+1. Set and get methods for `title` attribute:
+
+```
+public void setTitle(String gameTitle) {
+ title = gameTitle;
+}
+
+public String getTitle() {
+ return title;
+}
+```
+
+2. Set and get methods for `numberOfCopies` attribute with a condition to ensure the number of copies is non-negative:
+
+```
+public void setNumberOfCopies(int numberOfCopies) {
+ if (numberOfCopies >= 0) {
+ this.numberOfCopies = numberOfCopies;
+ }
+}
+
+public int getNumberOfCopies() {
+ return numberOfCopies;
+}
+```
+
+3. Methods to increase and decrease the number of copies:
+
+```
+public void increaseCopies(int howMuch) {
+ setNumberOfCopies(numberOfCopies + howMuch);
+}
+
+public void decreaseCopies(int howMuch) {
+ setNumberOfCopies(numberOfCopies - howMuch);
+}
+```
+
+#### Task 3: Test the VideoGame class in the main method
+
+Finally, we test the `VideoGame` class in the `main` method by creating instances, setting titles, increasing and decreasing the number of copies, and printing their titles and number of copies.
+
+```
+public static void main(String[] args) {
+ VideoGame rdr2 = new VideoGame();
+ rdr2.setTitle("Red Dead Redemption 2");
+ VideoGame tw3 = new VideoGame();
+ tw3.setTitle("The Witcher 3");
+ VideoGame botw = new VideoGame();
+ botw.setTitle("Breath of the Wild");
+
+ System.out.println(rdr2.getTitle());
+ System.out.println(tw3.getTitle());
+ System.out.println(botw.getTitle());
+
+ rdr2.increaseCopies(12);
+ tw3.increaseCopies(18);
+ botw.increaseCopies(24);
+ rdr2.decreaseCopies(6);
+ tw3.decreaseCopies(12);
+ botw.decreaseCopies(18);
+
+ System.out.println(rdr2.getNumberOfCopies());
+ System.out.println(tw3.getNumberOfCopies());
+ System.out.println(botw.getNumberOfCopies());
+}
+```
+
+This solution code demonstrates the proper implementation of encapsulation techniques and completes the `VideoGame` class as required by the problem statement.
+
+### Student File
+
+**VideoGameRunner.java**
+
+```
+
+public class VideoGameRunner {
+
+ static class VideoGame {
+ // Complete the code
+ }
+
+ public static void main(String[] args) {
+ // VideoGame rdr2 = new VideoGame();
+ // rdr2.setTitle("Red Dead Redemption 2");
+ // Complete the code
+ }
+}
+
+```
+
+
+
+
+### Solution File
+
+**VideoGameRunner.java**
+
+```
+public class VideoGameRunner {
+
+ static class VideoGame {
+ private String title;
+ private int numberOfCopies;
+
+ public void setTitle(String gameTitle) {
+ title = gameTitle;
+ }
+
+ public String getTitle() {
+ return title;
+ }
+
+ public void setNumberOfCopies(int numberOfCopies) {
+ if (numberOfCopies >= 0) {
+ this.numberOfCopies = numberOfCopies;
+ }
+ }
+
+ public int getNumberOfCopies() {
+ return numberOfCopies;
+ }
+
+ public void increaseCopies(int howMuch) {
+ setNumberOfCopies(numberOfCopies + howMuch);
+ }
+
+ public void decreaseCopies(int howMuch) {
+ setNumberOfCopies(numberOfCopies - howMuch);
+ }
+ }
+
+ public static void main(String[] args) {
+ VideoGame rdr2 = new VideoGame();
+ rdr2.setTitle("Red Dead Redemption 2");
+ VideoGame tw3 = new VideoGame();
+ tw3.setTitle("The Witcher 3");
+ VideoGame botw = new VideoGame();
+ botw.setTitle("Breath of the Wild");
+
+ System.out.println(rdr2.getTitle());
+ System.out.println(tw3.getTitle());
+ System.out.println(botw.getTitle());
+
+ rdr2.increaseCopies(12);
+ tw3.increaseCopies(18);
+ botw.increaseCopies(24);
+ rdr2.decreaseCopies(6);
+ tw3.decreaseCopies(12);
+ botw.decreaseCopies(18);
+
+ System.out.println(rdr2.getNumberOfCopies());
+ System.out.println(tw3.getNumberOfCopies());
+ System.out.println(botw.getNumberOfCopies());
+ }
+}
+
+```
+
+
+### Evaluation File
+
+**Evaluate.java**
+
+```
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.util.logging.Logger;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+public class Evaluate {
+
+ private VideoGameRunner.VideoGame videoGame;
+ private static final Logger LOGGER = Logger.getLogger(Evaluate.class.getName());
+
+ @BeforeEach
+ public void setUp() {
+ LOGGER.info("Setting up a new VideoGame instance for the tests...");
+ videoGame = new VideoGameRunner.VideoGame();
+ }
+
+ @Test
+ public void testSetTitleAndGetTitle() {
+ LOGGER.info("Running testSetTitleAndGetTitle...");
+ String testTitle = "Test Game";
+ LOGGER.info("Setting title to: " + testTitle);
+ videoGame.setTitle(testTitle);
+ LOGGER.info("Getting the title and checking if it matches the expected value...");
+ assertEquals(testTitle, videoGame.getTitle());
+ LOGGER.info("testSetTitleAndGetTitle passed.");
+ }
+
+ @Test
+ public void testSetNumberOfCopiesAndGetNumberOfCopies() {
+ LOGGER.info("Running testSetNumberOfCopiesAndGetNumberOfCopies...");
+ int testCopies = 10;
+ LOGGER.info("Setting number of copies to: " + testCopies);
+ videoGame.setNumberOfCopies(testCopies);
+ LOGGER.info("Getting the number of copies and checking if it matches the expected value...");
+ assertEquals(testCopies, videoGame.getNumberOfCopies());
+ LOGGER.info("testSetNumberOfCopiesAndGetNumberOfCopies passed.");
+ }
+
+ @Test
+ public void testIncreaseCopies() {
+ LOGGER.info("Running testIncreaseCopies...");
+ int initialCopies = 5;
+ int increaseCopiesBy = 5;
+ LOGGER.info("Setting initial number of copies to: " + initialCopies);
+ videoGame.setNumberOfCopies(initialCopies);
+ LOGGER.info("Increasing number of copies by: " + increaseCopiesBy);
+ videoGame.increaseCopies(increaseCopiesBy);
+ LOGGER.info("Getting the number of copies and checking if it matches the expected value...");
+ assertEquals(initialCopies + increaseCopiesBy, videoGame.getNumberOfCopies());
+ LOGGER.info("testIncreaseCopies passed.");
+ }
+
+ @Test
+ public void testDecreaseCopies() {
+ LOGGER.info("Running testDecreaseCopies...");
+ int initialCopies = 10;
+ int decreaseCopiesBy = 5;
+ LOGGER.info("Setting initial number of copies to: " + initialCopies);
+ videoGame.setNumberOfCopies(initialCopies);
+ LOGGER.info("Decreasing number of copies by: " + decreaseCopiesBy);
+ videoGame.decreaseCopies(decreaseCopiesBy);
+ LOGGER.info("Getting the number of copies and checking if it matches the expected value...");
+ assertEquals(initialCopies - decreaseCopiesBy, videoGame.getNumberOfCopies());
+ LOGGER.info("testDecreaseCopies passed.");
+ }
+}
+
+```
+
+
+
+
+
+
+## Exercise 2: Implementing Vehicle Engine Control and Speed Tracking
+
+
+
+### Instructions
+
+
+#### Objective
+
+In this exercise, you are asked to complete the implementation of a simple `Vehicle` class and a `VehicleRunner` class that demonstrates its usage.
+
+#### Instructions
+
+1. Complete the implementation of the `Vehicle` class inside the `VehicleRunner` class. The `Vehicle` class should have the following properties:
+
+ - `speed`: An integer representing the speed of the vehicle.
+ - `type`: A string representing the type of the vehicle, e.g., "Car", "Truck", "Bike".
+2. Implement two constructors for the `Vehicle` class:
+
+ - A constructor that takes two parameters: `speed` and `type`. The `speed` should be set only if the value is greater than 0. Otherwise, the default speed should be 10. The `type` should always be set.
+ - A default constructor that sets the `speed` to 10 and the `type` to "Bike".
+3. Implement the following methods for the `Vehicle` class:
+
+ - `startEngine()`: This method should print "Engine started!".
+ - `stopEngine()`: This method should print "Engine stopped!" and set the `speed` to 0.
+ - `getSpeed()`: This method should return the current `speed` of the vehicle.
+ - `getType()`: This method should return the current `type` of the vehicle.
+4. In the `main()` method of the `VehicleRunner` class, create three `Vehicle` instances with different speed and type values:
+
+ - `car`: Speed 30, Type "Car".
+ - `truck`: Speed 20, Type "Truck".
+ - `bike`: Default constructor.
+5. Start the engine of all three vehicles and print their initial speed and type.
+
+6. Stop the engine of all three vehicles and print their final speed.
+
+
+#### Example
+
+Below is an example of the incomplete code provided to the student:
+
+```
+public class VehicleRunner {
+ public static class Vehicle {
+ // Write your code
+ }
+
+ public static void main(String[] args) {
+ // Vehicle car = new Vehicle(30, "Car");
+ // Write your code
+ }
+}
+```
+
+After completing the exercise, the output should look like this:
+```
+Engine started!
+Engine started!
+Engine started!
+Earlier Car Speed is : 30, Type: Car
+Earlier Truck Speed is : 20, Type: Truck
+Earlier Bike Speed is : 10, Type: Bike
+Engine stopped!
+Engine stopped!
+Engine stopped!
+Stopped Car Speed is : 0
+Stopped Truck Speed is : 0
+Stopped Bike Speed is : 0
+```
+
+
+### Hints
+
+
+Here are some hints for completing the given incomplete exercise code:
+
+1. Inside the `Vehicle` class, you need to declare two instance variables:
+
+ - `speed` of type `int`
+ - `type` of type `String`
+2. Create a constructor for the `Vehicle` class that takes two parameters:
+
+ - `int speed`
+ - `String type` Inside the constructor, initialize the instance variables with the given parameters.
+3. Create a default constructor for the `Vehicle` class. In this constructor, set default values for the instance variables:
+
+ - Set `speed` to `10`
+ - Set `type` to `"Bike"`
+4. Add a method `startEngine()` to the `Vehicle` class that prints "Engine started!" when called.
+
+5. Add a method `stopEngine()` to the `Vehicle` class that prints "Engine stopped!" when called and sets the `speed` of the vehicle to `0`.
+
+6. Create getter methods for the `speed` and `type` instance variables in the `Vehicle` class:
+
+ - `public int getSpeed()`
+ - `public String getType()`
+7. In the `main` method of the `VehicleRunner` class, create three instances of the `Vehicle` class:
+
+ - `Vehicle car = new Vehicle(30, "Car");`
+ - `Vehicle truck = new Vehicle(20, "Truck");`
+ - `Vehicle bike = new Vehicle();`
+8. Start the engine of each vehicle by calling the `startEngine()` method on each instance.
+
+9. Print the initial speed and type of each vehicle by calling the `getSpeed()` and `getType()` methods.
+
+10. Stop the engine of each vehicle by calling the `stopEngine()` method on each instance.
+
+11. Print the final speed of each vehicle after stopping the engine by calling the `getSpeed()` method.
+
+
+### Solution Explanation
+
+
+
+In this exercise, we're asked to complete the given incomplete `VehicleRunner` class by implementing the `Vehicle` class, its methods, and then creating instances of the `Vehicle` class in the `main` method. Here's the step-by-step explanation of the solution:
+
+### Implementing the Vehicle class
+
+1. First, we declare two instance variables for the `Vehicle` class:
+ - `speed` of type `int`
+ - `type` of type `String`
+
+```
+private int speed;
+private String type;
+```
+
+2. Next, we create a constructor for the `Vehicle` class that takes two parameters:
+ - `int speed`
+ - `String type` Inside the constructor, we initialize the instance variables with the given parameters.
+
+```
+public Vehicle(int speed, String type) {
+ if (speed > 0) {
+ this.speed = speed;
+ }
+ this.type = type;
+}
+```
+
+3. We then create a default constructor for the `Vehicle` class. In this constructor, we set default values for the instance variables:
+ - Set `speed` to `10`
+ - Set `type` to `"Bike"`
+
+```
+public Vehicle() {
+ this.speed = 10;
+ this.type = "Bike";
+}
+```
+
+4. We add a method `startEngine()` to the `Vehicle` class that prints "Engine started!" when called.
+
+```
+public void startEngine() {
+ System.out.println("Engine started!");
+}
+```
+
+5. We add another method `stopEngine()` to the `Vehicle` class that prints "Engine stopped!" when called and sets the `speed` of the vehicle to `0`.
+
+```
+public void stopEngine() {
+ System.out.println("Engine stopped!");
+ this.speed = 0;
+}
+```
+
+6. We create getter methods for the `speed` and `type` instance variables in the `Vehicle` class:
+ - `public int getSpeed()`
+ - `public String getType()`
+
+```
+public int getSpeed() {
+ return speed;
+}
+
+public String getType() {
+ return type;
+}
+```
+
+### Creating instances and calling methods in the main method
+
+7. In the `main` method of the `VehicleRunner` class, we create three instances of the `Vehicle` class:
+
+```
+Vehicle car = new Vehicle(30, "Car");
+Vehicle truck = new Vehicle(20, "Truck");
+Vehicle bike = new Vehicle();
+```
+
+8. We start the engine of each vehicle by calling the `startEngine()` method on each instance:
+
+```
+car.startEngine();
+truck.startEngine();
+bike.startEngine();
+```
+
+9. We print the initial speed and type of each vehicle by calling the `getSpeed()` and `getType()` methods:
+
+```
+System.out.println("Earlier Car Speed is : " + car.getSpeed() + ", Type: " + car.getType());
+System.out.println("Earlier Truck Speed is : " + truck.getSpeed() + ", Type: " + truck.getType());
+System.out.println("Earlier Bike Speed is : " + bike.getSpeed() + ", Type: " + bike.getType());
+```
+
+10. We stop the engine of each vehicle by calling the `stopEngine()` method on each instance:
+
+```
+car.stopEngine();
+truck.stopEngine();
+bike.stopEngine();
+```
+
+11. Finally, we print the final speed of each vehicle after stopping the engine by calling the `getSpeed()` method:
+
+```
+System.out.println("Stopped Car Speed is : " + car.getSpeed());
+System.out.println("Stopped Truck Speed is : " + truck.getSpeed());
+System.out.println("Stopped Bike Speed is : " + bike.getSpeed());
+```
+
+With this, we have successfully completed the implementation of the `VehicleRunner` class and its inner `Vehicle` class.
+
+### Student File
+
+**VehicleRunner.java**
+
+```
+
+public class VehicleRunner {
+ public static class Vehicle {
+ // Write your code
+ }
+
+ public static void main(String[] args) {
+ // Vehicle car = new Vehicle(30, "Car");
+ // Write your code
+ }
+
+
+}
+```
+
+
+
+
+### Solution File
+
+**VehicleRunner.java**
+
+```
+public class VehicleRunner {
+ public static class Vehicle {
+ private int speed;
+ private String type;
+
+ public Vehicle(int speed, String type) {
+ if (speed > 0) {
+ this.speed = speed;
+ }
+ this.type = type;
+ }
+
+ public Vehicle() {
+ this.speed = 10;
+ this.type = "Bike";
+ }
+
+ public void startEngine() {
+ System.out.println("Engine started!");
+ }
+
+ public void stopEngine() {
+ System.out.println("Engine stopped!");
+ this.speed = 0;
+ }
+
+ public int getSpeed() {
+ return speed;
+ }
+
+ public String getType() {
+ return type;
+ }
+ }
+
+ public static void main(String[] args) {
+ Vehicle car = new Vehicle(30, "Car");
+ Vehicle truck = new Vehicle(20, "Truck");
+ Vehicle bike = new Vehicle();
+
+ car.startEngine();
+ truck.startEngine();
+ bike.startEngine();
+
+ System.out.println("Earlier Car Speed is : " + car.getSpeed() + ", Type: " + car.getType());
+ System.out.println("Earlier Truck Speed is : " + truck.getSpeed() + ", Type: " + truck.getType());
+ System.out.println("Earlier Bike Speed is : " + bike.getSpeed() + ", Type: " + bike.getType());
+
+ car.stopEngine();
+ truck.stopEngine();
+ bike.stopEngine();
+
+ System.out.println("Stopped Car Speed is : " + car.getSpeed());
+ System.out.println("Stopped Truck Speed is : " + truck.getSpeed());
+ System.out.println("Stopped Bike Speed is : " + bike.getSpeed());
+ }
+
+
+}
+
+```
+
+
+### Evaluation File
+
+**Evaluate.java**
+
+```
+
+import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.*;
+
+public class Evaluate {
+ @Test
+ public void testStartEngine() {
+ VehicleRunner.Vehicle car = new VehicleRunner.Vehicle(30, "Car");
+ VehicleRunner.Vehicle truck = new VehicleRunner.Vehicle(20, "Truck");
+ VehicleRunner.Vehicle bike = new VehicleRunner.Vehicle();
+
+ car.startEngine();
+ truck.startEngine();
+ bike.startEngine();
+
+ System.out.println("Car Speed after starting engine: " + car.getSpeed());
+ System.out.println("Truck Speed after starting engine: " + truck.getSpeed());
+ System.out.println("Bike Speed after starting engine: " + bike.getSpeed());
+
+ assertEquals(30, car.getSpeed());
+ assertEquals(20, truck.getSpeed());
+ assertEquals(10, bike.getSpeed());
+ }
+
+ @Test
+ public void testStopEngine() {
+ VehicleRunner.Vehicle car = new VehicleRunner.Vehicle(30, "Car");
+ VehicleRunner.Vehicle truck = new VehicleRunner.Vehicle(20, "Truck");
+ VehicleRunner.Vehicle bike = new VehicleRunner.Vehicle();
+
+ car.startEngine();
+ truck.startEngine();
+ bike.startEngine();
+
+ car.stopEngine();
+ truck.stopEngine();
+ bike.stopEngine();
+
+ System.out.println("Car Speed after stopping engine: " + car.getSpeed());
+ System.out.println("Truck Speed after stopping engine: " + truck.getSpeed());
+ System.out.println("Bike Speed after stopping engine: " + bike.getSpeed());
+
+ assertEquals(0, car.getSpeed());
+ assertEquals(0, truck.getSpeed());
+ assertEquals(0, bike.getSpeed());
+ }
+
+ @Test
+ public void testGetType() {
+ VehicleRunner.Vehicle car = new VehicleRunner.Vehicle(30, "Car");
+ VehicleRunner.Vehicle truck = new VehicleRunner.Vehicle(20, "Truck");
+ VehicleRunner.Vehicle bike = new VehicleRunner.Vehicle();
+
+ System.out.println("Car type: " + car.getType());
+ System.out.println("Truck type: " + truck.getType());
+ System.out.println("Bike type: " + bike.getType());
+
+ assertEquals("Car", car.getType());
+ assertEquals("Truck", truck.getType());
+ assertEquals("Bike", bike.getType());
+ }
+}
+
+
+```
\ No newline at end of file
diff --git a/txt_help.md b/txt_help.md
index 7a7d5687..e69de29b 100644
--- a/txt_help.md
+++ b/txt_help.md
@@ -1,1199 +0,0 @@
-## Primitive Data Types
-
-Earlier, we looked at basic Java types (including ```int```, ```double``` and ```boolean```), and got a little familiar with them.
-
-We used literal values, declared variables and formed expressions using them.
-
-Java **primitive types** include:
-* Integer Types
- * ```byte```
- * ```short```
- * ```int```
- * ```long```
-* Floating-Point Types
- * ```float```
- * ```double```
-* Character Type
- * ```char```
-* Logical Type
- * ```boolean```
-
-In this section, let's play with each of these types to understand them further.
-
-### Step 01: The Integer Types
-
-Integers are not much of a mystery, are they? They've been part of us since our school days, and we normally prefer them over other numbers (they scare us less!).
-
-Java supports them with ease, and we have coded quite a few examples using them, already.
-
-Java also has a **wrapper class** corresponding to each of them, which make their primitive versions more versatile. The wrapper classes we are talking about are:
-
-* ```Byte```: for ```byte```
-* ```Short```: matching ```short```
-* ```Integer``` corresponding to ```int```
-* ```Long```: about ```long```
-
-Let's see how we can work with them.
-
-##### Snippet-01 : Integer Sizes
-
-Look at all the information these tiny classes hold for you! As they say, **_"fore-warned is fore-armed"_**. Depending on the data (range and size) your program handles, you decide which types to use, to store them.
-
-```java
-
- jshell> Byte.SIZE
- $1 ==> 8
- jshell> Byte.BYTES
- $2 ==> 1
- jshell> Byte.MAX_VALUE
- $3 ==> 127
- jshell> Byte.MIN_VALUE
- $4 ==> -128
- jshell> Short.BYTES
- $5 ==> 2
- jshell> Integer.BYTES
- $6 ==> 4
- jshell> Long.BYTES
- $7 ==> 8
- jshell> Short.MAX_VALUE
- $8 ==> 32767
- jshell> Integer.MAX_VALUE
- $8 ==> 2147483647
- jshell> int i = 100000;
- i ==> 100000
- jshell> long l = 50000000000;
- | Error:
- | integer number too large: 50000000000
- | long l = 50000000000;
- |_________^
- jshell> long l = 50000000000l;
- l ==> 50000000000
- jshell>
-
-```
-
-#### Integer Type Conversions
-
-Problems will (and should) arise if we attempt to store large data into smaller bins. The compiler warns the programmer about such issues by flagging errors. However, if the programmer is aware of the risks and intends to go ahead, **explicit casts** are her tools to push the code through.
-
-Operations in the other direction (storing a smaller data value in a larger bin), is a piece of cake for the compiler. Such a conversion is called an **implicit cast**.
-
-##### Snippet-02 : Integer Type Conversions
-
-Attempting to store a ```long``` value into an ```int``` variable will give us a compiler error. However, you can use an explicit cast, such as ```i = (int) l;```.
-
-```java
-
- jshell> int i = 100000;
- i ==> 100000
- jshell> long l = 50000000000l;
- l ==> 50000000000
- jshell> i = l;
- | Error :
- | incompatible types: possible lossy conversion from long to int
- | i = l;
- |_____^
- jshell> i = (int) l;
- i ==> -1539607552
- jshell> l = i;
- l ==> -1539607552
- jshell>
-
-```
-
-**_The compiler is not responsible for the type-safety of this statement. The onus is on me, the programmer._**
-
-Remember our earlier statement on possible incorrect program behavior? As you can see, a different value got stored in ```i```.
-
-#### Summary
-
-In this step, we:
-
-* Explored the wrapper classes present for the primitive integer types
-* Understood the different capacities and data ranges of these types
-* Examined how to use explicit and implicit casts
-
-### Step 02: Integer Representations, And Other Puzzles
-
-In a decimal system, the allowed digits are ```0``` through ```9```. When a value of ```10``` is encountered, the number of digits increases by 1, and its representation is "```10```".
-
-Those familiar with number systems would know that decimal is not the only system that computers understand.
-
-Other number systems that the Java language supports are **Octal** (Base-8) and **Hexadecimal** (Base-16).
-
-In an Octal system, the allowed digits are ```0``` through ```7```, and a value ```8``` is represented by "```010```". The leading ```0``` is added only to distinguish the octal format from the decimal one.
-
-In a Hexadecimal system, the allowed digits are ```0``` through ```9```, followed by ```a``` through ```f``` (or ```A``` through ```F```). A value of ```16``` is represented by "```0x10```". Here, a leading ```0x``` is added to help the compiler recognize Hexa decimal representation.
-
-Let's see how Java supports these three number systems.
-
-##### Snippet-01 : Storing Octal and Hexadecimal in Integer types
-
-There are no number-system specific integer types in Java! The same ```int``` type is used to store decimal, octal and hexadecimal values.
-
-If we adhere to to number system conventions about valid digits and understand the compiler hints, we get no surprises.
-
-```java
-
- jshell> int eight = 010;
- eight ==> 8
- jshell> int sixteen = 0x10;
- sixteen ==> 16
- jshell> int fifteen = 0xf;
- fifteen ==> 15
- jshell> int eight = 08;//8 is invalid octal digit
- | Error:
- | integer number too large : 08
- | int eight = 08;
- |___________^
- jshell> int big = 0xbbaacc;
- big ==> 12298956
- jshell>
-
-```
-
-##### Snippet-02 : More Integer Type-casting
-
-There are two kinds of assignments:
-* Literal-to-variable assignment: With ```short s = 123456;```, the data is clearly out of range (this is known at compile-time). The compiler flags an error.
-* Variable-to-variable assignment: Consider ```sh = in;```. The value stored in ```int in``` at that stage was ```4567```, which is well within the range of the ```short``` type. The compiler chooses not to take chances and flags an error. This can again be preempted with a explicit cast `sh = (short) in`.
-
-
-```java
-
- jshell> byte b = 128;
- | Error:
- | incompatible types: possible lossy conversion from int to byte
- | byte b = 128;
- |_________^--^
- jshell> short s = 123456;
- | Error:
- | incompatible types: possible lossy conversion from int to short
- | short s = 123456;
- |__________^-------^
- jshell> short sh = 3456;
- sh ==> 3456
- jshell> int in = 4567;
- in ==> 3456
- jshell> sh = in;
- | Error:
- | incompatible types: possible lossy conversion from int to short
- | sh = in;
- |______^
- jshell> sh = (short) in;
- sh ==> 4567
- jshell> int num = sh;
- num ==> 4567
- jshell>
-
-```
-
-#### Built-In Operators For Integer Types
-
-We already had a glimpse of arithmetic operators for the integer types:
-* ```+```
-* ```-```
-* ```*```
-* ```/```
-* ```%```
-* ```++``` (both prefix and post-fix increment)
-* ```--``` (both prefix and post-fix increment)
-
-The increment and decrement operators are an interesting case, as they are actually short-hands for multiple statements. When we use their prefix and post-fix versions, we need to look out for side-effects.
-
-##### Snippet-03 : Increment & Decrement Operators
-
-With post-fix increment, such as in ```int j = i++;```, the increment takes place *after* the assignment is done. ```j``` gets the value before increment.
-```java
-
- jshell> int i = 10;
- i ==> 10
- jshell> int j = i++;
- j ==> 10
- jshell> i
- i ==> 11
-```
-
-When prefix increment is involved, as with ```int n = ++m;```, the increment is carried out *before* the assignment. ```n``` gets the value after increment.
-
-```java
- jshell> int m = 10;
- m ==> 10
- jshell> int n = ++m;
- n ==> 11
- jshell> m
- m ==> 11
-```
-
-With post-fix decrement, as with ```int l = k--;```, the decrement occurs *after* the assignment is done. As far as prefix decrement is concerned, such as in ```int q = --p;```, the decrement is performed *before* the assignment.
-
-```java
- jshell> int k = 10;
- k ==> 10
- jshell> int l = k--;
- l ==> 10
- jshell> k
- k ==> 9
- jshell> int p = 10;
- p ==> 10
- jshell> int q = --p;
- q ==> 9
- jshell> p
- p ==> 9
- jshell>
-
-```
-
-#### Summary:
-
-In this step, we:
-
-* Looked at the number-systems supported in Java for integers
-* Examined how prefix and post-fix versions work for increment and decrement operators
-
-- - -
-### Step 03: Classroom Exercise CE-01 (With Solutions)
-
-#### Exercise Set
-
-1. Create a Java ```class``` ```BiNumber``` that stores a pair of integers, and has the following functionality:
-
- * Can be created by passing its initial two numbers to store
- * Must Support Addition and Multiplication operations on the stored integers
- * An operation to double the values of both numbers
- * Operations to access each number individually
-
-In short, we must be able to write code like this in the ```main``` method of our runner class:
-
-```java
-
- BiNumber numbers = new BiNumber(2, 3);
- System.out.println(numbers.add());
- System.out.println(numbers.multiply());
- numbers.double();
- System.out.println(numbers.getNumber1());
- System.out.println(numbers.getNumber2());
-
-```
-
-#### Solution to CE-01
-
-**_BiNumber.java_**
-
-```java
-
- package com.in28minutes.primitive.datatypes;
-
- public class BiNumber {
- private int number1;
- private int number2;
-
- public BiNumber(int number1, int number2) {
- this.number1 = number1;
- this.number2 = number2;
- }
-
- public int add() {
- return number1 + number2;
- }
-
- public int multiply() {
- return number1 * number2;
- }
-
- public void doubleValue() {
- number1 *= 2;
- number2 *= 2;
- }
-
- public int getNumber1() {`
- return number1;
- }
-
- public int getNumber2() {
- return number2;
- }
-
- public void setNumber1(int number1) {
- this.number1 = number1;
- }
-
- public void setNumber2(int number2) {
- this.number2 = number2;
- }
- }
-
-```
-
-**_BiNumberRunner.java_**
-
-```java
-
- package com.in28minutes.primitive.datatypes;
-
- public class BiNumberRunner {
- public static void main(String[] args) {
- BiNumber numbers = new BiNumber(2, 3);
- System.out.println(numbers.add());
- System.out.println(numbers.multiply());
- numbers.doubleValue();
- System.out.println(numbers.getNumber1());
- System.out.println(numbers.getNumber2());
- }
- }
-
-```
-
-**_Console Output_**
-
-_5_
-
-_6_
-
-_4_
-
-_6_
-
-### Step 05: Floating-Point Types
-
-You would recall there are two types in Java to support floating-point numbers:
-* ```double```: The default type for floating-point literals, with a capacity of 8 bytes
-* ```float```: A narrower, less precise representation for floating-point data. It has a capacity of 4 bytes.
-
-Let's quickly refresh what we know, with a few code snippets.
-
-##### Snippet-01 : double and float
-
-Default floating point type in Java is `double`. A ```float``` literal must be accompanied with a trailing ```f``` or ```F```.
-
-
-```java
-
- jshell> float f = 34.5;
- | Error:
- | incomaptible types: possible lossy conversion from double to float
- | float f = 34.5;
- |_________^---^
- jshell> float f = 34.5f;
- f ==> 34.5
- jshell> float fl = 34.5F;
- fl ==> 34.5
- jshell> double d = 34.5678;
- d ==> 34.5678
- jshell> float flo = d;
- | Error:
- | incomaptible types: possible lossy conversion from double to float
- | float flo = d;
- |__________^
- jshell> float flo = (float) d;
- flo ==> 34.567
- jshell>
-
-```
-
-##### Snippet-02 : Operators for type double
-
-You can use operators `++`, `--` and `%` on double.
-
-```java
-
-jshell> double dbl = 34.5678;
-dbl ==> 34.5678
-
-jshell> dbl++
-$3 ==> 34.5678
-
-jshell> dbl
-dbl ==> 35.5678
-
-jshell> dbl--
-dbl ==> 35.5678
-jshell> dbl % 5
-dbl ==> 4.567799999999998
-```
-
-You would need an explicit cast to convert a float to an integer value `int i = (int)f`.
-
-```java
- jshell> float f = 34.5678f;
- f ==> 34.5678
- jshell> int i = f;
- | Error:
- | incomaptible types: possible lossy conversion from float to int
- | int i = f;
- |_______^
- jshell> int i = (int)f;
- i ==> 34
- jshell> float fl = i;
- fl ==> 34.0
- jshell>
-
-```
-#### Summary
-
-In this step, we:
-
-* Saw how we create literals and variables of the floating-point types
-* Understood the differences between ```double``` and ```float```
-
-### Step 06: Introducing BigDecimal
-
-Compact though they are, ```double``` and ```float``` are not very precise representations of floating-point numbers.
-
-In fact, they are not used in computations that require high degrees for accuracy, such as scientific experiments and financial applications. The next example shows you why.
-
-
-```java
-
- jshell> 34.56789876 + 34.2234
- $1 ==> 68.79129875999999
-```
-
-The literal expression ```34.56789876 + 34.2234``` should evaluate to ```68.79129876```. Above addition is not really accurate.
-
-This is due to a flaw in floating-point representations, used in the ```double``` and ```float``` types.
-
-The ```BigDecimal``` class was introduced in Java to tide over these problems.
-
-Accuracy of ```BigDecimal``` representation is retained only when ```String``` literals are used to build it.
-
-
-
-```java
-
- jshell> BigDecimal number1 = new BigDecimal("34.56789876");
- number1 ==> 34.56789876
- jshell> BigDecimal number2 = new BigDecimal("34.2234");
- number2 ==> 34.2234_
-```
-
-A ```BigDecimal``` type can be used to create only **immutable** objects. The values in an *immutable* object cannot be changed after creation.
-
-You can see that the value of number1 is not changed on executing `number1.add(number2)`. To get the result of the sum, we create a new variable `sum`.
-
-```java
- jshell> number1.add(number2);
- $2 ==> 68.79129876
- jshell> number1
- number1 ==> 34.56789876
- jshell> BigDecimal sum = number1.add(number2);
- sum ==> 68.79129876
-```
-
-#### Summary
-
-In this step, we:
-
-* Learned that ```double``` and ```float``` are not very precise data types
-* Were introduced to the ```BigDecimal``` built-in data type
-* Understood that ```BigDecimal``` is immutable
-* Saw that accuracy is best achieved when you construct ```BigDecimal``` data using string literals
-
-### Step 06: BigDecimal Operations
-
-Let's look at a few other operations defined in the ```BigDecimal``` class.
-
-##### Snippet-01: Arithmetic Operations
-
-All BigDecimal operations support only BigDecimal operands.
-
-```java
-
- jshell> BigDecimal number1 = new BigDecimal("11.5");
- number1 ==> 34.56789876
- jshell> BigDecimal number2 = new BigDecimal("23.45678");
- number2 ==> 23.45678
- jshell> number1.add(number2);
- $1 ==> 34.95678
-```
-
-```BigDecimal``` does not jell well with primitive types.
-
-```java
- jshell> int i = 5;
- i ==> 5
- jshell> number1.add(i);
- | Error:
- | incompatible types: int cannot be converted to java.math.BigDecimal
- | number1.add(i);
- |_____________^
-```
-
-We can add, multiple, divide or subtract `BigDecimal` values.
-
-```java
- jshell> number1.add(new BigDecimal(i));
- $2 ==> 16.5
- jshell> number1.multiply(new BigDecimal(i));
- $3 ==> 67.5
- jshell> number1.divide(new BigDecimal(100));
- $4 ==> 0.115
- jshell>
-
-```
-
-#### Summary
-
-In this step, we:
-
-* Explored the ```BigDecimal``` methods for doing some basic arithmetic
-* Found that ```BigDecimal``` has constructors accepting most basic Java numeric types
-
-### Step 07: Classroom Exercise CE-02
-
-#### Exercise-Set
-
-Write a Program that does a Simple Interest computation for a Principal amount. Recall that the formula for such a calculation is:
-
-`Total amount (TA) = Principal Amount (PA) + ( PA * Simple Interest (SI) Rate * Duration In Years (N))`
-
-In essence, write a ```SimpleInterestCalculator``` ```class``` that can be used in the following manner:
-
-```java
-
- SimpleInterestCalculator calculator = new SimpleInterestCalculator("4500.00", "7.5");
- BigDecimal totalValue = calculator.calculateTotalValue(5); //5 year duration
- System.out.println(totalValue);
-
-```
-
-#### Solution To CE-02
-
-**_SimpleInterestCalculatorRunner.java_**
-
-```java
-
- package com.in28minutes.primitive.datatypes;
- import java.math.BigDecimal;
-
- public class SimpleInterestCalculatorRunner {
- public static void main(String[] args) {
- SimpleInterestCalculator calculator = new SimpleInterestCalculator("4500.00", 7.5");
- BigDecimal totalValue = calculator.calculateTotalValue(5); //5 year duration
- System.out.println(totalValue);
- }
- }
-
-```
-
-**_SimpleInterestCalculator.java_**
-
-```java
-
- package com.in28minutes.primitive.datatypes;
- import java.math.BigDecimal;
-
- public class SimpleInterestCalculatorRunner {
- BigDecimal principal;
- BigDecimal interest;
-
- public SimpleInterestCalculator(String principal, String interest) {
- this.principal = new BigDecimal(principal);
- this.interest = new BigDecimal(interest).divide(new BigDecimal(100));
- }
-
- public BigDecimal calculateTotalValue(int noOfYears)
- //Total Value = Principal + Principal * Interest* Years
- BigDecimal totalValue = prinipal.add(principal.multiply(interest).multiply(new BigDecimal(noOfYears)));
- return totalValue;`
- }
-}
-
-```
-
-**_Console Output:_**
-
-_6187.50000_
-
-#### Tip: The ```import``` Statement
-
-The Java ```import``` statement is Required in each source file that uses a ```class``` from another ```package```. Hence, both **_SimpleInterestCalculator.java_** (```class``` definition) and **_SimpleInterestCalculatorRunner.java_** (runner ```class``` definition) need to import ```class``` ```java.math.BigDecimal```.
-
-```package java.lang.*``` is imported by default.
-
-The ```.*``` suffix indicates that all classes in the ```package``` ```java.lang``` are being imported.
-
-#### Summary
-
-In this step, we:
-
-* Used ```BigDecimal``` values in a stand-alone Java program
-* Learnt how to make use of built-in Java packages, through the ```import``` statement
-
-### Step 08: ```boolean```, Relational and Logical Operators
-
-The Java ```boolean ``` data type is one that holds only one of two values: ```true``` or ```false```. Both labels are case-sensitive. We have seen examples of built-in comparison operators, such as ```==```, ```!=``` and ```>```, that evaluate expressions to give us ```boolean``` results. Let us do a quick recap of some of these.
-
-##### Snippet-01 : Relational Operators : Recap
-
-Relational Operators are used mainly for comparison. They accept operands of non-```boolean``` primitive data types, and return a ```boolean``` value.
-
-```java
-
- jshell> int i = 7;
- i ==> 7
- jshell> i > 7;
- $1 ==> false
- jshell> i >= 7;
- $2 ==> true
- jshell> i < 7;
- $3 ==> false
- jshell> i <= 7;
- $4 ==> true
- jshell> i == 7;
- $5 ==> true
- jshell> i == 8;
- $6 ==> false
- jshell>
-
-```
-
-#### Logical Operators
-
-Java also has logical operators that are used in expressions. Logical operators expect ```boolean``` operands. Expressions involving these are used for forming ```boolean``` conditions in code, including within ```if```, ```for``` and ```while``` statements. The prominent logical operators are:
-
-* ```&&``` : logical **AND**
-* ```||``` : **OR**
-* ```!``` : **NOT**
-
-Let's learn how we use them in our code.
-
-##### Snippet-02 : Logical Operators
-
-We would want to find if `i` is between `15` and `25`. An expression `i >= 15 && i <= 25` can be used. Details below.
-
-```java
-
- jshell> int i = 17;
- i ==> 17
- jshell> i >= 15
- $1 ==> true
- jshell> i <= 25
- $2 ==> true
- jshell> i >= 15 && i <= 25
- $3 ==> true
- jshell> i == 30;
- i ==> 30
- jshell> i >= 15 && i <= 25
- $4 ==> false
- jshell> i == 5;
- i ==> 30
- jshell> i >= 15 && i <= 25
- $5 ==> false
-```
-
-An expression with```&&``` evaluates to ```true``` only if **both** its ```boolean``` operands evaluate to ```true```.
-
-```java
- jshell> true && true
- $6 ==> true
- jshell> true && false
- $7 ==> false
- jshell> false && true
- $8 ==> false
- jshell> false && false
- $9 ==> false
- jshell>
-
-```
-
-##### Snippet-02 Explained
-
-The next example helps us visualize truth tables for the prominent logical operators.
-
-```java
-
- jshell> true || true
- $1 ==> true
- jshell> true || false
- $2 ==> true
- jshell> false || true
- $3 ==> true
- jshell> false || false
- $4 ==> false
- jshell> true ^ true
- $5 ==> false
- jshell> true ^ false
- $6 ==> true
- jshell> false ^ true
- $7 ==> true
- jshell> false ^ false
- $8 ==> false
- jshell> !true
- $9 ==> false
- jshell> !false
- $10 ==> true
- jshell> int x = 6;
- x ==> 6
- jshell> !(x > 7)
- $11 ==> true
- jshell>
-
-```
-
-#### Summary
-
-In this step, we:
-
-* We're introduced to the ```boolean``` primitive type
-* Understood where logical operators are used in Java programs
-* Explored the truth-tables of commonly used logical operators
-
-### Step 09: Short-Circuit Evaluation (With Puzzles)
-
-Consider code below. The expression ```j > 15 && i++ > 5``` evaluates to ```false``` as expected. `j>15` is `false` as `j` has a value of `15`.
-
-
-```java
-
- jshell> int j = 15;
- j ==> 15
- jshell> int i = 10;
- i ==> 10
- jshell> j > 15 && i++ > 5
- $1 ==> false
- jshell> j
- j ==> 15
- jshell> i
- i ==> 10
-```
-
-You can also observe that the value of i remains unchanged `10`.
-
-Why? Because ```i++ > 5``` was not even evaluated.
-Why? `&&` is lazy. It saw that `j > 15` is false. Irrespective of the result of second expression, the result of this `&&` would be false. So, it does NOT evaluate the second expression.
-
-***A more detailed explanation***
-
-The expression ```j > 15 && i++ > 5``` was scanned from left to right. As the first operand to ```&&``` evaluated to ```false```, the compiler got lazy. `&&` avoids evaluating expressions that don't affect the final result. The optimization has a name: **Short-Circuit Evaluation**, also called **lazy evaluation**.
-
-
-The logical operator ```&``` is another version of the logical **AND** operation, that does away with lazy evaluation.
-
-Both operands to ```&``` are always evaluated.
-
-```java
-
- jshell> j > 15 & i++ > 5
- $1 ==> false
- jshell> j
- j ==> 15
- jshell> i
- i ==> 11
- jshell>
-
-```
-
-Similarly, the logical **OR** operator also has two versions:
-* The ```||``` operator we saw earlier. This exhibits lazy evaluation.
-* The ```|``` operator, without lazy evaluation.
-
-It is bad programming practice for our code to depend on the compiler's lazy evaluation. It makes code less readable, and can hide difficult-to-fix software bugs. It obviously adds to the code maintenance burden, so don't do it unless you like being in your peers' bad books.
-
-#### Summary
-
-In this step, we:
-
-* Examined conditions involving logical operators, that had lazy evaluation
-* Observed that the lazy evaluation depends on the operator's truth-table
-* Saw versions of the operators without lazy evaluation
-* Learned that code depending on lazy-evaluation, is less readable
-
-### Step 10: Character Types
-
-Earlier, we explored how we could store basic keyboard characters(called **ascii-code** characters), such as:
-* Upper-Case and lower-case letters (A-Z, a-z)
-* Numeric characters (0-9)
-* Punctuation and other special characters (such as ',', '$', '{', etc.)
-
-Turns out Java supports a much larger family of character encoding sets, called **Unicode**. All Unicode characters can be input to, understood and processed by, as well as output from your code.
-
-##### Snippet-01 : Unicode characters
-
-Not all Unicode characters can be input from your keyboard. But Java allows you to handle their values from your code, if you deal correctly with their format.
-
-```java
-
- jshell> char ch = '"';
- ch ==> '"'
- jshell> char c = '\u0022';
- c ==> '"'
-```
-
-Integer values can be stored in ```char``` variables. If the value is within a meaningful range, it also corresponds to the **ascii** value of a keyboard character.
-
-```java
- jshell> char cn = 65;
- cn ==> 'A'
-```
-
-Integer arithmetic can be performed on `char` data.
-
-```java
- jshell> cn++
- $1 ==> 'A'
- jshell> cn
- $2 ==> 'B'
- jshell> ++cn
- $3 ==> 'C'
- jshell> cn + 5
- $4 ==> 72
- jshell> cn
- cn ==> 'C'
- jshell> (int)cn
- cn ==> 67
- jshell>
-
-```
-
-
-#### Summary
-
-In this step, we:
-
-* Were introduced the the ```char``` data type
-* Learned that Unicode takes the character set beyond your keyboard
-* An ascii character is ```char``` value, encoded by an integer value
-
-### Step 11: Programming Exercise PE-02
-
-#### Exercise Set
-
-1. Write a Java class ```MyChar``` that is a special type of ```char```. An object of type ```MyChar``` is created round an input ```char``` data element, and has operations that do the following:
- * Check if the input character is a:
- * Numeric Digit
- * Letter of the Alphabet
- * Vowel (Either upper-case or lower-case)
- * Consonant (Either upper-case or lower-case) NOTE: A letter is a consonant if not a vowel
- * Print all the letters of the Alphabet in
- * Upper-Case
- * Lower-Case
-
-In Essence, a runner ```class``` for ```MyChar``` would have its ```main``` method run code similar to:
-
-```java
-
- MyChar myChar = new MyChar('c');
- System.out.println(myChar.isDigit());
- System.out.println(myChar.isAlphabet());
- System.out.println(myChar.isVowel());
- System.out.println(myChar.isConsonant());
- myChar.printLowerCaseAlphabets();
- myChar.printUpperCaseAlphabets();
-
-```
-
-### Step 12: Solution To PE-02, Part 1 - ```isVowel()```
-
-**_MyCharRunner.java_**
-
-```java
-
- package com.in28minutes.primitive.datatypes;
-
- public class MyCharRunner {
- public static void main(String[] args) {
- MyChar myChar = new MyChar('c');
- System.out.println(myChar.isVowel());
- }
- }
-
-```
-
-**_MyChar.java_**
-
-```java
-
- package com.in28minutes.primitive.datatypes;
-
- public class MyChar {
- private char ch;
-
- public MyChar(char ch) {
- this.ch = ch;
- }
-
- public boolean isVowel() {
- if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
- return true;
- }
- if(ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') {
- return true;
- }
- return false;
- }
- }
-
-```
-
-**_Console Output_** :
-
-_false_
-
-### Step 13: Solution To PE-02, Part 2 - ```isDigit()```
-
-**_MyCharRunner.java_**
-
-```java
-
- package com.in28minutes.primitive.datatypes;
-
- public class MyCharRunner {
- public static void main(String[] args) {
- MyChar myChar = new MyChar('c');
- System.out.println(myChar.isDigit());
- System.out.println(myChar.isVowel());
- }
- }
-
-```
-
-**_MyChar.java_**
-
-```java
-
- package com.in28minutes.primitive.datatypes;
-
- public class MyChar {
- private char ch;
-
- public MyChar(char ch) {
- this.ch = ch;
- }
-
- public boolean isVowel() {
- if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
- return true;
- }
-
- if(ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') {
- return true;
- }
- return false;
- }
-
- public boolean isDigit() {
- if(ch >= 48 && ch <= 57) {
- return true;
- }
- return false;
- }
-
-}
-
-```
-
-**_Console Output_** :
-
-_false_
-
-_false_
-
-### Step 14: Solution To PE-02, Part 3 - Other Methods
-
-**_MyCharRunner.java_**
-
-```java
-
- package com.in28minutes.primitive.datatypes;
-
- public class MyCharRunner {
- public static void main(String[] args) {
- MyChar myChar = new MyChar('c');
- System.out.println(myChar.isDigit());
- System.out.println(myChar.isAlphabet());
- System.out.println(myChar.isVowel());
- System.out.println(myChar.isConsonant());
- myChar.printLowerCaseAlphabets();
- myChar.printUpperCaseAlphabets();
- }
- }
-
-```
-
-**_MyChar.java_**
-
-```java
-
- package com.in28minutes.primitive.datatypes;
-
- public class MyChar {
- private char ch;
-
- public MyChar(char ch) {
- this.ch = ch;
- }
-
- public boolean isVowel() {
- if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
- return true;
- }
- if(ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') {
- return true;
- }
- return false;
- }
-
- public boolean isConsonant() {
- if(isAlphabet() && !(isVowel())) {
- return true;
- }
- return false;
- }
-
- public boolean isDigit() {
- if(ch >= 48 && ch <= 57) {
- return true;
- }
- return false;
- }
-
- public boolean isAlphabet() {
- if(ch >= 97 && ch <= 122) {
- return true;
- }
- if(ch >= 65 && ch <= 90) {
- return true;
- }
- return false;
- }
-
- public void printLowerCaseAlphabets() {
- for(char ch='a'; ch <= 'z'; ch++) {
- System.out.println(ch);
- }
- }
-
- public void printUpperCaseAlphabets() {
- for(char ch='A'; ch <= 'Z'; ch++) {
- System.out.println(ch);
- }
- }
- }
-
-```
-
-**_Console Output_** :
-
-_false_
-
-_true_
-
-_false_
-
-_true_
-
-a
-
-b
-
-c
-
-d
-
-e
-
-f
-
-g
-
-h
-
-i
-
-j
-
-k
-
-l
-
-m
-
-n
-
-o
-
-p
-
-q
-
-r
-
-s
-
-t
-
-u
-
-v
-
-w
-
-x
-
-y
-
-z
-
-A
-
-B
-
-C
-
-D
-
-E
-
-F
-
-G
-
-H
-
-I
-
-J
-
-K
-
-L
-
-M
-
-N
-
-O
-
-P
-
-Q
-
-R
-
-S
-
-T
-
-U
-
-V
-
-W
-
-X
-
-Y
-
-Z
-
-### Step 15: The Primitive Types - A Review
-
-In this section, we built on our knowledge of the primitive Java types.
-
-* We first got familiar with built-in wrappers for the integer types, that store useful type information.
-* Going from the integer to the floating-point types, we examined type compatibility, and how the compiler warns you about common pitfalls. We used explicit casts to force type conversions, and learned that implicit type conversions are quite common.
-* We moved on to the ```BigDecimal``` class, a floating-point type with greater precision and accuracy.
-* Next in line was ```boolean```, where we built on what we know of logical expressions. We focused on the logical operators, more so on short-circuit evaluation of their expressions.
-* We saw how dependency on side-effects, and on lazy evaluation, is not a good programming practice.
-* Finally, we got to the ```char``` type, and were pleasantly surprised to know, that the keyboard is not the limit.
From ac414cbec74fb41c6decc27c4cd8fa7d4aecf8d6 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sun, 16 Apr 2023 00:44:36 +0530
Subject: [PATCH 122/178] .
---
.../06-PrimitiveDataTypesAndAlternatives.md | 231 +++++++++---------
txt_help.md | 30 +++
2 files changed, 141 insertions(+), 120 deletions(-)
diff --git a/02-CodeChallenge/06-PrimitiveDataTypesAndAlternatives.md b/02-CodeChallenge/06-PrimitiveDataTypesAndAlternatives.md
index 5107ab52..0d224faf 100644
--- a/02-CodeChallenge/06-PrimitiveDataTypesAndAlternatives.md
+++ b/02-CodeChallenge/06-PrimitiveDataTypesAndAlternatives.md
@@ -7,26 +7,22 @@
## Instructions
-### Problem Statement:
+### Problem Statement
-You have been tasked with creating a Java program that calculates the average speed of a group of Formula 1 cars during a race, taking into account their total distance covered and the time taken for each car. Your program should use the following primitive data types: int, long, float, and double.
+In a Formula 1 race, there are 5 cars competing. The total distance traveled by all cars combined is 12,000 meters, and the total time taken by all cars is 720.5 seconds. Your task is to calculate the average speed of the cars in the race.
-### Instructions:
+### Instructions
-1. Create a Java class called `Formula1RaceRunner`.
-2. Define a method named `calculateAverageSpeed` that takes three parameters:
- - an `int` named `numberOfCars`, representing the number of Formula 1 cars in the race
- - a `long` named `totalDistance`, representing the total distance covered by all cars in meters
- - a `float` named `totalTime`, representing the total time taken by all cars in seconds
-3. In the `calculateAverageSpeed` method, calculate the average distance covered by each car by dividing the total distance by the number of cars.
-4. Calculate the average time taken by each car by dividing the total time by the number of cars.
-5. Calculate the average speed by dividing the average distance by the average time. Return the result as a `double`.
-6. Create a `main` method in the `Formula1RaceRunner` class.
-7. In the `main` method, define variables for the number of cars, total distance, and total time. Assign appropriate values to these variables.
-8. Call the `calculateAverageSpeed` method with the defined variables as arguments and store the result in a `double` variable named `averageSpeed`.
-9. Print the `averageSpeed` to the console, formatted to one decimal place.
-
-By following these instructions, you will create a Java program that calculates the average speed of a group of Formula 1 cars during a race, considering their total distance covered and the time taken for each car, using the requested primitive data types.
+1. Implement the `calculateAverageSpeed` method:
+- a. This method should take three parameters: `numberOfCars` (int), `totalDistance` (BigDecimal), and `totalTime` (BigDecimal).
+- b. Calculate the average distance by dividing the `totalDistance` by the `numberOfCars`. Set the scale to 2 and use BigDecimal.ROUND_HALF_UP for rounding.
+- c. Calculate the average time by dividing the `totalTime` by the `numberOfCars`. Set the scale to 2 and use BigDecimal.ROUND_HALF_UP for rounding.
+- d. Divide the average distance by the average time to get the average speed. Set the scale to 2 and use BigDecimal.ROUND_HALF_UP for rounding.
+- e. Return the calculated average speed (BigDecimal).
+
+3. In the `main` method:
+Call the `calculateAverageSpeed` method with the values `numberOfCars`, `totalDistance`, and `totalTime`. Store the result in a variable named `averageSpeed`.
+
#### Output:
@@ -34,115 +30,76 @@ By following these instructions, you will create a Java program that calculates
```
Average speed for the Formula 1 cars: 16.7 m/s
+
```
-This output shows the calculated average speed for the Formula 1 cars during the race, considering their total distance covered and the time taken for each car. The result is formatted to one decimal place.
## Hints
-Here are the hints:
+Here are some short hints in markdown format:
-1. **Hint 1**: Create a `Formula1RaceRunner` class and define a method named `calculateAverageSpeed` that takes three parameters - `numberOfCars`, `totalDistance`, and `totalTime`.
-2. **Hint 2**: Calculate `averageDistance` by dividing `totalDistance` by `numberOfCars`. Calculate `averageTime` by dividing `totalTime` by `numberOfCars`.
-3. **Hint 3**: Calculate the `averageSpeed` by dividing `averageDistance` by `averageTime`. Return the result as a `double`.
-4. **Hint 4**: Create a `main` method in the `Formula1RaceRunner` class. Define variables for the `numberOfCars`, `totalDistance`, and `totalTime`. Assign appropriate values to these variables.
-5. **Hint 5**: Call the `calculateAverageSpeed` method with the defined variables as arguments and store the result in a `double` variable named `averageSpeed`.
-6. **Hint 6**: Print the `averageSpeed` to the console, formatted to one decimal place using `System.out.printf()`.
+1. Use the BigDecimal class for precise decimal calculations.
+2. Divide the total distance by the total time to get the average speed of one car.
+3. Divide the result by the number of cars to get the average speed of all the cars.
+4. Use the ROUND_HALF_UP rounding mode to round the result according to standard mathematical rules.
+5. Call the calculateAverageSpeed() method with the appropriate arguments to get the average speed of the cars.
+6. Store the result of the calculateAverageSpeed() method in a variable named averageSpeed.
## Solution Explanation
-Here is the solution explanation with code in Markdown format:
-To solve this problem, we'll create a Java class called `Formula1RaceRunner` that calculates the average speed of a group of Formula 1 cars during a race, considering their total distance covered and the time taken for each car.
+#### Step 1: Define a method to calculate the average speed of the cars
-**Step 1**: Create a method named `calculateAverageSpeed` in the `Formula1RaceRunner` class:
+The first step is to define a method to calculate the average speed of the cars. This method should take in the following three parameters:
-```
-static double calculateAverageSpeed(int numberOfCars, long totalDistance, float totalTime) {
- // .....
-}
-```
+- `numberOfCars`: an integer representing the number of cars in the race
+- `totalDistance`: a BigDecimal representing the total distance covered by all the cars
+- `totalTime`: a BigDecimal representing the total time taken by all the cars
-This method takes three parameters: `numberOfCars` (an integer), `totalDistance` (a long), and `totalTime` (a float).
+The method should return a BigDecimal representing the average speed of the cars. We can implement this method using the `BigDecimal.divide` method with a scale of 2 and rounding mode of `BigDecimal.ROUND_HALF_UP`.
-**Step 2**: Calculate the average distance and average time:
+Here's the code for the `calculateAverageSpeed` method:
```
-double averageDistance = (double) totalDistance / numberOfCars;
-double averageTime = totalTime / numberOfCars;
-```
-
-We divide the total distance by the number of cars to get the average distance. Similarly, we divide the total time by the number of cars to get the average time.
-
-**Step 3**: Calculate and return the average speed:
-
-```
-return averageDistance / averageTime;
-```
-
-To calculate the average speed, we divide the average distance by the average time.
-
-**Step 4**: Create the `main` method in the `Formula1RaceRunner` class:
+static BigDecimal calculateAverageSpeed(int numberOfCars, BigDecimal totalDistance, BigDecimal totalTime) {
+ BigDecimal averageDistance = totalDistance.divide(new BigDecimal(numberOfCars), 2, BigDecimal.ROUND_HALF_UP);
+ BigDecimal averageTime = totalTime.divide(new BigDecimal(numberOfCars), 2, BigDecimal.ROUND_HALF_UP);
-```
-public static void main(String[] args) {
- // ...
+ return averageDistance.divide(averageTime, 2, BigDecimal.ROUND_HALF_UP);
}
```
-**Step 5**: Define the variables for the number of cars, total distance, and total time, and assign appropriate values to them:
-
-```
-int numberOfCars = 5;
-long totalDistance = 12000; // in meters
-float totalTime = 720.5f; // in seconds
-```
-
-**Step 6**: Call the `calculateAverageSpeed` method with the defined variables as arguments and store the result in a `double` variable named `averageSpeed`:
-
-```
-double averageSpeed = calculateAverageSpeed(numberOfCars, totalDistance, totalTime);
-```
-
-**Step 7**: Print the `averageSpeed` to the console, formatted to one decimal place using `System.out.printf()`:
+#### Step 2: Call the `calculateAverageSpeed` method in the `main` method
-```
-System.out.printf("Average speed for the Formula 1 cars: %.1f m/s\n", averageSpeed);
-```
+The next step is to call the `calculateAverageSpeed` method in the `main` method and store the result in a variable named `averageSpeed`. We can then print out the average speed using the `System.out.println` method.
-The complete `Formula1RaceRunner` class should look like this:
+Here's the code for the `main` method:
```
-public class Formula1RaceRunner {
-
- static double calculateAverageSpeed(int numberOfCars, long totalDistance, float totalTime) {
- double averageDistance = (double) totalDistance / numberOfCars;
- double averageTime = totalTime / numberOfCars;
-
- return averageDistance / averageTime;
- }
-
- public static void main(String[] args) {
- int numberOfCars = 5;
- long totalDistance = 12000; // in meters
- float totalTime = 720.5f; // in seconds
+public static void main(String[] args) {
+ int numberOfCars = 5;
+ BigDecimal totalDistance = new BigDecimal("12000"); // in meters
+ BigDecimal totalTime = new BigDecimal("720.5"); // in seconds
- double averageSpeed = calculateAverageSpeed(numberOfCars, totalDistance, totalTime);
+ BigDecimal averageSpeed = calculateAverageSpeed(numberOfCars, totalDistance, totalTime);
- System.out.printf("Average speed for the Formula 1 cars: %.1f m/s\n", averageSpeed);
- }
+ System.out.println("Average speed for the Formula 1 cars: " + averageSpeed.setScale(1, BigDecimal.ROUND_HALF_UP) + " m/s");
}
```
-When you run this Java program, it calculates the average speed of the Formula 1 cars during the race and prints the result:
+#### Step 3: Output the result
+
+The final step is to run the program and observe the output. The program should output the following:
```
Average speed for the Formula 1 cars: 16.7 m/s
```
-
+
+And that's it!
+
## Student File
@@ -153,24 +110,29 @@ Average speed for the Formula 1 cars: 16.7 m/s
```
+import java.math.BigDecimal;
+
public class Formula1RaceRunner {
-
- static double calculateAverageSpeed(int numberOfCars, long totalDistance, float totalTime) {
- // Complete the code
+
+ // The method should return a BigDecimal representing the average speed of the cars.
+ // Use the BigDecimal.divide method with a scale of 2 and rounding mode of BigDecimal.ROUND_HALF_UP.
+ static BigDecimal calculateAverageSpeed(int numberOfCars, BigDecimal totalDistance, BigDecimal totalTime) {
+ // Write your code here
}
public static void main(String[] args) {
int numberOfCars = 5;
- long totalDistance = 12000; // in meters
- float totalTime = 720.5f; // in seconds
+ BigDecimal totalDistance = new BigDecimal("12000"); // in meters
+ BigDecimal totalTime = new BigDecimal("720.5"); // in seconds
- // Complete the code
- double averageSpeed;
+ // TODO: Call the calculateAverageSpeed method and store the result in a variable named averageSpeed.
+ BigDecimal averageSpeed;
- System.out.printf("Average speed for the Formula 1 cars: %.1f m/s\n", averageSpeed);
+ System.out.println("Average speed for the Formula 1 cars: " + averageSpeed.setScale(1, BigDecimal.ROUND_HALF_UP) + " m/s");
}
}
+
```
@@ -186,23 +148,25 @@ public class Formula1RaceRunner {
```
+import java.math.BigDecimal;
+
public class Formula1RaceRunner {
- static double calculateAverageSpeed(int numberOfCars, long totalDistance, float totalTime) {
- double averageDistance = (double) totalDistance / numberOfCars;
- double averageTime = totalTime / numberOfCars;
+ static BigDecimal calculateAverageSpeed(int numberOfCars, BigDecimal totalDistance, BigDecimal totalTime) {
+ BigDecimal averageDistance = totalDistance.divide(new BigDecimal(numberOfCars), 2, BigDecimal.ROUND_HALF_UP);
+ BigDecimal averageTime = totalTime.divide(new BigDecimal(numberOfCars), 2, BigDecimal.ROUND_HALF_UP);
- return averageDistance / averageTime;
+ return averageDistance.divide(averageTime, 2, BigDecimal.ROUND_HALF_UP);
}
public static void main(String[] args) {
int numberOfCars = 5;
- long totalDistance = 12000; // in meters
- float totalTime = 720.5f; // in seconds
+ BigDecimal totalDistance = new BigDecimal("12000"); // in meters
+ BigDecimal totalTime = new BigDecimal("720.5"); // in seconds
- double averageSpeed = calculateAverageSpeed(numberOfCars, totalDistance, totalTime);
+ BigDecimal averageSpeed = calculateAverageSpeed(numberOfCars, totalDistance, totalTime);
- System.out.printf("Average speed for the Formula 1 cars: %.1f m/s\n", averageSpeed);
+ System.out.println("Average speed for the Formula 1 cars: " + averageSpeed.setScale(1, BigDecimal.ROUND_HALF_UP) + " m/s");
}
}
@@ -219,35 +183,62 @@ public class Formula1RaceRunner {
```
-import org.junit.jupiter.api.BeforeEach;
+// Evaluate.java
import org.junit.jupiter.api.Test;
-import java.util.logging.Logger;
import static org.junit.jupiter.api.Assertions.assertEquals;
+import com.udemy.ucp.IOHelper;
+import com.udemy.ucp.EvaluationHelper;
+import static org.junit.jupiter.api.Assertions.fail;
+import java.lang.reflect.Method;
+
+import java.math.BigDecimal;
public class Evaluate {
- private Formula1RaceRunner formula1RaceRunner;
- private static final Logger LOGGER = Logger.getLogger(Evaluate.class.getName());
+ Formula1RaceRunner runner = new Formula1RaceRunner();
+ IOHelper helper = new IOHelper();
+
+ EvaluationHelper evaluationHelper = new EvaluationHelper();
- @BeforeEach
- public void setUp() {
- formula1RaceRunner = new Formula1RaceRunner();
+
+ @Test
+ public void testFieldsAndMethods() {
+ try {
+ Method calculateAverageSpeedMethod = Formula1RaceRunner.class.getDeclaredMethod("calculateAverageSpeed", int.class, BigDecimal.class, BigDecimal.class);
+ } catch (NoSuchMethodException e) {
+ fail("'calculateAverageSpeed' method is not declared.");
+ }
+
+ try {
+ Method mainMethod = Formula1RaceRunner.class.getDeclaredMethod("main", String[].class);
+ } catch (NoSuchMethodException e) {
+ fail("'main' method is not declared.");
+ }
}
+
+
+
+
@Test
public void testCalculateAverageSpeed() {
- LOGGER.info("Running testCalculateAverageSpeed...");
-
int numberOfCars = 5;
- long totalDistance = 12000; // in meters
- float totalTime = 720.5f; // in seconds
+ BigDecimal totalDistance = new BigDecimal("12000");
+ BigDecimal totalTime = new BigDecimal("720.5");
- double expectedAverageSpeed = 16.7;
+ BigDecimal averageSpeed = runner.calculateAverageSpeed(numberOfCars, totalDistance, totalTime);
- double actualAverageSpeed = Formula1RaceRunner.calculateAverageSpeed(numberOfCars, totalDistance, totalTime);
+ assertEquals(new BigDecimal("16.7"), averageSpeed.setScale(1, BigDecimal.ROUND_HALF_UP), "Average speed calculation is incorrect.");
+ }
- assertEquals(expectedAverageSpeed, actualAverageSpeed, 0.1, "The average speed calculation is not correct");
+ @Test
+ public void testMainMethod() {
+ helper.resetStdOut(); // clean stdout
+ Formula1RaceRunner.main(new String[] {});
+ String actualOutput = helper.getOutput().trim(); // remove leading/trailing whitespaces
+ assertEquals("Average speed for the Formula 1 cars: 16.7 m/s", actualOutput, "Output does not match the expected format.");
}
+
}
```
\ No newline at end of file
diff --git a/txt_help.md b/txt_help.md
index e69de29b..6765666a 100644
--- a/txt_help.md
+++ b/txt_help.md
@@ -0,0 +1,30 @@
+
+
+Solution
+
+```
+import java.math.BigDecimal;
+
+public class Formula1RaceRunner {
+
+ static BigDecimal calculateAverageSpeed(int numberOfCars, BigDecimal totalDistance, BigDecimal totalTime) {
+ BigDecimal averageDistance = totalDistance.divide(new BigDecimal(numberOfCars), 2, BigDecimal.ROUND_HALF_UP);
+ BigDecimal averageTime = totalTime.divide(new BigDecimal(numberOfCars), 2, BigDecimal.ROUND_HALF_UP);
+
+ return averageDistance.divide(averageTime, 2, BigDecimal.ROUND_HALF_UP);
+ }
+
+ public static void main(String[] args) {
+ int numberOfCars = 5;
+ BigDecimal totalDistance = new BigDecimal("12000"); // in meters
+ BigDecimal totalTime = new BigDecimal("720.5"); // in seconds
+
+ BigDecimal averageSpeed = calculateAverageSpeed(numberOfCars, totalDistance, totalTime);
+
+ System.out.println("Average speed for the Formula 1 cars: " + averageSpeed.setScale(1, BigDecimal.ROUND_HALF_UP) + " m/s");
+ }
+}
+```
+
+Test
+
From f638928acf3a6a690644ecaed5e445e67d800a6f Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Mon, 24 Apr 2023 12:28:34 +0530
Subject: [PATCH 123/178] .
---
.../06-PrimitiveDataTypesAndAlternatives.md | 362 +++++++++++++++++-
1 file changed, 361 insertions(+), 1 deletion(-)
diff --git a/02-CodeChallenge/06-PrimitiveDataTypesAndAlternatives.md b/02-CodeChallenge/06-PrimitiveDataTypesAndAlternatives.md
index 0d224faf..5d24c63b 100644
--- a/02-CodeChallenge/06-PrimitiveDataTypesAndAlternatives.md
+++ b/02-CodeChallenge/06-PrimitiveDataTypesAndAlternatives.md
@@ -1,5 +1,5 @@
-# Exercise 2: Calculating Average Speed of Formula 1 Cars in a Race using Java
+# Exercise 1: Calculating Average Speed of Formula 1 Cars in a Race using Java
@@ -241,4 +241,364 @@ public class Evaluate {
}
+```
+
+
+
+
+
+
+# Exercise 2: Print First Nth Fibonacci Numbers with MyIntRunner
+
+
+
+## Instructions
+
+### Problem Statement
+
+You are given an incomplete Java program called `MyIntRunner` that has a nested class `MyInt`. Your task is to complete the `MyInt` class by adding the required fields, constructor, and methods, following the provided solution code.
+
+### Detailed Instructions
+
+1. Declare an instance variable `value` of type `int` in the `MyInt` class to store the value of the `MyInt` object.
+
+2. Create a constructor for the `MyInt` class that takes an `int` parameter, `value`. The constructor should initialize the `value` field of the `MyInt` object with the provided `value`.
+
+3. Implement the `printFirstNFibonacciNumbers()` method in the `MyInt` class. This method should print the first N Fibonacci numbers, where N is the `value` of the `MyInt` object.
+
+ (i) Declare and initialize two variables, `a` and `b`, to store the first two Fibonacci numbers (0 and 1, respectively).
+
+ (ii) Declare a variable `c` to store the sum of the two previous Fibonacci numbers.
+
+ (iii) Use a loop to iterate from 1 to `value` (inclusive).
+
+ - (a) Print the current Fibonacci number (value of `a`).
+ - (b) Calculate the sum of the two previous Fibonacci numbers (`a` and `b`) and store it in `c`.
+ - (c) Update the values of `a` and `b` for the next iteration: `a` should become `b` and `b` should become `c`.
+
+
+### Output Format
+
+The output of the program should be the first N Fibonacci numbers, where N is the `value` of the `MyInt` object, each on a new line.
+
+### Example
+
+For a `MyInt` object with a `value` of 10, the output should be:
+
+```
+0
+1
+1
+2
+3
+5
+8
+13
+21
+34
+```
+
+
+## Hints
+
+1. Use the `public` keyword to declare the instance variable `value` and the constructor of the `MyInt` class.
+
+2. Initialize the `value` field of the `MyInt` object in the constructor using `this.value = value`.
+
+3. To declare the `printFirstNFibonacciNumbers()` method, use the `public` keyword followed by the `void` return type.
+
+4. Use a `for` loop to iterate from 1 to `value` (inclusive).
+
+5. Inside the loop, print the current Fibonacci number using `System.out.println(a)`.
+
+6. Update the Fibonacci numbers using `c = a + b`, `a = b`, and `b = c` inside the loop.
+
+## Solution Explanation
+
+The solution involves completing the `MyInt` class by adding the required fields, constructor, and methods. Let's go through the solution step by step:
+
+1. Declare the instance variable `value` of type `int` in the `MyInt` class:
+
+ ```
+ public int value;
+ ```
+
+2. Create a constructor for the `MyInt` class that takes an `int` parameter, `value`. The constructor should initialize the `value` field of the `MyInt` object with the provided `value`:
+
+ ```
+ public MyInt(int value) {
+ this.value = value;
+ }
+ ```
+
+3. Implement the `printFirstNFibonacciNumbers()` method in the `MyInt` class:
+
+ ```public void printFirstNFibonacciNumbers() {
+ // (i) Declare and initialize variables to store the first two Fibonacci numbers
+ int a = 0, b = 1;
+
+ // (ii) Declare a variable to store the sum of the two previous Fibonacci numbers
+ int c;
+
+ // (iii) Use a loop to iterate from 1 to value (inclusive)
+ for (int i = 1; i <= value; i++) {
+ // (a) Print the current Fibonacci number
+ System.out.println(a);
+
+ // (b) Calculate the sum of the two previous Fibonacci numbers and store it in c
+ c = a + b;
+
+ // (c) Update the values of a and b for the next iteration
+ a = b;
+ b = c;
+ }
+ }
+ ```
+
+
+Now, the `MyInt` class is complete with the required fields, constructor, and methods. The `MyIntRunner` class, with the completed `MyInt` class, will print the first N Fibonacci numbers, where N is the `value` of the `MyInt` object.
+
+Here's the final solution code:
+
+```
+public class MyIntRunner {
+ public static void main(String[] args) {
+ // Create a MyInt object with a value of 10
+ MyInt myInt = new MyInt(10);
+
+ // Call the printFirstNFibonacciNumbers method on the myInt object
+ myInt.printFirstNFibonacciNumbers();
+ }
+
+ static class MyInt {
+ // Declare an instance variable to store the value
+ public int value;
+
+ // Constructor to initialize the value of the MyInt object
+ public MyInt(int value) {
+ this.value = value;
+ }
+
+ // Method to print the first N Fibonacci numbers, where N is the value of the MyInt object
+ public void printFirstNFibonacciNumbers() {
+ // Declare and initialize variables to store the first two Fibonacci numbers
+ int a = 0, b = 1;
+
+ // Declare a variable to store the sum of the two previous Fibonacci numbers
+ int c;
+
+ // Loop from 1 to value (inclusive)
+ for (int i = 1; i <= value; i++) {
+ // Print the current Fibonacci number
+ System.out.println(a);
+
+ // Calculate the sum of the two previous Fibonacci numbers
+ c = a + b;
+
+ // Update the values of a and b for the next iteration
+ a = b;
+ b = c;
+ }
+ }
+ }
+}
+```
+
+
+## Student File
+
+
+
+**MyIntRunner.java**
+
+
+
+```
+public class MyIntRunner {
+ public static void main(String[] args) {
+ // Create a MyInt object with a value of 10
+ MyInt myInt = new MyInt(10);
+
+ // Call the printFirstNFibonacciNumbers method on the myInt object
+ myInt.printFirstNFibonacciNumbers();
+ }
+
+ static class MyInt {
+ // Declare an instance variable to store the value
+
+ // Constructor to initialize the value of the MyInt object
+
+ // Method to print the first N Fibonacci numbers, where N is the value of the MyInt object
+ public void printFirstNFibonacciNumbers() {
+ // TODO: Declare and initialize variables to store the first two Fibonacci numbers
+
+ // TODO: Declare a variable to store the sum of the two previous Fibonacci numbers
+
+ // TODO: Loop from 1 to value (inclusive)
+
+ // TODO: Print the current Fibonacci number
+
+ // TODO: Calculate the sum of the two previous Fibonacci numbers
+
+ // TODO: Update the values of the two Fibonacci number variables for the next iteration
+ }
+ }
+}
+
+
+
+```
+
+
+
+
+
+## Solution File
+
+
+
+**MyIntRunner.java**
+
+
+
+```
+public class MyIntRunner {
+ public static void main(String[] args) {
+ // Create a MyInt object with a value of 10
+ MyInt myInt = new MyInt(10);
+
+ // Call the printFirstNFibonacciNumbers method on the myInt object
+ myInt.printFirstNFibonacciNumbers();
+ }
+
+ static class MyInt {
+ // Declare an instance variable to store the value
+ public int value;
+
+ // Constructor to initialize the value of the MyInt object
+ public MyInt(int value) {
+ this.value = value;
+ }
+
+
+ // Method to print the first N Fibonacci numbers, where N is the value of the MyInt object
+ public void printFirstNFibonacciNumbers() {
+ // Declare and initialize variables to store the first two Fibonacci numbers
+ int a = 0, b = 1;
+
+ // Declare a variable to store the sum of the two previous Fibonacci numbers
+ int c;
+
+ // Loop from 1 to value (inclusive)
+ for (int i = 1; i <= value; i++) {
+ // Print the current Fibonacci number
+ System.out.println(a);
+
+ // Calculate the sum of the two previous Fibonacci numbers
+ c = a + b;
+
+ // Update the values of a and b for the next iteration
+ a = b;
+ b = c;
+ }
+ }
+ }
+}
+
+```
+
+
+
+
+## Evaluation File
+
+
+**Evaluate.java**
+
+
+
+```
+// Evaluate.java
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+import java.util.logging.Logger;
+import java.util.logging.Level;
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+
+public class Evaluate {
+
+ private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
+ private final PrintStream originalOut = System.out;
+ private static final Logger LOGGER = Logger.getLogger(Evaluate.class.getName());
+
+ @BeforeEach
+ public void setUpStreams() {
+ System.setOut(new PrintStream(outContent));
+ }
+
+ // Other tests...
+ @Test
+ public void testPrintFirstNFibonacciNumbers() {
+ MyIntRunner.MyInt myInt = new MyIntRunner.MyInt(10);
+ myInt.printFirstNFibonacciNumbers();
+
+ String expectedOutput = "0" + System.lineSeparator() +
+ "1" + System.lineSeparator() +
+ "1" + System.lineSeparator() +
+ "2" + System.lineSeparator() +
+ "3" + System.lineSeparator() +
+ "5" + System.lineSeparator() +
+ "8" + System.lineSeparator() +
+ "13" + System.lineSeparator() +
+ "21" + System.lineSeparator() +
+ "34" + System.lineSeparator();
+ String actualOutput = outContent.toString();
+ LOGGER.log(Level.INFO, "Expected Output: " + expectedOutput);
+ LOGGER.log(Level.INFO, "Actual Output: " + actualOutput);
+ assertEquals(expectedOutput, actualOutput, "MyInt.printFirstNFibonacciNumbers() should print the first N Fibonacci numbers correctly");
+ }
+
+ @Test
+ public void testFieldsAndMethods() {
+ // Check if the 'value' field is declared
+ try {
+ Field valueField = MyIntRunner.MyInt.class.getDeclaredField("value");
+ assertEquals(int.class, valueField.getType(), "MyInt.value field should be of type int");
+ } catch (NoSuchFieldException e) {
+ LOGGER.log(Level.SEVERE, "MyInt.value field is missing", e);
+ assertTrue(false, "MyInt.value field should be declared");
+ }
+
+ // Check if the constructor is declared
+ try {
+ MyIntRunner.MyInt.class.getDeclaredConstructor(int.class);
+ assertTrue(true, "MyInt constructor should be declared");
+ } catch (NoSuchMethodException e) {
+ LOGGER.log(Level.SEVERE, "MyInt constructor is missing", e);
+ assertTrue(false, "MyInt constructor should be declared");
+ }
+
+ // Check if the 'printFirstNFibonacciNumbers()' method is declared
+ try {
+ Method printFirstNFibonacciNumbersMethod = MyIntRunner.MyInt.class.getDeclaredMethod("printFirstNFibonacciNumbers");
+ assertEquals(void.class, printFirstNFibonacciNumbersMethod.getReturnType(), "MyInt.printFirstNFibonacciNumbers() method should have void return type");
+ } catch (NoSuchMethodException e) {
+ LOGGER.log(Level.SEVERE, "MyInt.printFirstNFibonacciNumbers() method is missing", e);
+ assertTrue(false, "MyInt.printFirstNFibonacciNumbers() method should be declared");
+ }
+ }
+
+ @AfterEach
+ public void restoreStreams() {
+ System.setOut(originalOut);
+ }
+}
+
+
```
\ No newline at end of file
From 407ade5266ff3cfd9480e90ad600ea373d2470d7 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Mon, 24 Apr 2023 12:31:29 +0530
Subject: [PATCH 124/178] Update 06-PrimitiveDataTypesAndAlternatives.md
---
02-CodeChallenge/06-PrimitiveDataTypesAndAlternatives.md | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/02-CodeChallenge/06-PrimitiveDataTypesAndAlternatives.md b/02-CodeChallenge/06-PrimitiveDataTypesAndAlternatives.md
index 5d24c63b..e89f3810 100644
--- a/02-CodeChallenge/06-PrimitiveDataTypesAndAlternatives.md
+++ b/02-CodeChallenge/06-PrimitiveDataTypesAndAlternatives.md
@@ -260,7 +260,7 @@ You are given an incomplete Java program called `MyIntRunner` that has a nested
### Detailed Instructions
-1. Declare an instance variable `value` of type `int` in the `MyInt` class to store the value of the `MyInt` object.
+1. Declare an public instance variable `value` of type `int` in the `MyInt` class to store the value of the `MyInt` object.
2. Create a constructor for the `MyInt` class that takes an `int` parameter, `value`. The constructor should initialize the `value` field of the `MyInt` object with the provided `value`.
@@ -371,7 +371,7 @@ public class MyIntRunner {
}
static class MyInt {
- // Declare an instance variable to store the value
+ // Declare an public instance variable to store the value
public int value;
// Constructor to initialize the value of the MyInt object
@@ -601,4 +601,4 @@ public class Evaluate {
}
-```
\ No newline at end of file
+```
From 31ccc912cba8d013695f7f130b253cddf67414c1 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Tue, 25 Apr 2023 10:55:27 +0530
Subject: [PATCH 125/178] .
---
Archive/Ref.md | 62 ++++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 62 insertions(+)
create mode 100644 Archive/Ref.md
diff --git a/Archive/Ref.md b/Archive/Ref.md
new file mode 100644
index 00000000..4583b03d
--- /dev/null
+++ b/Archive/Ref.md
@@ -0,0 +1,62 @@
+## 1
+
+```
+import java.util.Scanner;
+
+public class UdemyCourseAccess {
+
+ public static void main(String[] args) {
+ Scanner scanner = new Scanner(System.in);
+
+ System.out.print("Are you logged in? (yes/no): ");
+ String loggedIn = scanner.nextLine();
+
+ if (loggedIn.equalsIgnoreCase("yes")) {
+ System.out.print("Are you enrolled in the in28Minutes course? (yes/no): ");
+ String enrolled = scanner.nextLine();
+
+ if (enrolled.equalsIgnoreCase("yes")) {
+ System.out.println("Welcome to the in28Minutes Course!");
+ } else {
+ System.out.println("Please enroll in the in28Minutes course.");
+ }
+ } else {
+ System.out.println("Please log in to Udemy.");
+ }
+
+ scanner.close();
+ }
+}
+```
+
+
+## 2
+
+```
+import java.util.Scanner;
+
+public class UdemyCourseAccess {
+
+ public static void main(String[] args) {
+ Scanner scanner = new Scanner(System.in);
+
+ System.out.print("Are you logged in? (1 for yes, 0 for no): ");
+ int loggedIn = scanner.nextInt();
+
+ if (loggedIn == 1) {
+ System.out.print("Are you enrolled in the in28Minutes course? (1 for yes, 0 for no): ");
+ int enrolled = scanner.nextInt();
+
+ if (enrolled == 1) {
+ System.out.println("Welcome to the in28Minutes Course!");
+ } else {
+ System.out.println("Please enroll in the in28Minutes course.");
+ }
+ } else {
+ System.out.println("Please log in to Udemy.");
+ }
+
+ scanner.close();
+ }
+}
+```
\ No newline at end of file
From e6a38510e1ed9fef3bd23b7cd0ba2fa74b7ce8b9 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Tue, 25 Apr 2023 12:33:46 +0530
Subject: [PATCH 126/178] .
---
02-CodeChallenge/07-Conditionals.md | 285 ++++++++++++++++++++++++++++
txt_help.md | 66 +++++--
2 files changed, 334 insertions(+), 17 deletions(-)
create mode 100644 02-CodeChallenge/07-Conditionals.md
diff --git a/02-CodeChallenge/07-Conditionals.md b/02-CodeChallenge/07-Conditionals.md
new file mode 100644
index 00000000..9123d036
--- /dev/null
+++ b/02-CodeChallenge/07-Conditionals.md
@@ -0,0 +1,285 @@
+
+# Month Name Printer
+
+## Problem Statement
+
+You are tasked with implementing a Java program that takes an integer input representing the month number (1-12) and prints the corresponding month name.
+
+### Instructions
+
+1. **TODO:** Implement the `getMonthName()` method which takes an integer `monthNumber` as a parameter and returns the corresponding month name as a string. If the given `monthNumber` is invalid (not in the range of 1-12), the method should return `null`.
+
+2. **TODO:** In the `main()` method, prompt the user to enter the month number (1-12). Call the `getMonthName()` method with the entered month number as an argument and store the result in a variable named `monthName`.
+
+3. **TODO:** Use an `if-else` statement to check if the `monthName` is `null`. If it is, print "Invalid month number entered." If it's not `null`, print "The name of month number [monthNumber] is [monthName]."
+
+
+### Input Format
+
+The input is a single integer `monthNumber` (1 ≤ monthNumber ≤ 12).
+
+```
+4
+```
+
+### Output Format
+
+The output is a single line with the month name corresponding to the given `monthNumber`. If the `monthNumber` is invalid, the output is "Invalid month number entered."
+
+```
+The name of month number 4 is April.
+```
+
+### Example
+
+**Input:**
+
+```
+Enter the month number (1-12):
+4
+```
+
+**Output:**
+
+```
+The name of month number 4 is April.
+```
+
+**Input:**
+
+```
+Enter the month number (1-12):
+0
+```
+
+**Output:**
+
+```
+Invalid month number entered.
+```
+
+
+## Hints
+
+1. Use a `switch` statement inside the `getMonthName()` method to map the `monthNumber` to its corresponding month name.
+
+2. Use a `Scanner` object to read user input in the `main()` method.
+
+3. After calling the `getMonthName()` method, use an `if-else` statement to check if the returned value is `null` or a valid month name.
+
+4. Print the appropriate message based on the value of the `monthName` variable.
+
+
+## Answer Explanation
+
+To implement the Month Name Printer program, follow these steps:
+
+1. Use a `switch` statement inside the `getMonthName()` method to map the `monthNumber` to its corresponding month name.
+2. Use a `Scanner` object to read user input in the `main()` method.
+3. After calling the `getMonthName()` method, use an `if-else` statement to check if the returned value is `null` or a valid month name.
+4. Print the appropriate message based on the value of the `monthName` variable.
+
+Here's the complete code for the Month Name Printer program:
+
+
+```
+import java.util.Scanner;
+
+public class MonthNamePrinter {
+
+ public static void main(String[] args) {
+ Scanner scanner = new Scanner(System.in);
+
+ System.out.println("Enter the month number (1-12):");
+ int monthNumber = scanner.nextInt();
+
+ String monthName = getMonthName(monthNumber);
+
+ if (monthName == null) {
+ System.out.println("Invalid month number entered.");
+ } else {
+ System.out.println("The name of month number " + monthNumber + " is " + monthName + ".");
+ }
+ }
+
+ public static String getMonthName(int monthNumber) {
+ switch (monthNumber) {
+ case 1: return "January";
+ case 2: return "February";
+ case 3: return "March";
+ case 4: return "April";
+ case 5: return "May";
+ case 6: return "June";
+ case 7: return "July";
+ case 8: return "August";
+ case 9: return "September";
+ case 10: return "October";
+ case 11: return "November";
+ case 12: return "December";
+ default: return null;
+ }
+ }
+}
+```
+
+In this implementation, the `getMonthName()` method uses a `switch` statement to map the input `monthNumber` to its corresponding month name. If the input is invalid (not between 1 and 12), the method returns `null`.
+
+The `main()` method uses a `Scanner` object to read the month number from the user, calls the `getMonthName()` method, and checks if the returned value is `null` or a valid month name. If the value is `null`, the program prints "Invalid month number entered." If the value is a valid month name, the program prints "The name of month number [monthNumber] is [monthName]."
+
+
+
+
+
+
+## Student File
+
+
+
+
+
+**MonthNamePrinter.java**
+
+
+
+
+
+```
+
+import java.util.Scanner;
+
+public class MonthNamePrinter {
+
+ public static void main(String[] args) {
+ Scanner scanner = new Scanner(System.in);
+
+ System.out.println("Enter the month number (1-12):");
+ int monthNumber = scanner.nextInt();
+
+ // TODO: Call the getMonthName method with monthNumber as the argument
+ String monthName = null; // Replace 'null' with the method call
+
+ if (monthName == null) {
+ System.out.println("Invalid month number entered.");
+ } else {
+ System.out.println("The name of month number " + monthNumber + " is " + monthName + ".");
+ }
+ }
+
+ // TODO: Complete the getMonthName method
+ public static String getMonthName(int monthNumber) {
+ // Implement the method to return the correct month name based on the given month number
+ // You can use a switch statement to determine the month name
+ return null; // Replace 'null' with your implementation
+ }
+}
+
+
+```
+
+
+
+
+
+
+
+## Solution File
+
+
+
+
+
+**MonthNamePrinter.java**
+
+
+
+
+
+```
+
+import java.util.Scanner;
+
+public class MonthNamePrinter {
+
+ public static void main(String[] args) {
+ Scanner scanner = new Scanner(System.in);
+
+ System.out.println("Enter the month number (1-12):");
+ int monthNumber = scanner.nextInt();
+
+ String monthName = getMonthName(monthNumber);
+
+ if (monthName == null) {
+ System.out.println("Invalid month number entered.");
+ } else {
+ System.out.println("The name of month number " + monthNumber + " is " + monthName + ".");
+ }
+ }
+
+ public static String getMonthName(int monthNumber) {
+ switch (monthNumber) {
+ case 1: return "January";
+ case 2: return "February";
+ case 3: return "March";
+ case 4: return "April";
+ case 5: return "May";
+ case 6: return "June";
+ case 7: return "July";
+ case 8: return "August";
+ case 9: return "September";
+ case 10: return "October";
+ case 11: return "November";
+ case 12: return "December";
+ default: return null;
+ }
+ }
+}
+
+```
+
+
+
+
+
+## Evaluation File
+
+
+
+**Evaluate.java**
+
+
+
+
+
+```
+
+import org.junit.jupiter.api.Test;
+
+import java.util.logging.Logger;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+class Evaluate {
+ private static final Logger LOGGER = Logger.getLogger(Evaluate.class.getName());
+
+ @Test
+ void testGetMonthName() {
+ LOGGER.info("Testing getMonthName() method...");
+ assertEquals("January", MonthNamePrinter.getMonthName(1), "Month number 1 should return January");
+ assertEquals("February", MonthNamePrinter.getMonthName(2), "Month number 2 should return February");
+ assertEquals("March", MonthNamePrinter.getMonthName(3), "Month number 3 should return March");
+ assertEquals("April", MonthNamePrinter.getMonthName(4), "Month number 4 should return April");
+ assertEquals("May", MonthNamePrinter.getMonthName(5), "Month number 5 should return May");
+ assertEquals("June", MonthNamePrinter.getMonthName(6), "Month number 6 should return June");
+ assertEquals("July", MonthNamePrinter.getMonthName(7), "Month number 7 should return July");
+ assertEquals("August", MonthNamePrinter.getMonthName(8), "Month number 8 should return August");
+ assertEquals("September", MonthNamePrinter.getMonthName(9), "Month number 9 should return September");
+ assertEquals("October", MonthNamePrinter.getMonthName(10), "Month number 10 should return October");
+ assertEquals("November", MonthNamePrinter.getMonthName(11), "Month number 11 should return November");
+ assertEquals("December", MonthNamePrinter.getMonthName(12), "Month number 12 should return December");
+ assertNull(MonthNamePrinter.getMonthName(0), "Month number 0 should return null");
+ assertNull(MonthNamePrinter.getMonthName(13), "Month number 13 should return null");
+ }
+}
+
+
+```
\ No newline at end of file
diff --git a/txt_help.md b/txt_help.md
index 6765666a..f4aed4f1 100644
--- a/txt_help.md
+++ b/txt_help.md
@@ -1,30 +1,62 @@
-Solution
+# Month Name Printer
+
+## Problem Statement
+
+You are tasked with implementing a Java program that takes an integer input representing the month number (1-12) and prints the corresponding month name.
+
+### Instructions
+
+1. **TODO:** Implement the `getMonthName()` method which takes an integer `monthNumber` as a parameter and returns the corresponding month name as a string. If the given `monthNumber` is invalid (not in the range of 1-12), the method should return `null`.
+
+2. **TODO:** In the `main()` method, prompt the user to enter the month number (1-12). Call the `getMonthName()` method with the entered month number as an argument and store the result in a variable named `monthName`.
+
+3. **TODO:** Use an `if-else` statement to check if the `monthName` is `null`. If it is, print "Invalid month number entered." If it's not `null`, print "The name of month number [monthNumber] is [monthName]."
+
+
+### Input Format
+
+The input is a single integer `monthNumber` (1 ≤ monthNumber ≤ 12).
+
+```
+4
+```
+
+## Output Format
+
+The output is a single line with the month name corresponding to the given `monthNumber`. If the `monthNumber` is invalid, the output is "Invalid month number entered."
```
-import java.math.BigDecimal;
+The name of month number 4 is April.
+```
+
+### Example
-public class Formula1RaceRunner {
+**Input:**
- static BigDecimal calculateAverageSpeed(int numberOfCars, BigDecimal totalDistance, BigDecimal totalTime) {
- BigDecimal averageDistance = totalDistance.divide(new BigDecimal(numberOfCars), 2, BigDecimal.ROUND_HALF_UP);
- BigDecimal averageTime = totalTime.divide(new BigDecimal(numberOfCars), 2, BigDecimal.ROUND_HALF_UP);
+```
+Enter the month number (1-12):
+4
+```
- return averageDistance.divide(averageTime, 2, BigDecimal.ROUND_HALF_UP);
- }
+**Output:**
- public static void main(String[] args) {
- int numberOfCars = 5;
- BigDecimal totalDistance = new BigDecimal("12000"); // in meters
- BigDecimal totalTime = new BigDecimal("720.5"); // in seconds
+```
+The name of month number 4 is April.
+```
- BigDecimal averageSpeed = calculateAverageSpeed(numberOfCars, totalDistance, totalTime);
+**Input:**
- System.out.println("Average speed for the Formula 1 cars: " + averageSpeed.setScale(1, BigDecimal.ROUND_HALF_UP) + " m/s");
- }
-}
+```
+Enter the month number (1-12):
+0
+```
+
+**Output:**
+
+```
+Invalid month number entered.
```
-Test
From 4815fb10d639dccf82e81f5f3fbdaa1453ff1e38 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Tue, 25 Apr 2023 12:34:35 +0530
Subject: [PATCH 127/178] Update 07-Conditionals.md
---
02-CodeChallenge/07-Conditionals.md | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/02-CodeChallenge/07-Conditionals.md b/02-CodeChallenge/07-Conditionals.md
index 9123d036..30b8acd8 100644
--- a/02-CodeChallenge/07-Conditionals.md
+++ b/02-CodeChallenge/07-Conditionals.md
@@ -32,7 +32,7 @@ The name of month number 4 is April.
### Example
-**Input:**
+**Input 1:**
```
Enter the month number (1-12):
@@ -45,7 +45,7 @@ Enter the month number (1-12):
The name of month number 4 is April.
```
-**Input:**
+**Input 2:**
```
Enter the month number (1-12):
@@ -282,4 +282,4 @@ class Evaluate {
}
-```
\ No newline at end of file
+```
From 45ce4beb99d782cead813259f57b8f5d73efc445 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Tue, 25 Apr 2023 13:48:39 +0530
Subject: [PATCH 128/178] h
---
02-CodeChallenge/07-Conditionals.md | 370 +++++++++++++++++++++++++++-
1 file changed, 369 insertions(+), 1 deletion(-)
diff --git a/02-CodeChallenge/07-Conditionals.md b/02-CodeChallenge/07-Conditionals.md
index 30b8acd8..a491bee9 100644
--- a/02-CodeChallenge/07-Conditionals.md
+++ b/02-CodeChallenge/07-Conditionals.md
@@ -1,5 +1,6 @@
-# Month Name Printer
+
+# Exercise 1: Month Name Printer
## Problem Statement
@@ -283,3 +284,370 @@ class Evaluate {
```
+
+
+
+
+# Exercise 2: Udemy Course Access Exercise
+
+## Problem Statement
+
+You are given the task of implementing a simple console application in Java that checks if a user is logged in and enrolled in the "in28Minutes" course on Udemy. The application should prompt the user to input their login and enrollment status and then display a response based on the input.
+
+### Instructions
+
+Complete the following tasks in the `UdemyCourseAccess` class:
+
+- **TODO 1**: Create a new `Scanner` object to read input from the console.
+- **TODO 2**: Prompt the user to enter their login status (1 for yes, 0 for no) and store the input in the `loggedIn` variable.
+- **TODO 3**: Prompt the user to enter their enrollment status (1 for yes, 0 for no) and store the input in the `enrolled` variable.
+- **TODO 4**: Call the `processUserInput` method with the `loggedIn` and `enrolled` values, and store the result in the `response` variable.
+- **TODO 5**: Print the response to the console.
+- **TODO 6**: Close the scanner to avoid resource leaks.
+- **TODO 7**: Implement the `processUserInput` method that takes `loggedIn` and `enrolled` as parameters and returns a `String` response.
+
+In the `processUserInput` method, implement the following logic:
+
+- **TODO 8**: Check if the user is logged in (`loggedIn` == 1).
+- **TODO 9**: If logged in, check if the user is enrolled in the "in28Minutes" course (`enrolled` == 1).
+- **TODO 10**: If enrolled, return the welcome message: `"Welcome to the in28Minutes Course!"`.
+- **TODO 11**: If not enrolled, return a message asking the user to enroll: `"Please enroll in the in28Minutes course."`.
+- **TODO 12**: If not logged in, return a message asking the user to log in: `"Please log in to Udemy."`.
+
+After implementing the above tasks, the application should correctly display the appropriate response based on the user's input.
+
+
+### Output Format
+
+The output is a single string based on the user's input.
+
+- If the user is logged in and enrolled in the course, the output is: `"Welcome to the in28Minutes Course!"`.
+- If the user is logged in but not enrolled, the output is: `"Please enroll in the in28Minutes course."`.
+- If the user is not logged in, the output is: `"Please log in to Udemy."`.
+
+**Example:**
+
+```
+Welcome to the in28Minutes Course!
+```
+
+or
+
+```
+Please enroll in the in28Minutes course.
+```
+
+or
+
+```
+Please log in to Udemy.
+```
+
+
+## Hints
+
+1. Use a `Scanner` object to read input from the console.
+2. Prompt the user to input their login and enrollment status using `nextInt()`.
+3. Call the `processUserInput` method and store the result in a variable.
+4. Print the result to the console.
+5. Close the `Scanner` object.
+6. Implement the `processUserInput` method with the given parameters.
+7. Use conditional statements (`if`, `else`) to determine the appropriate response.
+8. Return the corresponding response string based on the user's input.
+
+
+## Solution Explanation
+
+We will implement the `UdemyCourseAccess` class, which will prompt the user for their login and enrollment status, process the input, and display the appropriate response. The `processUserInput` method will contain the logic to determine the response based on the input.
+
+Here's a step-by-step explanation of the solution:
+
+1. Create a `Scanner` object to read input from the console.
+
+```
+Scanner scanner = new Scanner(System.in);
+```
+
+2. Prompt the user to enter their login status and store the input in the `loggedIn` variable.
+
+```
+System.out.print("Are you logged in? (1 for yes, 0 for no): ");
+int loggedIn = scanner.nextInt();
+```
+
+3. Prompt the user to enter their enrollment status and store the input in the `enrolled` variable.
+
+```
+System.out.print("Are you enrolled in the in28Minutes course? (1 for yes, 0 for no): ");
+int enrolled = scanner.nextInt();
+```
+
+4. Call the `processUserInput` method with the `loggedIn` and `enrolled` values, and store the result in the `response` variable.
+
+```
+String response = processUserInput(loggedIn, enrolled);
+```
+
+5. Print the response to the console.
+
+```
+System.out.println(response);
+```
+
+6. Close the `Scanner` object to avoid resource leaks.
+
+```
+scanner.close();
+```
+
+7. Implement the `processUserInput` method that takes `loggedIn` and `enrolled` as parameters and returns a `String` response.
+
+```
+public static String processUserInput(int loggedIn, int enrolled) {
+```
+
+8. Use conditional statements (`if`, `else`) to determine the appropriate response.
+
+```
+if (loggedIn == 1) {
+ if (enrolled == 1) {
+ return "Welcome to the in28Minutes Course!";
+ } else {
+ return "Please enroll in the in28Minutes course.";
+ }
+} else {
+ return "Please log in to Udemy.";
+}
+```
+
+The complete `UdemyCourseAccess` class will look like this:
+
+```
+import java.util.Scanner;
+
+public class UdemyCourseAccess {
+
+ public static void main(String[] args) {
+ Scanner scanner = new Scanner(System.in);
+
+ System.out.print("Are you logged in? (1 for yes, 0 for no): ");
+ int loggedIn = scanner.nextInt();
+
+ System.out.print("Are you enrolled in the in28Minutes course? (1 for yes, 0 for no): ");
+ int enrolled = scanner.nextInt();
+
+ String response = processUserInput(loggedIn, enrolled);
+ System.out.println(response);
+
+ scanner.close();
+ }
+
+ public static String processUserInput(int loggedIn, int enrolled) {
+ if (loggedIn == 1) {
+ if (enrolled == 1) {
+ return "Welcome to the in28Minutes Course!";
+ } else {
+ return "Please enroll in the in28Minutes course.";
+ }
+ } else {
+ return "Please log in to Udemy.";
+ }
+ }
+}
+```
+
+This solution will correctly display the appropriate response based on the user's input for login and enrollment status.
+
+
+
+
+## Student File
+
+
+
+
+
+
+
+**UdemyCourseAccess.java**
+
+
+
+
+
+
+
+```
+import java.util.Scanner;
+
+public class UdemyCourseAccess {
+
+ public static void main(String[] args) {
+ // TODO: 1. Create a new Scanner object to read input from the console.
+
+
+ // TODO: 2. Prompt the user to enter their login status, and store the input in the loggedIn variable.
+ System.out.print("Are you logged in? (1 for yes, 0 for no): ");
+ int loggedIn;
+
+ // TODO: 3. Prompt the user to enter their enrollment status, and store the input in the enrolled variable.
+ System.out.print("Are you enrolled in the in28Minutes course? (1 for yes, 0 for no): ");
+ int enrolled;
+
+ // TODO: 4. Call the processUserInput method with the loggedIn and enrolled values, and store the result in the response variable.
+ String response;
+
+ // TODO: 5. Print the response to the console.
+ System.out.println(response);
+
+ // TODO: 6. Close the scanner to avoid resource leaks.
+
+ }
+
+ // 7. Implement the processUserInput method that takes loggedIn and enrolled as parameters and returns a String response.
+ public static String processUserInput(int loggedIn, int enrolled) {
+ // TODO: Implement the logic to return the appropriate response based on loggedIn and enrolled values.
+
+ // 8. Check if the user is logged in (loggedIn == 1).
+
+ // 9. If logged in, check if the user is enrolled in the in28Minutes course (enrolled == 1).
+
+ // 10. If enrolled, return the welcome message.
+
+ // 11. If not enrolled, return a message asking the user to enroll.
+
+ // 12. If not logged in, return a message asking the user to log in.
+
+ return ""; // Replace this line with your logic.
+ }
+}
+
+```
+
+
+
+
+
+
+
+
+
+## Solution File
+
+
+
+
+
+
+
+**UdemyCourseAccess.java**
+
+
+```
+import java.util.Scanner;
+
+public class UdemyCourseAccess {
+
+ public static void main(String[] args) {
+ // 1. Create a new Scanner object to read input from the console.
+ Scanner scanner = new Scanner(System.in);
+
+ // 2. Prompt the user to enter their login status, and store the input in the loggedIn variable.
+ System.out.print("Are you logged in? (1 for yes, 0 for no): ");
+ int loggedIn = scanner.nextInt();
+
+ // 3. Prompt the user to enter their enrollment status, and store the input in the enrolled variable.
+ System.out.print("Are you enrolled in the in28Minutes course? (1 for yes, 0 for no): ");
+ int enrolled = scanner.nextInt();
+
+ // 4. Call the processUserInput method with the loggedIn and enrolled values, and store the result in the response variable.
+ String response = processUserInput(loggedIn, enrolled);
+
+ // 5. Print the response to the console.
+ System.out.println(response);
+
+ // 6. Close the scanner to avoid resource leaks.
+ scanner.close();
+ }
+
+ // 7. Implement the processUserInput method that takes loggedIn and enrolled as parameters and returns a String response.
+ public static String processUserInput(int loggedIn, int enrolled) {
+ // 8. Check if the user is logged in (loggedIn == 1).
+ if (loggedIn == 1) {
+ // 9. If logged in, check if the user is enrolled in the in28Minutes course (enrolled == 1).
+ if (enrolled == 1) {
+ // 10. If enrolled, return the welcome message.
+ return "Welcome to the in28Minutes Course!";
+ } else {
+ // 11. If not enrolled, return a message asking the user to enroll.
+ return "Please enroll in the in28Minutes course.";
+ }
+ } else {
+ // 12. If not logged in, return a message asking the user to log in.
+ return "Please log in to Udemy.";
+ }
+ }
+}
+
+
+```
+
+
+
+
+
+
+
+## Evaluation File
+
+
+
+
+
+**Evaluate.java**
+
+
+
+
+
+
+
+```
+
+import org.junit.jupiter.api.Test;
+import java.util.logging.Logger;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+public class Evaluate {
+
+ private static final Logger LOGGER = Logger.getLogger(Evaluate.class.getName());
+
+ @Test
+ public void testLoggedInAndEnrolled() {
+ String expected = "Welcome to the in28Minutes Course!";
+ String actual = UdemyCourseAccess.processUserInput(1, 1);
+ LOGGER.info("Expected: " + expected + ", Actual: " + actual);
+ assertEquals(expected, actual, "Failed: Logged in and enrolled test");
+ }
+
+ @Test
+ public void testLoggedInNotEnrolled() {
+ String expected = "Please enroll in the in28Minutes course.";
+ String actual = UdemyCourseAccess.processUserInput(1, 0);
+ LOGGER.info("Expected: " + expected + ", Actual: " + actual);
+ assertEquals(expected, actual, "Failed: Logged in but not enrolled test");
+ }
+
+ @Test
+ public void testNotLoggedIn() {
+ String expected = "Please log in to Udemy.";
+ String actual = UdemyCourseAccess.processUserInput(0, 0);
+ LOGGER.info("Expected: " + expected + ", Actual: " + actual);
+ assertEquals(expected, actual, "Failed: Not logged in test");
+ }
+}
+
+```
+=======
+
+>>>>>>> 4815fb10d639dccf82e81f5f3fbdaa1453ff1e38
\ No newline at end of file
From 636eacad4aaf45e4e76ef73d5da44400189e60cf Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Tue, 25 Apr 2023 13:49:07 +0530
Subject: [PATCH 129/178] .
---
02-CodeChallenge/07-Conditionals.md | 1 -
1 file changed, 1 deletion(-)
diff --git a/02-CodeChallenge/07-Conditionals.md b/02-CodeChallenge/07-Conditionals.md
index a491bee9..7d5a1a1e 100644
--- a/02-CodeChallenge/07-Conditionals.md
+++ b/02-CodeChallenge/07-Conditionals.md
@@ -650,4 +650,3 @@ public class Evaluate {
```
=======
->>>>>>> 4815fb10d639dccf82e81f5f3fbdaa1453ff1e38
\ No newline at end of file
From 4f1b5a635f505c23daaa025e28e600cbb010dcae Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Wed, 3 May 2023 21:38:00 +0530
Subject: [PATCH 130/178] .
---
02-CodeChallenge/08-Loops.md | 624 +++++++++++++++++++++++++++++++++++
1 file changed, 624 insertions(+)
create mode 100644 02-CodeChallenge/08-Loops.md
diff --git a/02-CodeChallenge/08-Loops.md b/02-CodeChallenge/08-Loops.md
new file mode 100644
index 00000000..53ae1d9d
--- /dev/null
+++ b/02-CodeChallenge/08-Loops.md
@@ -0,0 +1,624 @@
+# Exercise 1: Pyramid Star Pattern Exercise
+
+## Problem Statement
+
+In this exercise, you will complete a Java program to print a pyramid star pattern. The program has an incomplete function `printPyramidStarPattern()` that takes an integer `n` as an input, which represents the number of rows in the pyramid. Your task is to complete the function so that it prints a pyramid pattern with `n` rows using asterisks (*) and spaces.
+
+### Instructions
+
+1. Complete the `printPyramidStarPattern(int n)` method inside the `PyramidStarPattern` class. This method should take an integer `n` as its parameter and print a pyramid pattern with `n` rows using asterisks (*) and spaces.
+2. In the `printPyramidStarPattern()` method, use nested loops to print the pyramid pattern.
+ - In the outer loop, iterate from `1` to `n` inclusive.
+ - In the first inner loop, print spaces. The number of spaces to print is equal to `n - i`, where `i` is the current iteration of the outer loop.
+ - In the second inner loop, print asterisks. The number of asterisks to print is equal to `(2 * i) - 1`.
+ - After printing the spaces and asterisks, move to the next line.
+
+### Example Output
+
+For an input of `5`, the output should look like this:
+
+```
+ *
+ ***
+ *****
+ *******
+*********
+```
+
+The main method and the variable initialization have already been provided for you. Complete the `printPyramidStarPattern()` method to produce the correct output for the given input. Good luck!
+
+
+## Hints
+
+1. Use nested loops to construct the pyramid pattern. The outer loop iterates through each row, while the inner loops print spaces and asterisks.
+
+2. In the outer loop, start with `i = 1` and iterate up to `n` inclusive, where `n` is the number of rows.
+
+3. In the first inner loop, start with `j = 1` and iterate up to `n - i` inclusive. In each iteration, print a space character (`" "`).
+
+4. In the second inner loop, start with `k = 1` and iterate up to `(2 * i) - 1` inclusive. In each iteration, print an asterisk (`"*"`).
+
+5. After the inner loops have finished, use `System.out.println();` to move to the next line before the next iteration of the outer loop.
+
+
+Remember to use the provided student code as a starting point, and complete the `printPyramidStarPattern()` method to produce the correct output.
+
+
+## Answer Explanation
+
+To complete the `printPyramidStarPattern()` method, we need to use nested loops to print spaces and asterisks in the correct order to form a pyramid pattern.
+
+Here is the complete code with an explanation:
+
+```
+public class PyramidStarPattern {
+ // Method to print a pyramid pattern with n rows
+ public static void printPyramidStarPattern(int n) {
+ // Iterate through each row, where i is the current row number
+ for (int i = 1; i <= n; i++) {
+ // Print spaces before the asterisks in the current row
+ for (int j = 1; j <= n - i; j++) {
+ System.out.print(" ");
+ }
+ // Print asterisks in the current row
+ for (int k = 1; k <= (2 * i) - 1; k++) {
+ System.out.print("*");
+ }
+ // Move to the next line for the next row
+ System.out.println();
+ }
+ }
+
+ // Main method to run the program
+ public static void main(String[] args) {
+ // Set the fixed number of rows for the pyramid
+ int myPyramid = 5;
+ // Call the printPyramidStarPattern method with the specified number of rows
+ printPyramidStarPattern(myPyramid);
+ }
+}
+
+```
+
+1. The outer loop iterates from `1` to `n` inclusive, where `n` is the number of rows in the pyramid. In each iteration, the value of `i` represents the current row number.
+
+2. In the first inner loop, we print spaces. We iterate from `1` to `n - i` inclusive. In each iteration, we print a space character (`" "`). This creates the necessary spacing to the left of the pyramid.
+
+3. In the second inner loop, we print asterisks. We iterate from `1` to `(2 * i) - 1` inclusive. In each iteration, we print an asterisk (`"*"`). This forms the actual shape of the pyramid with increasing numbers of asterisks in each row.
+
+4. After the inner loops have finished, we use `System.out.println();` to move to the next line before the next iteration of the outer loop. This creates a new row for the next set of spaces and asterisks.
+
+
+When the program is run, it will print the pyramid pattern with the specified number of rows (in this case, `5`).
+
+
+## Student File
+
+```
+public class PyramidStarPattern {
+ // Method to print the pyramid star pattern
+ public static void printPyramidStarPattern(int n) {
+ // TODO: Use nested loops to print the pyramid pattern
+ // Outer loop: iterate through each row
+ // First inner loop: print spaces (n - i spaces for row i)
+ // Second inner loop: print asterisks ((2 * i) - 1 asterisks for row i)
+ // After inner loops: move to the next line
+ }
+
+ // Main method to run the program
+ public static void main(String[] args) {
+ int myPyramid = 5; // Set the fixed number of rows for the pyramid
+ // Call the printPyramidStarPattern method to print the pyramid pattern
+ printPyramidStarPattern(myPyramid);
+ }
+}
+
+```
+
+
+## Solution File
+
+```
+public class PyramidStarPattern {
+ // Method to print a pyramid pattern with n rows
+ public static void printPyramidStarPattern(int n) {
+ // Iterate through each row, where i is the current row number
+ for (int i = 1; i <= n; i++) {
+ // Print spaces before the asterisks in the current row
+ for (int j = 1; j <= n - i; j++) {
+ System.out.print(" ");
+ }
+ // Print asterisks in the current row
+ for (int k = 1; k <= (2 * i) - 1; k++) {
+ System.out.print("*");
+ }
+ // Move to the next line for the next row
+ System.out.println();
+ }
+ }
+
+ // Main method to run the program
+ public static void main(String[] args) {
+ // Set the fixed number of rows for the pyramid
+ int myPyramid = 5;
+ // Call the printPyramidStarPattern method with the specified number of rows
+ printPyramidStarPattern(myPyramid);
+ }
+}
+
+```
+
+## Evaluation File
+
+```
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+import java.util.logging.Logger;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+public class Evaluate {
+ private final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
+ private final PrintStream originalOut = System.out;
+ private final Logger logger = Logger.getLogger(Evaluate.class.getName());
+
+ @BeforeEach
+ public void setUpStreams() {
+ System.setOut(new PrintStream(outputStream));
+ }
+
+ @AfterEach
+ public void restoreStreams() {
+ System.setOut(originalOut);
+ }
+
+ @Test
+ public void test_print_pyramid_with_1_row() {
+ PyramidStarPattern.printPyramidStarPattern(1);
+ String expected = "*\n";
+ String actual = outputStream.toString();
+ logger.info("Expected output: \n" + expected);
+ logger.info("Actual output: \n" + actual);
+ assertEquals(expected, actual, "Should print a pyramid with 1 row");
+ }
+
+ @Test
+ public void test_print_pyramid_with_3_rows() {
+ PyramidStarPattern.printPyramidStarPattern(3);
+ String expected = " *\n ***\n*****\n";
+ String actual = outputStream.toString();
+ logger.info("Expected output: \n" + expected);
+ logger.info("Actual output: \n" + actual);
+ assertEquals(expected, actual, "Should print a pyramid with 3 rows");
+ }
+
+ @Test
+ public void test_print_pyramid_with_5_rows() {
+ PyramidStarPattern.printPyramidStarPattern(5);
+ String expected = " *\n ***\n *****\n *******\n*********\n";
+ String actual = outputStream.toString();
+ logger.info("Expected output: \n" + expected);
+ logger.info("Actual output: \n" + actual);
+ assertEquals(expected, actual, "Should print a pyramid with 5 rows");
+ }
+}
+```
+
+
+
+
+
+# Exercise 2: Simple Calculator Exercise
+
+## Problem Statement
+
+In this exercise, you will complete a Java program that acts as a simple calculator. The calculator allows users to perform addition and subtraction. The program contains a `printMenu()` method to display the available operations, and an incomplete `main` method where you need to implement the calculator's functionality.
+
+### Instructions
+
+1. Complete the `main` method inside the `SimpleCalculator` class using a `do-while` loop. The loop should continue executing until the user chooses to exit (option `3`).
+
+2. Inside the `do-while` loop, call the `printMenu()` method to display the available operations.
+
+3. Read the user's choice using `scanner.nextInt()` and store it in the `choice` variable.
+
+4. Use conditional statements (`if-else`) to perform the selected operation:
+
+ - If `choice` is `1`, perform addition:
+ - Prompt the user with `System.out.print("Enter the first number: ");`
+ - Read the first number from the user using `scanner.nextInt()`.
+ - Prompt the user with `System.out.print("Enter the second number: ");`
+ - Read the second number from the user using `scanner.nextInt()`.
+ - Add the two numbers together and print the result using `System.out.println("The result is: " + sum);`
+ - If `choice` is `2`, perform subtraction:
+ - Prompt the user with `System.out.print("Enter the first number: ");`
+ - Read the first number from the user using `scanner.nextInt()`.
+ - Prompt the user with `System.out.print("Enter the second number: ");`
+ - Read the second number from the user using `scanner.nextInt()`.
+ - Subtract the second number from the first number and print the result using `System.out.println("The result is: " + difference);`
+ - If `choice` is `3`, exit the loop and print a goodbye message using `System.out.println("Thank you for using Simple Calculator. Goodbye!");`
+ - If the `choice` is any other value, print an error message indicating an invalid choice using `System.out.println("Invalid choice. Please try again.");`
+5. The loop should continue executing until the user selects option `3` (Exit). After the loop, close the `Scanner` object using `scanner.close()`.
+
+
+### Example Output
+
+A sample interaction with the calculator should look like this:
+
+```
+Welcome to Simple Calculator!
+Please choose an operation:
+1. Addition
+2. Subtraction
+3. Exit
+Enter your choice: 1
+Enter the first number: 5
+Enter the second number: 3
+The result is: 8
+
+Welcome to Simple Calculator!
+Please choose an operation:
+1. Addition
+2. Subtraction
+3. Exit
+Enter your choice: 2
+Enter the first number: 10
+Enter the second number: 4
+The result is: 6
+
+Welcome to Simple Calculator!
+Please choose an operation:
+1. Addition
+2. Subtraction
+3. Exit
+Enter your choice: 3
+Thank you for using Simple Calculator. Goodbye!
+```
+
+Complete the `main` method in the provided student code, following the solution code to implement the calculator's functionality. Ensure that you include the specific print statements as described in the instructions. Good luck!
+
+
+## Hints
+
+1. Use a `do-while` loop to keep the calculator running until the user selects option `3` (Exit).
+
+2. Call the `printMenu()` method at the beginning of each iteration of the `do-while` loop to display the available operations.
+
+3. Use `scanner.nextInt()` to read the user's choice and store it in the `choice` variable.
+
+4. Use `if-else` statements to handle the user's choice:
+
+ - For addition (choice `1`), read two numbers and print their sum.
+ - For subtraction (choice `2`), read two numbers and print their difference.
+ - For exit (choice `3`), print a goodbye message and exit the loop.
+ - For an invalid choice, print an error message.
+5. Remember to close the `Scanner` object after the `do-while` loop using `scanner.close()`.
+
+
+Use the provided student code as a starting point, and complete the `main` method to implement the calculator's functionality.
+
+
+### Solution Explanation
+
+To complete the `main` method inside the `SimpleCalculator` class, follow these steps:
+
+1. Wrap the calculator's functionality in a `do-while` loop that continues executing until the user selects option `3` (Exit).
+
+```
+do {
+ // Calculator functionality will go here
+} while (choice != 3);
+```
+
+2. Inside the `do-while` loop, call the `printMenu()` method to display the available operations, and read the user's choice using `scanner.nextInt()`.
+
+```
+printMenu();
+choice = scanner.nextInt();
+```
+3. Use an `if-else` statement to perform the selected operation based on the user's choice:
+
+```
+if (choice == 1) {
+ // Addition
+} else if (choice == 2) {
+ // Subtraction
+} else if (choice == 3) {
+ // Exit
+} else {
+ // Invalid choice
+}
+```
+
+4. Complete the `if-else` branches for addition, subtraction, and invalid choice:
+
+ - For addition (choice `1`), read two numbers from the user, add them together, and print the result.
+
+```
+System.out.print("Enter the first number: ");
+ int num1 = scanner.nextInt();
+ System.out.print("Enter the second number: ");
+ int num2 = scanner.nextInt();
+ int sum = num1 + num2;
+ System.out.println("The result is: " + sum);
+```
+
+ - For subtraction (choice `2`), read two numbers from the user, subtract the second number from the first number, and print the result.
+
+ ```
+ System.out.print("Enter the first number: ");
+ int num1 = scanner.nextInt();
+ System.out.print("Enter the second number: ");
+ int num2 = scanner.nextInt();
+ int difference = num1 - num2;
+ System.out.println("The result is: " + difference);
+````
+
+ - For exit (choice `3`), print a goodbye message.
+
+ ```
+ System.out.println("Thank you for using Simple Calculator. Goodbye!");
+```
+
+ - For an invalid choice, print an error message.
+
+
+ System.out.println("Invalid choice. Please try again.");
+
+
+5. After the `do-while` loop, close the `Scanner` object using `scanner.close()`.
+
+
+Here is the complete `main` method with all the steps implemented:
+
+```
+import java.util.Scanner;
+
+public class SimpleCalculator {
+
+ // Print menu to display available operations
+ public static void printMenu() {
+ System.out.println("Welcome to Simple Calculator!");
+ System.out.println("Please choose an operation:");
+ System.out.println("1. Addition");
+ System.out.println("2. Subtraction");
+ System.out.println("3. Exit");
+ System.out.print("Enter your choice: ");
+ }
+
+ public static void main(String[] args) {
+ Scanner scanner = new Scanner(System.in); // Initialize the Scanner object
+ int choice; // Declare a variable to store the user's choice
+
+ do {
+ printMenu(); // Display the available operations
+ choice = scanner.nextInt(); // Read the user's choice
+
+ if (choice == 1) {
+ // Perform addition
+ System.out.print("Enter the first number: ");
+ int num1 = scanner.nextInt();
+ System.out.print("Enter the second number: ");
+ int num2 = scanner.nextInt();
+ int sum = num1 + num2;
+ System.out.println("The result is: " + sum);
+ } else if (choice == 2) {
+ // Perform subtraction
+ System.out.print("Enter the first number: ");
+ int num1 = scanner.nextInt();
+ System.out.print("Enter the second number: ");
+ int num2 = scanner.nextInt();
+ int difference = num1 - num2;
+ System.out.println("The result is: " + difference);
+ } else if (choice == 3) {
+ // Exit the calculator
+ System.out.println("Thank you for using Simple Calculator. Goodbye!");
+ } else {
+ // Handle invalid choice
+ System.out.println("Invalid choice. Please try again.");
+ }
+
+ } while (choice != 3); // Continue executing until the user selects option 3 (Exit)
+
+ scanner.close(); // Close the Scanner object
+ }
+}
+
+```
+With these steps implemented, the `SimpleCalculator` class is now complete. The calculator will continue running until the user selects option `3` (Exit), allowing them to perform addition and subtraction operations repeatedly. The specific print statements for each operation ensure clear communication with the user.
+
+
+## Student File
+
+```
+
+import java.util.Scanner;
+
+public class SimpleCalculator {
+
+ // Print menu to display available operations
+ public static void printMenu() {
+ System.out.println("Welcome to Simple Calculator!");
+ System.out.println("Please choose an operation:");
+ System.out.println("1. Addition");
+ System.out.println("2. Subtraction");
+ System.out.println("3. Exit");
+ System.out.print("Enter your choice: ");
+ }
+
+ public static void main(String[] args) {
+ Scanner scanner = new Scanner(System.in); // Initialize the Scanner object
+ int choice; // Declare a variable to store the user's choice
+
+ // Implement the calculator functionality in a do-while loop
+ // The loop should continue until the user chooses to exit (option 3)
+ // Your code will go here
+
+ scanner.close(); // Close the Scanner object
+ }
+}
+
+
+```
+
+
+## Solution File
+
+```
+import java.util.Scanner;
+
+public class SimpleCalculator {
+
+ // Print menu to display available operations
+ public static void printMenu() {
+ System.out.println("Welcome to Simple Calculator!");
+ System.out.println("Please choose an operation:");
+ System.out.println("1. Addition");
+ System.out.println("2. Subtraction");
+ System.out.println("3. Exit");
+ System.out.print("Enter your choice: ");
+ }
+
+ public static void main(String[] args) {
+ Scanner scanner = new Scanner(System.in); // Initialize the Scanner object
+ int choice; // Declare a variable to store the user's choice
+
+ do {
+ printMenu(); // Display the available operations
+ choice = scanner.nextInt(); // Read the user's choice
+
+ if (choice == 1) {
+ // Perform addition
+ System.out.print("Enter the first number: ");
+ int num1 = scanner.nextInt();
+ System.out.print("Enter the second number: ");
+ int num2 = scanner.nextInt();
+ int sum = num1 + num2;
+ System.out.println("The result is: " + sum);
+ } else if (choice == 2) {
+ // Perform subtraction
+ System.out.print("Enter the first number: ");
+ int num1 = scanner.nextInt();
+ System.out.print("Enter the second number: ");
+ int num2 = scanner.nextInt();
+ int difference = num1 - num2;
+ System.out.println("The result is: " + difference);
+ } else if (choice == 3) {
+ // Exit the calculator
+ System.out.println("Thank you for using Simple Calculator. Goodbye!");
+ } else {
+ // Handle invalid choice
+ System.out.println("Invalid choice. Please try again.");
+ }
+
+ } while (choice != 3); // Continue executing until the user selects option 3 (Exit)
+
+ scanner.close(); // Close the Scanner object
+ }
+}
+
+
+```
+
+
+## Evaluation File
+
+```
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.InputStream;
+import java.io.PrintStream;
+import java.util.logging.Logger;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+public class Evaluate {
+ private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
+ private final PrintStream originalOut = System.out;
+ private static final Logger logger = Logger.getLogger(Evaluate.class.getName());
+
+ @BeforeEach
+ public void setUpStreams() {
+ System.setOut(new PrintStream(outContent));
+ }
+
+ @AfterEach
+ public void restoreStreams() {
+ System.setOut(originalOut);
+ }
+
+ @Test
+ public void test_addition() {
+ String input = "1\n5\n3\n3\n";
+ InputStream in = new ByteArrayInputStream(input.getBytes());
+ System.setIn(in);
+
+ SimpleCalculator.main(new String[]{});
+
+ String actualOutput = outContent.toString();
+ String expectedOutput = "Welcome to Simple Calculator!\nPlease choose an operation:\n1. Addition\n2. Subtraction\n3. Exit\nEnter your choice: Enter the first number: Enter the second number: The result is: 8\nWelcome to Simple Calculator!\nPlease choose an operation:\n1. Addition\n2. Subtraction\n3. Exit\nEnter your choice: Thank you for using Simple Calculator. Goodbye!\n";
+ assertEquals(expectedOutput, actualOutput);
+ logger.info("Actual Output: " + actualOutput);
+ logger.info("Expected Output: " + expectedOutput);
+ }
+
+ @Test
+ public void test_subtraction() {
+ String input = "2\n5\n3\n3\n";
+ InputStream in = new ByteArrayInputStream(input.getBytes());
+ System.setIn(in);
+
+ SimpleCalculator.main(new String[]{});
+
+ String actualOutput = outContent.toString();
+ String expectedOutput = "Welcome to Simple Calculator!\nPlease choose an operation:\n1. Addition\n2. Subtraction\n3. Exit\nEnter your choice: Enter the first number: Enter the second number: The result is: 2\nWelcome to Simple Calculator!\nPlease choose an operation:\n1. Addition\n2. Subtraction\n3. Exit\nEnter your choice: Thank you for using Simple Calculator. Goodbye!\n";
+ assertEquals(expectedOutput, actualOutput);
+ logger.info("Actual Output: " + actualOutput);
+ logger.info("Expected Output: " + expectedOutput);
+ }
+
+ @Test
+ public void test_invalid_choice() {
+ String input = "4\n3\n";
+ InputStream in = new ByteArrayInputStream(input.getBytes());
+ System.setIn(in);
+
+ SimpleCalculator.main(new String[]{});
+
+ String actualOutput = outContent.toString();
+ String expectedOutput = "Welcome to Simple Calculator!\nPlease choose an operation:\n1. Addition\n2. Subtraction\n3. Exit\nEnter your choice: Invalid choice. Please try again.\nWelcome to Simple Calculator!\nPlease choose an operation:\n1. Addition\n2. Subtraction\n3. Exit\nEnter your choice: Thank you for using Simple Calculator. Goodbye!\n";
+ assertEquals(expectedOutput, actualOutput);
+ logger.info("Actual Output: " + actualOutput);
+ logger.info("Expected Output: " + expectedOutput);
+ }
+
+ @Test
+ public void test_exit() {
+ String input = "3\n";
+ InputStream in = new ByteArrayInputStream(input.getBytes());
+ System.setIn(in);
+
+ SimpleCalculator.main(new String[]{});
+
+ String actualOutput = outContent.toString();
+ String expectedOutput = "Welcome to Simple Calculator!\nPlease choose an operation:\n1. Addition\n2. Subtraction\n3. Exit\nEnter your choice: Thank you for using Simple Calculator. Goodbye!\n";
+ assertEquals(expectedOutput, actualOutput);
+ logger.info("Actual Output: " + actualOutput);
+ logger.info("Expected Output: " + expectedOutput);
+ }
+}
+
+
+```
+
+
+
+
From 7f4161131120e7b2caf57767004c4e6776275e34 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Wed, 3 May 2023 22:00:40 +0530
Subject: [PATCH 131/178] .
---
02-CodeChallenge/09-ReferenceTypes.md | 305 ++++++++++++++++++++++++++
1 file changed, 305 insertions(+)
create mode 100644 02-CodeChallenge/09-ReferenceTypes.md
diff --git a/02-CodeChallenge/09-ReferenceTypes.md b/02-CodeChallenge/09-ReferenceTypes.md
new file mode 100644
index 00000000..463abc47
--- /dev/null
+++ b/02-CodeChallenge/09-ReferenceTypes.md
@@ -0,0 +1,305 @@
+## Exercise 1: Vowel Extraction from a String
+
+You are given a partial implementation of a `VowelPrinter` class. Your task is to complete the `isVowel` method and the `main` method to achieve the following functionality:
+
+1. Read a string input from the user.
+2. Iterate through the characters of the string using a `while` loop.
+3. Check if a character is a vowel (a, e, i, o, or u) using the `isVowel` method.
+4. Print the vowel characters in the order they appear in the input string.
+
+### Input Format
+
+- A single line containing a string (1 <= |input| <= 1000) consisting of alphanumeric characters and spaces.
+
+### Output Format
+
+- A single line containing the vowels from the input string in the order they appear.
+
+### Instructions
+
+1. Implement the `isVowel` method to check if a given character is a vowel. Convert the character to lowercase and compare it to the vowel characters (a, e, i, o, or u).
+
+2. In the `main` method, read a string from the user using the `Scanner` object and store it in the `input` variable. Close the `Scanner` object after reading the input.
+
+3. Initialize an `index` variable with the value `0`.
+
+4. Use a `while` loop to iterate through the characters of the input string. The loop should continue until the `index` is equal to the length of the input string.
+
+5. Inside the loop, get the character at the current `index` of the input string using the `charAt` method.
+
+6. Check if the character is a vowel using the `isVowel` method. If it is a vowel, print the character.
+
+7. Increment the `index` variable by `1`.
+
+
+Use the provided student code as a starting point, and complete the `isVowel` method and the `main` method according to the instructions.
+
+### Example
+
+Input:
+
+```
+Programming is fun!
+```
+
+Output:
+
+```
+oaiu
+```
+
+In the input string "Programming is fun!", the vowels are 'o', 'a', 'i', and 'u', which are printed in the order they appear.
+
+
+
+## Hints
+
+1. In the `isVowel` method, use `Character.toLowerCase` to convert the input character to lowercase before comparing it to the vowel characters.
+2. To compare the character with vowel characters, use the logical OR operator (`||`) to check if the character is equal to any of the vowel characters (a, e, i, o, or u).
+3. In the `main` method, use the `Scanner` object to read the input string and close the scanner after reading the input.
+4. Create a `while` loop with the condition `index < input.length()`.
+5. Inside the loop, use the `charAt` method to get the character at the current index from the input string.
+6. Call the `isVowel` method to check if the character is a vowel, and print it if the method returns `true`.
+7. Increment the `index` variable by 1 to move to the next character in the input string.
+
+## Solution Explanation
+
+In this solution, we implement the `VowelPrinter` class by completing the `isVowel` method and the `main` method as follows:
+
+1. **Implement the `isVowel` method**: Convert the input character to lowercase using `Character.toLowerCase` and then check if the character is equal to any of the vowel characters (a, e, i, o, or u) using the logical OR operator (`||`).
+
+```
+public static boolean isVowel(char ch) {
+ ch = Character.toLowerCase(ch);
+ return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u';
+}
+```
+
+2. **Read the input string**: In the `main` method, use a `Scanner` object to read the input string and store it in the `input` variable. Close the `Scanner` object after reading the input.
+
+```
+Scanner scanner = new Scanner(System.in);
+String input = scanner.nextLine();
+scanner.close();
+```
+
+3. **Initialize the index variable**: Create an `index` variable with the value `0`.
+
+```
+int index = 0;
+```
+
+4. **Iterate through the characters**: Use a `while` loop with the condition `index < input.length()` to iterate through the characters of the input string.
+
+```
+while (index < input.length()) {
+ // Loop body
+}
+```
+
+5. **Get the character**: Inside the loop, use the `charAt` method to get the character at the current index from the input string.
+
+```
+char ch = input.charAt(index);
+```
+
+6. **Check if the character is a vowel**: Call the `isVowel` method to check if the character is a vowel. If the method returns `true`, print the character.
+
+```
+if (isVowel(ch)) {
+ System.out.print(ch);
+}
+```
+
+7. **Increment the index**: Increment the `index` variable by 1 to move to the next character in the input string.
+
+```
+index++;
+```
+
+With these steps implemented, the `VowelPrinter` class is now complete. The program will read the input string and print the vowels in the order they appear.
+
+**Full Solution Code :**
+
+```
+import java.util.Scanner;
+
+public class VowelPrinter {
+
+ public static boolean isVowel(char ch) {
+ // Convert the input character to lowercase
+ ch = Character.toLowerCase(ch);
+ // Check if the character is a vowel (a, e, i, o, or u) and return the result
+ return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u';
+ }
+
+ public static void main(String[] args) {
+ // Create a Scanner object to read input from the user
+ Scanner scanner = new Scanner(System.in);
+ // Read the input string from the user
+ String input = scanner.nextLine();
+ // Close the scanner object
+ scanner.close();
+ // Initialize an index variable with the value 0
+ int index = 0;
+
+ // Use a while loop to iterate through the characters of the input string
+ while (index < input.length()) {
+ // Get the character at the current index from the input string
+ char ch = input.charAt(index);
+ // Check if the character is a vowel using the isVowel method
+ if (isVowel(ch)) {
+ // If the character is a vowel, print it
+ System.out.print(ch);
+ }
+ // Increment the index variable by 1 to move to the next character
+ index++;
+ }
+ }
+}
+
+```
+
+## Student File
+
+```
+
+import java.util.Scanner;
+
+public class VowelPrinter {
+
+ public static boolean isVowel(char ch) {
+ // TODO: Convert the input character to lowercase
+ // TODO: Check if the character is a vowel (a, e, i, o, or u)
+ // TODO: Return true if the character is a vowel, otherwise return false
+ }
+
+ public static void main(String[] args) {
+ // Create a Scanner object to read input from the user
+ Scanner scanner = new Scanner(System.in);
+ // Read the input string from the user
+ String input = scanner.nextLine();
+ // Close the scanner object
+ scanner.close();
+ // Initialize an index variable with the value 0
+ int index = 0;
+
+ // TODO: Use a while loop to iterate through the characters of the input string
+ // TODO: Inside the loop, get the character at the current index
+ // TODO: Check if the character is a vowel using the isVowel method
+ // TODO: If the character is a vowel, print it
+ // TODO: Increment the index variable by 1
+ }
+}
+
+
+```
+
+## Solution File
+
+```
+
+ import java.util.Scanner;
+
+ public class VowelPrinter {
+
+ public static boolean isVowel(char ch) {
+ ch = Character.toLowerCase(ch);
+ return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u';
+ }
+
+ public static void main(String[] args) {
+ Scanner scanner = new Scanner(System.in);
+ String input = scanner.nextLine();
+ scanner.close();
+ int index = 0;
+ while (index < input.length()) {
+ char ch = input.charAt(index);
+ if (isVowel(ch)) {
+ System.out.print(ch);
+ }
+ index++;
+ }
+ }
+ }
+
+```
+
+## Evaluation File
+
+```
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+import java.util.logging.Logger;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+public class Evaluate {
+
+ private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
+ private final PrintStream originalOut = System.out;
+ private final Logger logger = Logger.getLogger(Evaluate.class.getName());
+
+ @BeforeEach
+ public void setUpStreams() {
+ System.setOut(new PrintStream(outContent));
+ }
+
+ @AfterEach
+ public void restoreStreams() {
+ System.setOut(originalOut);
+ }
+
+ @Test
+ public void test_vowel_printer_empty_string() {
+ System.setIn(new ByteArrayInputStream("\n".getBytes()));
+ VowelPrinter.main(new String[]{});
+ String actualOutput = outContent.toString().trim();
+ String expectedOutput = "";
+ logger.info("Actual Output: " + actualOutput);
+ logger.info("Expected Output: " + expectedOutput);
+ assertEquals(expectedOutput, actualOutput, "Should return empty string for empty input");
+ }
+
+ @Test
+ public void test_vowel_printer_no_vowels() {
+ System.setIn(new ByteArrayInputStream("xyz\n".getBytes()));
+ VowelPrinter.main(new String[]{});
+ String actualOutput = outContent.toString().trim();
+ String expectedOutput = "";
+ logger.info("Actual Output: " + actualOutput);
+ logger.info("Expected Output: " + expectedOutput);
+ assertEquals(expectedOutput, actualOutput, "Should return empty string for input with no vowels");
+ }
+
+ @Test
+ public void test_vowel_printer_all_vowels() {
+ System.setIn(new ByteArrayInputStream("aeiou\n".getBytes()));
+ VowelPrinter.main(new String[]{});
+ String actualOutput = outContent.toString().trim();
+ String expectedOutput = "aeiou";
+ logger.info("Actual Output: " + actualOutput);
+ logger.info("Expected Output: " + expectedOutput);
+ assertEquals(expectedOutput, actualOutput, "Should return all vowels for input with all vowels");
+ }
+
+ @Test
+ public void test_vowel_printer_mixed_input() {
+ System.setIn(new ByteArrayInputStream("Hello World\n".getBytes()));
+ VowelPrinter.main(new String[]{});
+ String actualOutput = outContent.toString().trim();
+ String expectedOutput = "eoo";
+ logger.info("Actual Output: " + actualOutput);
+ logger.info("Expected Output: " + expectedOutput);
+ assertEquals(expectedOutput, actualOutput, "Should return all vowels in the input string");
+ }
+}
+
+
+```
\ No newline at end of file
From 913d49aaff2e3e15bab3bf67843a295d9586fd39 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Wed, 3 May 2023 22:39:30 +0530
Subject: [PATCH 132/178] .
---
02-CodeChallenge/09-ReferenceTypes.md | 316 ++++++++++++++++++++++++++
1 file changed, 316 insertions(+)
diff --git a/02-CodeChallenge/09-ReferenceTypes.md b/02-CodeChallenge/09-ReferenceTypes.md
index 463abc47..e2421ded 100644
--- a/02-CodeChallenge/09-ReferenceTypes.md
+++ b/02-CodeChallenge/09-ReferenceTypes.md
@@ -302,4 +302,320 @@ public class Evaluate {
}
+```
+
+
+
+
+
+
+# Exercise 2 : Age Calculator using Java's LocalDate and Period classes
+
+## Problem Statement
+
+In this exercise, you are required to implement an `AgeCalculator` class that calculates a person's age based on their date of birth and the current date. The date of birth should be entered by the user in the format `YYYY-MM-DD`. You need to complete the `calculateAge` method.
+
+### Instructions
+
+1. Import the `LocalDate` and `Period` classes from the `java.time` package.
+2. Complete the `calculateAge` method by implementing the logic to calculate a person's age based on their date of birth and the current date.
+ - Use the `LocalDate.parse()` method to convert the birthDate string into a LocalDate object.
+ - Check if the currentDate is before the date of birth using the `isBefore()` method. If it is, return -1 to indicate an error.
+ - Check if the date of birth is before a specific date (e.g., `1900-01-01`). If it is, return -1 to indicate an error.
+ - Use the `Period.between()` method to calculate the difference between the date of birth and the current date in years.
+ - Return the calculated age.
+
+### Input Format
+
+- A string representing the user's date of birth in the format `YYYY-MM-DD`.
+
+### Output Format
+
+- If the input is invalid, print an error message: "Invalid input. Please enter a valid date in the format YYYY-MM-DD."
+- If the input is valid, print the person's age: "Your age is: X", where X is the calculated age.
+
+**Note**: Make sure to mention the `Period.between()`, `isBefore()`, and `LocalDate.parse()` methods in the instructions, as the student is not familiar with these methods.
+
+### Example
+
+**Input:**
+
+```
+Please enter your date of birth in YYYY-MM-DD format: 2000-05-01
+```
+
+**Output:**
+
+```
+Your age is: 23
+```
+
+**Explanation:** In this example, the user has entered their date of birth as `2000-05-01`. The current date is assumed to be `2023-05-03`. The difference between these two dates in years is 23 years. Hence, the output is "Your age is: 23".
+
+
+## Hints
+
+1. Use `LocalDate.parse()` method to convert the birthDate string into a LocalDate object.
+2. Use `isBefore()` method to check if one date is before another date.
+3. Use `Period.between()` method to calculate the difference between two dates in years.
+4. Make sure to return -1 in case of invalid input (e.g., when the date of birth is in the future or before a specific date such as `1900-01-01`).
+5. In the `main` method, the code to read input, calculate the current date, and call the `calculateAge` method is already provided.
+
+## Solution Explanation
+
+Here is the step-by-step explanation of the solution:
+
+1. In the `calculateAge` method, first, we check if the `birthDate` string is null or empty. If it is, we return -1 to indicate an error.
+
+ ```
+ if (birthDate == null || birthDate.isEmpty()) {
+ return -1;
+ }
+ ```
+
+2. Convert the `birthDate` string into a `LocalDate` object using the `LocalDate.parse()` method.
+
+ ```
+ LocalDate dob = LocalDate.parse(birthDate);
+ ```
+
+3. Check if the `currentDate` is before the date of birth using the `isBefore()` method. If it is, return -1 to indicate an error.
+
+ ```
+ if (currentDate.isBefore(dob)) {
+ return -1;
+ }
+```
+
+4. Check if the date of birth is before a specific date (e.g., `1900-01-01`). If it is, return -1 to indicate an error.
+
+ ```
+ if (dob.isBefore(LocalDate.of(1900, 1, 1))) {
+ return -1;
+ }
+ ```
+
+5. Use the `Period.between()` method to calculate the difference between the date of birth and the current date in years.
+
+ ```
+ return Period.between(dob, currentDate).getYears();
+ ```
+
+
+The `main` method is already provided in the student code. It takes care of reading the input, calculating the current date, calling the `calculateAge` method, and printing the age or an error message based on the calculated age.
+
+#### Here's the Full Solution Code:
+
+```
+import java.time.LocalDate;
+import java.time.Period;
+import java.util.Scanner;
+
+public class AgeCalculator {
+
+ public static int calculateAge(String birthDate, LocalDate currentDate) {
+ // Check if birthDate is null or empty
+ if (birthDate == null || birthDate.isEmpty()) {
+ return -1;
+ }
+
+ // Convert birthDate string to LocalDate object
+ LocalDate dob = LocalDate.parse(birthDate);
+
+ // Check if currentDate is before the date of birth
+ if (currentDate.isBefore(dob)) {
+ return -1;
+ }
+
+ // Check if the date of birth is before a specific date (e.g., 1900-01-01)
+ if (dob.isBefore(LocalDate.of(1900, 1, 1))) {
+ return -1;
+ }
+
+ // Calculate the difference between dob and currentDate in years using Period.between() method
+ return Period.between(dob, currentDate).getYears();
+ }
+
+ public static void main(String[] args) {
+ Scanner scanner = new Scanner(System.in);
+ System.out.print("Please enter your date of birth in YYYY-MM-DD format: ");
+ String birthDate = scanner.nextLine();
+ scanner.close();
+
+ // Get the current date
+ LocalDate currentDate = LocalDate.now();
+
+ // Calculate the age using the calculateAge method
+ int age = calculateAge(birthDate, currentDate);
+
+ // Print the age or an error message if age is negative
+ if (age < 0) {
+ System.out.println("Invalid input. Please enter a valid date in the format YYYY-MM-DD.");
+ } else {
+ System.out.println("Your age is: " + age);
+ }
+ }
+}
+```
+
+I hope this helps! Let me know if you have any questions.
+
+
+## Student File
+
+```
+import java.time.LocalDate;
+import java.time.Period;
+import java.util.Scanner;
+
+public class AgeCalculator {
+
+ public static int calculateAge(String birthDate, LocalDate currentDate) {
+ // Write your code to calculate the age based on the birthDate and currentDate
+ // You can use the Period.between() method to calculate the difference between two dates in years
+ // Return -1 if the input is invalid
+ }
+
+ public static void main(String[] args) {
+ Scanner scanner = new Scanner(System.in);
+ System.out.print("Please enter your date of birth in YYYY-MM-DD format: ");
+ String birthDate = scanner.nextLine();
+ scanner.close();
+
+ // Get the current date
+ LocalDate currentDate = LocalDate.now();
+
+ // Call the calculateAge method to calculate the age
+ int age = calculateAge(birthDate, currentDate);
+
+ // Print the age or an error message if age is negative
+ if (age < 0) {
+ System.out.println("Invalid input. Please enter a valid date in the format YYYY-MM-DD.");
+ } else {
+ System.out.println("Your age is: " + age);
+ }
+ }
+}
+
+```
+
+## Solution code
+
+```
+
+
+import java.time.LocalDate;
+import java.time.Period;
+import java.util.Scanner;
+
+public class AgeCalculator {
+
+ public static int calculateAge(String birthDate, LocalDate currentDate) {
+ if (birthDate == null || birthDate.isEmpty()) {
+ return -1;
+ }
+
+ LocalDate dob = LocalDate.parse(birthDate);
+
+
+ if (currentDate.isBefore(dob)) {
+ return -1;
+ }
+
+ if (dob.isBefore(LocalDate.of(1900, 1, 1))) {
+ return -1;
+ }
+
+
+ return Period.between(dob, currentDate).getYears();
+ }
+
+ public static void main(String[] args) {
+ Scanner scanner = new Scanner(System.in);
+ System.out.print("Please enter your date of birth in YYYY-MM-DD format: ");
+ String birthDate = scanner.nextLine();
+ scanner.close();
+
+ LocalDate currentDate = LocalDate.now();
+
+ int age = calculateAge(birthDate, currentDate);
+
+ if (age < 0) {
+ System.out.println("Invalid input. Please enter a valid date in the format YYYY-MM-DD.");
+ } else {
+ System.out.println("Your age is: " + age);
+ }
+ }
+}
+
+
+
+```
+
+## Evaluation File
+
+```
+import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import java.time.LocalDate;
+import java.util.logging.Logger;
+
+public class Evaluate {
+private final Logger logger = Logger.getLogger(Evaluate.class.getName());
+
+@Test
+public void test_valid_input(){
+ LocalDate currentDate = LocalDate.of(2022, 10, 1);
+ int age = AgeCalculator.calculateAge("2000-01-01", currentDate);
+ assertEquals(22, age, "Should return correct age for valid input");
+ logger.info("Actual Output: " + age);
+ logger.info("Expected Output: " + 22);
+}
+
+@Test
+public void test_invalid_input(){
+ LocalDate currentDate = LocalDate.of(2022, 10, 1);
+ int age = AgeCalculator.calculateAge("", currentDate);
+ assertEquals(-1, age, "Should return -1 for empty input");
+ logger.info("Actual Output: " + age);
+ logger.info("Expected Output: " + -1);
+
+ age = AgeCalculator.calculateAge(null, currentDate);
+ assertEquals(-1, age, "Should return -1 for null input");
+ logger.info("Actual Output: " + age);
+ logger.info("Expected Output: " + -1);
+
+ LocalDate futureDate = LocalDate.of(1999, 2, 1);
+ age = AgeCalculator.calculateAge("2000-01-01", futureDate);
+ assertEquals(-1, age, "Should return -1 for future date input");
+ logger.info("Actual Output: " + age);
+ logger.info("Expected Output: " + -1);
+}
+
+@Test
+public void test_edge_cases(){
+ LocalDate currentDate = LocalDate.of(2022, 10, 1);
+ int age = AgeCalculator.calculateAge("2000-10-01", currentDate);
+ assertEquals(22, age, "Should return correct age for edge case input (same birth date and current date)");
+ logger.info("Actual Output: " + age);
+ logger.info("Expected Output: " + 22);
+
+ age = AgeCalculator.calculateAge("1900-01-01", currentDate);
+ assertEquals(122, age, "Should return correct age for edge case input (very old birth date)");
+ logger.info("Actual Output: " + age);
+ logger.info("Expected Output: 122");
+
+ age = AgeCalculator.calculateAge("1901-01-01", currentDate);
+ assertEquals(121, age, "Should return correct age for edge case input (after 1900-01-01)");
+ logger.info("Actual Output: " + age);
+ logger.info("Expected Output: 121");
+
+ age = AgeCalculator.calculateAge("1899-12-31", currentDate);
+ assertEquals(-1, age, "Should not return correct age for edge case input (very old birth date)");
+ logger.info("Actual Output: " + age);
+ logger.info("Expected Output: -1");
+ }
+}
+
```
\ No newline at end of file
From 11adc123cec19251b4b321ada7333d794da78be2 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Wed, 3 May 2023 22:40:23 +0530
Subject: [PATCH 133/178] Update 08-Loops.md
---
02-CodeChallenge/08-Loops.md | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/02-CodeChallenge/08-Loops.md b/02-CodeChallenge/08-Loops.md
index 53ae1d9d..4e8bf5fa 100644
--- a/02-CodeChallenge/08-Loops.md
+++ b/02-CodeChallenge/08-Loops.md
@@ -245,7 +245,7 @@ In this exercise, you will complete a Java program that acts as a simple calcula
5. The loop should continue executing until the user selects option `3` (Exit). After the loop, close the `Scanner` object using `scanner.close()`.
-### Example Output
+#### Example Output
A sample interaction with the calculator should look like this:
@@ -302,7 +302,7 @@ Complete the `main` method in the provided student code, following the solution
Use the provided student code as a starting point, and complete the `main` method to implement the calculator's functionality.
-### Solution Explanation
+## Solution Explanation
To complete the `main` method inside the `SimpleCalculator` class, follow these steps:
From ed45d45cef7fd9f5dbe19f455277ac86d85bec03 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Thu, 4 May 2023 00:42:04 +0530
Subject: [PATCH 134/178] .
---
02-CodeChallenge/13-Generics.md | 220 ++++++++++++++++++++++++++++++++
1 file changed, 220 insertions(+)
create mode 100644 02-CodeChallenge/13-Generics.md
diff --git a/02-CodeChallenge/13-Generics.md b/02-CodeChallenge/13-Generics.md
new file mode 100644
index 00000000..f8295462
--- /dev/null
+++ b/02-CodeChallenge/13-Generics.md
@@ -0,0 +1,220 @@
+# Exercise 1: Implementing and Using a Generic Pair Class
+
+## Problem Statement
+
+In this exercise, you need to complete the implementation of a simple generic class called `GenericPair` that can store a pair of objects with different types. You will also use this class to create instances and print the pairs.
+
+You have been given an incomplete code file, and your task is to fill in the missing parts of the code.
+
+### Instructions
+
+1. Complete the constructor of the `GenericPair` class by assigning the constructor arguments to the corresponding instance variables.
+2. Implement the `getKey()` method that returns the `key` instance variable.
+3. Implement the `getValue()` method that returns the `value` instance variable.
+
+### Example Usage
+
+After completing the code, the `GenericPair` class should be used as follows:
+
+```
+GenericPair pair1 = new GenericPair<>("One", 1);
+System.out.println("Key: " + pair1.getKey() + ", Value: " + pair1.getValue());
+// Output: Key: One, Value: 1
+
+GenericPair pair2 = new GenericPair<>(2, 2.0);
+System.out.println("Key: " + pair2.getKey() + ", Value: " + pair2.getValue());
+// Output: Key: 2, Value: 2.0
+```
+
+After the student completes the implementation, the example output should look like this:
+
+```
+Key: One, Value: 1
+Key: 2, Value: 2.0
+```
+
+## Hints
+
+1. **Constructor**: Assign the constructor arguments to the instance variables `key` and `value` in the `GenericPair` class.
+
+```
+this.key = key;
+this.value = value;
+```
+
+2. **getKey() method**: Return the `key` instance variable.
+
+
+`return key;`
+
+3. **getValue() method**: Return the `value` instance variable.
+
+
+`return value;`
+
+## Solution Explanation
+
+The solution involves completing the implementation of the `GenericPair` class, which is a generic class that stores a pair of objects with different types. The class has two type parameters `K` and `V`, and two private instance variables called `key` and `value` of type `K` and `V` respectively.
+
+1. **Constructor**: The constructor takes two arguments, one of type `K` and another of type `V`. These arguments need to be assigned to the instance variables `key` and `value`. To do this, we use the `this` keyword, which refers to the current instance of the class:
+
+```
+this.key = key;
+this.value = value;
+```
+
+2. **getKey() method**: This method should return the `key` instance variable. It has a return type of `K` to match the type of the `key` instance variable:
+
+`return key;`
+
+3. **getValue() method**: This method should return the `value` instance variable. It has a return type of `V` to match the type of the `value` instance variable:
+
+`return value;`
+
+After completing these steps, the `GenericPair` class can be used to store and retrieve pairs of objects with different types, as demonstrated in the example usage.
+
+
+**Full Solution Code :**
+```
+public class GenericPairTest {
+ public static void main(String[] args) {
+ // Create a GenericPair object with String and Integer types
+ GenericPair pair1 = new GenericPair<>("One", 1);
+ // Print the key and value of the pair1 object
+ System.out.println("Key: " + pair1.getKey() + ", Value: " + pair1.getValue());
+ // Output: Key: One, Value: 1
+
+ // Create a GenericPair object with Integer and Double types
+ GenericPair pair2 = new GenericPair<>(2, 2.0);
+ // Print the key and value of the pair2 object
+ System.out.println("Key: " + pair2.getKey() + ", Value: " + pair2.getValue());
+ // Output: Key: 2, Value: 2.0
+ }
+
+ public static class GenericPair {
+ // Instance variables to store the key and value
+ private K key;
+ private V value;
+
+ // Constructor to initialize the key and value
+ public GenericPair(K key, V value) {
+ this.key = key;
+ this.value = value;
+ }
+
+ // Method to get the key
+ public K getKey() {
+ return key;
+ }
+
+ // Method to get the value
+ public V getValue() {
+ return value;
+ }
+ }
+}
+
+```
+
+## Student Code File
+
+```
+public class GenericPairTest {
+ public static void main(String[] args) {
+ GenericPair pair1 = new GenericPair<>("One", 1);
+ System.out.println("Key: " + pair1.getKey() + ", Value: " + pair1.getValue());
+ // Output: Key: One, Value: 1
+
+ GenericPair pair2 = new GenericPair<>(2, 2.0);
+ System.out.println("Key: " + pair2.getKey() + ", Value: " + pair2.getValue());
+ // Output: Key: 2, Value: 2.0
+ }
+
+ public static class GenericPair {
+ private K key;
+ private V value;
+
+ public GenericPair(K key, V value) {
+ // TODO: Assign the key and value to the instance variables
+
+ }
+
+ public K getKey() {
+ // TODO: Return the key
+ }
+
+ public V getValue() {
+ // TODO: Return the value
+ }
+ }
+}
+
+```
+
+
+## Solution File
+
+```
+
+public class GenericPairTest {
+ public static void main(String[] args) {
+ GenericPair pair1 = new GenericPair<>("One", 1);
+ System.out.println("Key: " + pair1.getKey() + ", Value: " + pair1.getValue());
+ // Output: Key: One, Value: 1
+
+ GenericPair pair2 = new GenericPair<>(2, 2.0);
+ System.out.println("Key: " + pair2.getKey() + ", Value: " + pair2.getValue());
+ // Output: Key: 2, Value: 2.0
+ }
+
+ public static class GenericPair {
+ private K key;
+ private V value;
+
+ public GenericPair(K key, V value) {
+ this.key = key;
+ this.value = value;
+ }
+
+ public K getKey() {
+ return key;
+ }
+
+ public V getValue() {
+ return value;
+ }
+ }
+}
+
+```
+
+## Evaluation File
+
+```
+import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import java.util.logging.Logger;
+
+public class Evaluate {
+ private static final Logger logger = Logger.getLogger(Evaluate.class.getName());
+
+ @Test
+ public void test_generic_pair_string_integer(){
+ GenericPairTest.GenericPair pair = new GenericPairTest.GenericPair<>("One", 1);
+ logger.info("Expected Key: One, Actual Key: " + pair.getKey());
+ logger.info("Expected Value: 1, Actual Value: " + pair.getValue());
+ assertEquals("One", pair.getKey(), "Key should be One");
+ assertEquals(1, pair.getValue(), "Value should be 1");
+ }
+
+ @Test
+ public void test_generic_pair_integer_double(){
+ GenericPairTest.GenericPair pair = new GenericPairTest.GenericPair<>(2, 2.0);
+ logger.info("Expected Key: 2, Actual Key: " + pair.getKey());
+ logger.info("Expected Value: 2.0, Actual Value: " + pair.getValue());
+ assertEquals(2, pair.getKey(), "Key should be 2");
+ assertEquals(2.0, pair.getValue(), "Value should be 2.0");
+ }
+}
+```
\ No newline at end of file
From aed13dfc0039255e2184afbf64f3dea716a0b805 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Thu, 4 May 2023 11:33:40 +0530
Subject: [PATCH 135/178] .
---
02-CodeChallenge/16-ExceptionHandling.md | 350 +++++++++++++++++++++++
1 file changed, 350 insertions(+)
create mode 100644 02-CodeChallenge/16-ExceptionHandling.md
diff --git a/02-CodeChallenge/16-ExceptionHandling.md b/02-CodeChallenge/16-ExceptionHandling.md
new file mode 100644
index 00000000..f590ad05
--- /dev/null
+++ b/02-CodeChallenge/16-ExceptionHandling.md
@@ -0,0 +1,350 @@
+# Exercise 1: Football Team Roster Management: Handling Player ID Uniqueness
+
+## Problem Statement
+
+You are given an incomplete Java code that represents a football team and its players. Your task is to complete the code so that it accomplishes the following objectives:
+
+1. Implement a constructor for the `Player` class with three parameters: `id`, `name`, and `position`.
+2. Complete the `addPlayer` method in the `Team` class to add a new player to the team. If a player with the same `id` already exists in the team, throw an `IllegalArgumentException` with the message "Duplicate player ID: " followed by the player's `id`.
+
+### Instructions
+
+1. Add an all-argument constructor for the `Player` class that takes `id`, `name`, and `position` as input and initializes the corresponding instance variables.
+2. Complete the `addPlayer` method in the `Team` class: a. Check if a player with the same `id` already exists in the `players` list. If it does, throw an `IllegalArgumentException` with the message "Duplicate player ID: " followed by the player's `id`. b. If there's no duplicate player `id`, add the player to the `players` list.
+
+### Example
+
+When you run the provided `main` method, your program should output:
+
+```
+Duplicate player ID: 2
+```
+
+### Input/Output Example
+
+#### Input
+
+The input will be taken from the provided `main` method, which includes the following player information:
+
+```
+team.addPlayer(new Player(1, "John Smith", "Quarterback"));
+team.addPlayer(new Player(2, "Mary Johnson", "Running back"));
+team.addPlayer(new Player(3, "Bob Williams", "Offensive lineman"));
+team.addPlayer(new Player(2, "Steve Martin", "Wide receiver"));
+```
+
+#### Output
+
+When you run the provided `main` method, your program should output:
+
+```
+Duplicate player ID: 2
+```
+
+In this example, the program throws an exception when trying to add a player with a duplicate `id` (2).
+
+
+## Hints
+
+1. To implement the `Player` constructor, use the provided class variables and the constructor's parameters to initialize the object.
+
+```
+public Player(int id, String name, String position) {
+ this.id = id;
+ this.name = name;
+ this.position = position;
+}
+```
+
+2. To complete the `addPlayer` method in the `Team` class: a. Iterate through the `players` list using a for-each loop. b. Compare the `id` of each player with the `id` of the player to be added. If there's a match, throw an `IllegalArgumentException` with the specified message. c. If no duplicates are found, add the player to the `players` list.
+
+
+
+## Solution Explanation
+
+In the given problem, we have two classes: `Player` and `Team`. The `Player` class represents an individual football player, and the `Team` class represents a football team composed of multiple players. The goal is to complete the code by implementing a constructor for the `Player` class and the `addPlayer` method in the `Team` class.
+
+1. Implement the constructor for the `Player` class:
+
+The constructor should take three parameters: `id`, `name`, and `position`. These parameters should be used to initialize the corresponding instance variables of the `Player` class.
+
+```
+public Player(int id, String name, String position) {
+ this.id = id;
+ this.name = name;
+ this.position = position;
+}
+```
+2. Complete the `addPlayer` method in the `Team` class:
+
+The `addPlayer` method should take a `Player` object as a parameter and add it to the `players` list, which represents the team. Before adding the player to the list, the method should check if a player with the same `id` already exists in the team. If there is a duplicate `id`, an `IllegalArgumentException` should be thrown with the message "Duplicate player ID: " followed by the player's `id`.
+
+```
+public void addPlayer(Player player) throws IllegalArgumentException {
+ int playerId = player.getId();
+ for (Player p : players) {
+ if (p.getId() == playerId) {
+ throw new IllegalArgumentException("Duplicate player ID: " + playerId);
+ }
+ }
+ players.add(player);
+}
+```
+With these changes, the complete solution code should look like the following:
+
+```
+import java.util.ArrayList;
+import java.util.List;
+
+public class FootballStats {
+
+ public static class Player {
+ public int id;
+ public String name;
+ public String position;
+
+ // Constructor that takes id, name, and position as input parameters and initializes the corresponding instance variables.
+ public Player(int id, String name, String position) {
+ this.id = id;
+ this.name = name;
+ this.position = position;
+ }
+
+ public int getId() {
+ return id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public String getPosition() {
+ return position;
+ }
+ }
+
+ public static class Team {
+ public List players;
+
+ // Constructor that initializes an empty list of players.
+ public Team() {
+ this.players = new ArrayList<>();
+ }
+
+ // Method to add a player to the team while checking for duplicate IDs.
+ public void addPlayer(Player player) throws IllegalArgumentException {
+ int playerId = player.getId();
+
+ // Iterate through the list of players to check for duplicates.
+ for (Player p : players) {
+ if (p.getId() == playerId) {
+ throw new IllegalArgumentException("Duplicate player ID: " + playerId);
+ }
+ }
+
+ // If no duplicates are found, add the player to the list.
+ players.add(player);
+ }
+ }
+
+ public static void main(String[] args) {
+ Team team = new Team();
+
+ // Add players to the team and handle any IllegalArgumentExceptions.
+ try {
+ team.addPlayer(new Player(1, "John Smith", "Quarterback"));
+ team.addPlayer(new Player(2, "Mary Johnson", "Running back"));
+ team.addPlayer(new Player(3, "Bob Williams", "Offensive lineman"));
+ team.addPlayer(new Player(2, "Steve Martin", "Wide receiver"));
+ } catch (IllegalArgumentException e) {
+ System.out.println(e.getMessage());
+ }
+ }
+}
+
+```
+
+When you run the provided `main` method, the program should output:
+
+```
+Duplicate player ID: 2
+```
+
+
+
+## Student File
+
+```
+import java.util.ArrayList;
+import java.util.List;
+
+public class FootballStats {
+
+ public static class Player {
+ public int id;
+ public String name;
+ public String position;
+
+ // Create Player all arg constructor
+ // TODO: Implement a constructor that takes id, name, and position as input parameters and initializes the corresponding instance variables.
+
+ public int getId() {
+ return id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public String getPosition() {
+ return position;
+ }
+ }
+
+ public static class Team {
+ public List players;
+
+ public Team() {
+ this.players = new ArrayList<>();
+ }
+
+ public void addPlayer(Player player) throws IllegalArgumentException {
+ // Complete the code
+ // TODO: Check if a player with the same id already exists in the players list.
+ // If it does, throw an IllegalArgumentException with the message "Duplicate player ID: " followed by the player's id.
+ // If there's no duplicate player id, add the player to the players list.
+ }
+ }
+
+ public static void main(String[] args) {
+ Team team = new Team();
+
+ try {
+ team.addPlayer(new Player(1, "John Smith", "Quarterback"));
+ team.addPlayer(new Player(2, "Mary Johnson", "Running back"));
+ team.addPlayer(new Player(3, "Bob Williams", "Offensive lineman"));
+ team.addPlayer(new Player(2, "Steve Martin", "Wide receiver"));
+ } catch (IllegalArgumentException e) {
+ System.out.println(e.getMessage());
+ }
+ }
+
+}
+
+```
+
+
+## Solution Code
+
+```
+
+
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class FootballStats {
+
+ public static class Player {
+ public int id;
+ public String name;
+ public String position;
+
+ public Player(int id, String name, String position) {
+ this.id = id;
+ this.name = name;
+ this.position = position;
+ }
+
+ public int getId() {
+ return id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public String getPosition() {
+ return position;
+ }
+ }
+
+ public static class Team {
+ public List players;
+
+ public Team() {
+ this.players = new ArrayList<>();
+ }
+
+ public void addPlayer(Player player) throws IllegalArgumentException {
+ int playerId = player.getId();
+ for (Player p : players) {
+ if (p.getId() == playerId) {
+ throw new IllegalArgumentException("Duplicate player ID: " + playerId);
+ }
+ }
+ players.add(player);
+ }
+ }
+
+ public static void main(String[] args) {
+ Team team = new Team();
+
+ try {
+ team.addPlayer(new Player(1, "John Smith", "Quarterback"));
+ team.addPlayer(new Player(2, "Mary Johnson", "Running back"));
+ team.addPlayer(new Player(3, "Bob Williams", "Offensive lineman"));
+ team.addPlayer(new Player(2, "Steve Martin", "Wide receiver"));
+ } catch (IllegalArgumentException e) {
+ System.out.println(e.getMessage());
+ }
+ }
+
+}
+
+
+
+
+```
+
+## Evaluation Code
+
+```
+import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import java.util.logging.Logger;
+
+public class Evaluate {
+ private final Logger logger = Logger.getLogger(Evaluate.class.getName());
+
+ @Test
+ public void test_add_player_to_team(){
+ FootballStats.Team team = new FootballStats.Team();
+ FootballStats.Player player = new FootballStats.Player(1, "John Smith", "Quarterback");
+ team.addPlayer(player);
+ assertTrue(team.players.contains(player), "Should add player to team");
+
+ logger.info("Actual Output: " + team.players.contains(player));
+ logger.info("Expected Output: " + true);
+ }
+
+ @Test
+ public void test_add_duplicate_player_to_team(){
+ FootballStats.Team team = new FootballStats.Team();
+ FootballStats.Player player1 = new FootballStats.Player(2, "John Smith", "Quarterback");
+ FootballStats.Player player2 = new FootballStats.Player(2, "Mary Johnson", "Running back");
+ team.addPlayer(player1);
+ try {
+ team.addPlayer(player2);
+ } catch (IllegalArgumentException e) {
+ assertTrue(e.getMessage().contains("Duplicate player ID"), "Should throw exception for duplicate player ID");
+
+ logger.info("Actual Output: " + e.getMessage());
+ logger.info("Expected Output: " + "Duplicate player ID: " + player2.getId());
+ }
+ }
+}
+
+
+```
\ No newline at end of file
From 092427b4f9511250db40c60a3562259ab88377f5 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Thu, 4 May 2023 11:57:18 +0530
Subject: [PATCH 136/178] .
---
02-CodeChallenge/14-FunctionalProgramming.md | 194 +++++++++++++++++++
1 file changed, 194 insertions(+)
create mode 100644 02-CodeChallenge/14-FunctionalProgramming.md
diff --git a/02-CodeChallenge/14-FunctionalProgramming.md b/02-CodeChallenge/14-FunctionalProgramming.md
new file mode 100644
index 00000000..f99917e5
--- /dev/null
+++ b/02-CodeChallenge/14-FunctionalProgramming.md
@@ -0,0 +1,194 @@
+# Exercise 1: SimpleCalculator: Implementing Basic Arithmetic Operations Using Lambda Expressions and Functional Interfaces
+
+
+## Problem Statement
+
+You are given an incomplete `SimpleCalculator` class that aims to perform basic arithmetic operations (addition, subtraction, and multiplication) using lambda expressions and a functional interface named `Calculator`. Your task is to complete the missing parts of the code.
+
+### Instructions
+
+1. Define the lambda expressions for the following arithmetic operations:
+
+ - Addition
+ - Subtraction
+ - Multiplication
+2. Implement the `performCalculation` method that takes a `Calculator` object, two integer values `a` and `b`, and returns the result of the calculation.
+
+
+### Steps
+
+1. Define the lambda expression for the addition operation. Replace the `null` value with a lambda expression that takes two integers `a` and `b` and returns the sum of the two numbers.
+
+2. Define the lambda expression for the subtraction operation. Replace the `null` value with a lambda expression that takes two integers `a` and `b` and returns the result of `a - b`.
+
+3. Define the lambda expression for the multiplication operation. Replace the `null` value with a lambda expression that takes two integers `a` and `b` and returns the result of `a * b`.
+
+4. Implement the `performCalculation` method. This method should accept a `Calculator` object and two integers `a` and `b`. It should return the result of the calculation performed by the `Calculator` object on `a` and `b`.
+
+## Hints
+
+1. Lambda expressions are anonymous functions that can be assigned to functional interfaces. To define a lambda expression, use the following syntax: `(parameter1, parameter2) -> expression`.
+
+2. For the addition operation, the lambda expression should add the two input parameters and return the result.
+
+3. For the subtraction operation, the lambda expression should subtract the second input parameter from the first and return the result.
+
+4. For the multiplication operation, the lambda expression should multiply the two input parameters and return the result.
+
+5. The `performCalculation` method should call the `calculate` method of the given `Calculator` object with the input integers `a` and `b` and return the result of the calculation.
+
+
+## Solution Explanation
+
+The solution involves defining lambda expressions for the arithmetic operations (addition, subtraction, and multiplication) and implementing the `performCalculation` method to use the `Calculator` functional interface.
+
+Here's the complete solution code with explanations:
+
+```
+public class SimpleCalculator {
+
+ @FunctionalInterface
+ public interface Calculator {
+ int calculate(int a, int b);
+ }
+
+ public static void main(String[] args) {
+ // Define the lambda expression for the addition operation
+ Calculator addition = (a, b) -> a + b;
+
+ // Define the lambda expression for the subtraction operation
+ Calculator subtraction = (a, b) -> a - b;
+
+ // Define the lambda expression for the multiplication operation
+ Calculator multiplication = (a, b) -> a * b;
+
+ // Test the calculator functionality
+ System.out.println("Addition: " + performCalculation(addition, 5, 3)); // Output: 8
+ System.out.println("Subtraction: " + performCalculation(subtraction, 5, 3)); // Output: 2
+ System.out.println("Multiplication: " + performCalculation(multiplication, 5, 3)); // Output: 15
+ }
+
+ // Implement the performCalculation method
+ public static int performCalculation(Calculator calculator, int a, int b) {
+ return calculator.calculate(a, b);
+ }
+}
+```
+
+1. Define the lambda expressions for the arithmetic operations:
+
+ - `Calculator addition = (a, b) -> a + b;` - The addition operation takes two integers `a` and `b` as input and returns their sum.
+ - `Calculator subtraction = (a, b) -> a - b;` - The subtraction operation takes two integers `a` and `b` as input and returns the result of `a - b`.
+ - `Calculator multiplication = (a, b) -> a * b;` - The multiplication operation takes two integers `a` and `b` as input and returns the result of `a * b`.
+2. Implement the `performCalculation` method:
+
+ - `public static int performCalculation(Calculator calculator, int a, int b)` - This method takes a `Calculator` object and two integers `a` and `b` as input.
+ - `return calculator.calculate(a, b);` - The method calls the `calculate` method of the given `Calculator` object with the input integers `a` and `b` and returns the result of the calculation.
+
+By using lambda expressions and the functional interface `Calculator`, the solution provides a simple way to perform basic arithmetic operations with a flexible and reusable design.
+
+
+## Student File
+
+```
+public class SimpleCalculator {
+
+ @FunctionalInterface
+ public interface Calculator {
+ int calculate(int a, int b);
+ }
+
+ public static void main(String[] args) {
+ // TODO: Define the lambda expression for the addition operation
+ Calculator addition = null;
+
+ // TODO: Define the lambda expression for the subtraction operation
+ Calculator subtraction = null;
+
+ // TODO: Define the lambda expression for the multiplication operation
+ Calculator multiplication = null;
+
+ // Test the calculator functionality
+ System.out.println("Addition: " + performCalculation(addition, 5, 3)); // Output: 8
+ System.out.println("Subtraction: " + performCalculation(subtraction, 5, 3)); // Output: 2
+ System.out.println("Multiplication: " + performCalculation(multiplication, 5, 3)); // Output: 15
+ }
+
+ // TODO: Implement the performCalculation method
+ public static int performCalculation(Calculator calculator, int a, int b) {
+ return 0;
+ }
+}
+
+
+```
+
+## Solution File
+
+```
+public class SimpleCalculator {
+
+ @FunctionalInterface
+ public interface Calculator {
+ int calculate(int a, int b);
+ }
+
+ public static void main(String[] args) {
+ // Define the lambda expression for the addition operation
+ Calculator addition = (a, b) -> a + b;
+
+ // Define the lambda expression for the subtraction operation
+ Calculator subtraction = (a, b) -> a - b;
+
+ // Define the lambda expression for the multiplication operation
+ Calculator multiplication = (a, b) -> a * b;
+
+ // Test the calculator functionality
+ System.out.println("Addition: " + performCalculation(addition, 5, 3)); // Output: 8
+ System.out.println("Subtraction: " + performCalculation(subtraction, 5, 3)); // Output: 2
+ System.out.println("Multiplication: " + performCalculation(multiplication, 5, 3)); // Output: 15
+ }
+
+ // Implement the performCalculation method
+ public static int performCalculation(Calculator calculator, int a, int b) {
+ return calculator.calculate(a, b);
+ }
+}
+
+```
+
+## Evaluation File
+
+```
+import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import java.util.logging.Logger;
+
+public class Evaluate {
+ private static final Logger logger = Logger.getLogger(Evaluate.class.getName());
+
+ @Test
+ public void test_addition() {
+ SimpleCalculator.Calculator addition = (a, b) -> a + b;
+ int result = SimpleCalculator.performCalculation(addition, 5, 3);
+ logger.info("Addition test: expected output: 8, actual output: " + result);
+ assertEquals(8, result, "Addition test failed");
+ }
+
+ @Test
+ public void test_subtraction() {
+ SimpleCalculator.Calculator subtraction = (a, b) -> a - b;
+ int result = SimpleCalculator.performCalculation(subtraction, 5, 3);
+ logger.info("Subtraction test: expected output: 2, actual output: " + result);
+ assertEquals(2, result, "Subtraction test failed");
+ }
+
+ @Test
+ public void test_multiplication() {
+ SimpleCalculator.Calculator multiplication = (a, b) -> a * b;
+ int result = SimpleCalculator.performCalculation(multiplication, 5, 3);
+ logger.info("Multiplication test: expected output: 15, actual output: " + result);
+ assertEquals(15, result, "Multiplication test failed");
+ }
+}
+```
\ No newline at end of file
From 5efc571b2cf480064f281cfa636a29a049bdb37b Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Thu, 4 May 2023 12:18:18 +0530
Subject: [PATCH 137/178] .
---
02-CodeChallenge/14-FunctionalProgramming.md | 325 +++++++++++++++++++
1 file changed, 325 insertions(+)
diff --git a/02-CodeChallenge/14-FunctionalProgramming.md b/02-CodeChallenge/14-FunctionalProgramming.md
index f99917e5..725c0142 100644
--- a/02-CodeChallenge/14-FunctionalProgramming.md
+++ b/02-CodeChallenge/14-FunctionalProgramming.md
@@ -191,4 +191,329 @@ public class Evaluate {
assertEquals(15, result, "Multiplication test failed");
}
}
+```
+
+
+
+
+
+
+# Exercise 2: COVID-19 Symptom Filter using Java Streams
+
+## Problem Statement
+
+You are tasked with creating a simple program to filter and display a list of COVID-19 symptoms. Given a list of symptoms with their names and a boolean flag indicating whether they are related to COVID-19, you must implement the following functionalities:
+
+1. Filter the list of symptoms to only include those that are COVID-19 symptoms.
+2. Print the COVID-19 symptoms.
+
+### Instructions and Steps
+
+1. In the `main` method, use the `stream()` method and the `filter()` function to filter the list of symptoms to only include those that are COVID-19 symptoms. The `filter()` function should use the `isCovidSymptom()` method from the `Symptom` class to determine if a symptom is related to COVID-19.
+2. After filtering the symptoms, use the `collect()` method to collect the filtered symptoms into a new `List` object named `covidSymptoms`.
+3. To print the COVID-19 symptoms, use the `forEach()` method on the `covidSymptoms` list. Inside the `forEach()` method, use a lambda expression to print the name of each symptom using the `getName()` method from the `Symptom` class.
+
+### Example
+
+Input:
+
+```
+List symptoms = Arrays.asList(
+ new Symptom("Fever", true),
+ new Symptom("Dry Cough", true),
+ new Symptom("Tiredness", true),
+ new Symptom("Sore Throat", false),
+ new Symptom("Headache", false),
+ new Symptom("Loss of Taste or Smell", true),
+ new Symptom("Difficulty Breathing", true)
+);
+```
+
+Output:
+
+```
+COVID-19 Symptoms:
+Fever
+Dry Cough
+Tiredness
+Loss of Taste or Smell
+Difficulty Breathing
+```
+
+
+### Hints
+
+1. Use the `stream()` method on the `symptoms` list to create a stream of symptoms.
+2. Apply the `filter()` function on the stream, and pass the `Symptom::isCovidSymptom` method reference as a predicate to filter COVID-19 symptoms.
+3. Collect the filtered symptoms into a new list using the `collect()` method and `Collectors.toList()` as an argument.
+4. Iterate over the `covidSymptoms` list using the `forEach()` method.
+5. Inside the `forEach()` method, use a lambda expression to print the name of each symptom using the `getName()` method from the `Symptom` class.
+
+
+## Solution Explanation
+
+In this solution, we'll use Java Streams to filter the list of symptoms and display only the COVID-19 related symptoms.
+
+1. First, we create a stream of symptoms using the `stream()` method on the `symptoms` list.
+
+```
+symptoms.stream()
+```
+
+2. Next, we apply the `filter()` function on the stream, and pass the `Symptom::isCovidSymptom` method reference as a predicate to filter COVID-19 symptoms.
+
+```
+symptoms.stream()
+ .filter(Symptom::isCovidSymptom)
+```
+
+3. We then collect the filtered symptoms into a new list using the `collect()` method and `Collectors.toList()` as an argument.
+
+```
+List covidSymptoms = symptoms.stream()
+ .filter(Symptom::isCovidSymptom)
+ .collect(Collectors.toList());
+ ```
+
+4. To print the COVID-19 symptoms, we iterate over the `covidSymptoms` list using the `forEach()` method.
+
+```
+covidSymptoms.forEach(symptom -> System.out.println(symptom.getName()));
+```
+
+5. Inside the `forEach()` method, we use a lambda expression to print the name of each symptom using the `getName()` method from the `Symptom` class.
+
+
+**Complete Solution:**
+
+```
+import java.util.Arrays;
+import java.util.List;
+import java.util.stream.Collectors;
+
+public class CovidSymptomChecker {
+ public static void main(String[] args) {
+ List symptoms = Arrays.asList(
+ new Symptom("Fever", true),
+ new Symptom("Dry Cough", true),
+ new Symptom("Tiredness", true),
+ new Symptom("Sore Throat", false),
+ new Symptom("Headache", false),
+ new Symptom("Loss of Taste or Smell", true),
+ new Symptom("Difficulty Breathing", true)
+ );
+
+ List covidSymptoms = symptoms.stream()
+ .filter(Symptom::isCovidSymptom)
+ .collect(Collectors.toList());
+
+ System.out.println("COVID-19 Symptoms:");
+ covidSymptoms.forEach(symptom -> System.out.println(symptom.getName()));
+ }
+
+ public static class Symptom {
+ private String name;
+ private boolean isCovidSymptom;
+
+ public Symptom(String name, boolean isCovidSymptom) {
+ this.name = name;
+ this.isCovidSymptom = isCovidSymptom;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public boolean isCovidSymptom() {
+ return isCovidSymptom;
+ }
+ }
+}
+```
+
+This code will output the following:
+
+```
+COVID-19 Symptoms:
+Fever
+Dry Cough
+Tiredness
+Loss of Taste or Smell
+Difficulty Breathing
+```
+
+
+## Student File
+
+```
+import java.util.Arrays;
+import java.util.List;
+import java.util.stream.Collectors;
+
+public class CovidSymptomChecker {
+ public static void main(String[] args) {
+ List symptoms = Arrays.asList(
+ new Symptom("Fever", true),
+ new Symptom("Dry Cough", true),
+ new Symptom("Tiredness", true),
+ new Symptom("Sore Throat", false),
+ new Symptom("Headache", false),
+ new Symptom("Loss of Taste or Smell", true),
+ new Symptom("Difficulty Breathing", true)
+ );
+
+ // TODO: Filter the list of symptoms to only include those that are COVID-19 symptoms
+ List covidSymptoms = null;
+
+ System.out.println("COVID-19 Symptoms:");
+ // TODO: Print the COVID-19 symptoms
+ }
+
+ public static class Symptom {
+ private String name;
+ private boolean isCovidSymptom;
+
+ public Symptom(String name, boolean isCovidSymptom) {
+ this.name = name;
+ this.isCovidSymptom = isCovidSymptom;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public boolean isCovidSymptom() {
+ return isCovidSymptom;
+ }
+ }
+}
+
+```
+
+
+## Solution File
+
+```
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.stream.Collectors;
+
+public class CovidSymptomChecker {
+ public static void main(String[] args) {
+ List symptoms = Arrays.asList(
+ new Symptom("Fever", true),
+ new Symptom("Dry Cough", true),
+ new Symptom("Tiredness", true),
+ new Symptom("Sore Throat", false),
+ new Symptom("Headache", false),
+ new Symptom("Loss of Taste or Smell", true),
+ new Symptom("Difficulty Breathing", true)
+ );
+
+ List covidSymptoms = symptoms.stream()
+ .filter(Symptom::isCovidSymptom)
+ .collect(Collectors.toList());
+
+ System.out.println("COVID-19 Symptoms:");
+ covidSymptoms.forEach(symptom -> System.out.println(symptom.getName()));
+ }
+
+ public static class Symptom {
+ private String name;
+ private boolean isCovidSymptom;
+
+ public Symptom(String name, boolean isCovidSymptom) {
+ this.name = name;
+ this.isCovidSymptom = isCovidSymptom;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public boolean isCovidSymptom() {
+ return isCovidSymptom;
+ }
+ }
+}
+
+
+```
+
+## Evaluation File
+
+```
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+import java.util.Arrays;
+import java.util.List;
+import java.util.logging.Logger;
+import java.util.stream.Collectors;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+public class Evaluate {
+ private static final Logger logger = Logger.getLogger(Evaluate.class.getName());
+
+ @Test
+ public void test_covid_symptoms() {
+ List symptoms = Arrays.asList(
+ new CovidSymptomChecker.Symptom("Fever", true),
+ new CovidSymptomChecker.Symptom("Dry Cough", true),
+ new CovidSymptomChecker.Symptom("Tiredness", true),
+ new CovidSymptomChecker.Symptom("Sore Throat", false),
+ new CovidSymptomChecker.Symptom("Headache", false),
+ new CovidSymptomChecker.Symptom("Loss of Taste or Smell", true),
+ new CovidSymptomChecker.Symptom("Difficulty Breathing", true)
+ );
+
+ List covidSymptoms = symptoms.stream()
+ .filter(CovidSymptomChecker.Symptom::isCovidSymptom)
+ .collect(Collectors.toList());
+
+ List expected = Arrays.asList("Fever", "Dry Cough", "Tiredness", "Loss of Taste or Smell", "Difficulty Breathing");
+ List actual = covidSymptoms.stream().map(CovidSymptomChecker.Symptom::getName).collect(Collectors.toList());
+
+ logger.info("Expected output: " + expected);
+ logger.info("Actual output: " + actual);
+
+ assertEquals(expected, actual, "Should return the correct list of COVID-19 symptoms");
+ }
+
+ private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
+ private final PrintStream originalOut = System.out;
+
+ @BeforeEach
+ public void setUpStreams() {
+ System.setOut(new PrintStream(outContent));
+ }
+
+ @AfterEach
+ public void restoreStreams() {
+ System.setOut(originalOut);
+ }
+
+ @Test
+ public void test_covid_symptoms_output() {
+ CovidSymptomChecker.main(new String[]{});
+
+ String expectedOutput = "COVID-19 Symptoms:" + System.lineSeparator()
+ + "Fever" + System.lineSeparator()
+ + "Dry Cough" + System.lineSeparator()
+ + "Tiredness" + System.lineSeparator()
+ + "Loss of Taste or Smell" + System.lineSeparator()
+ + "Difficulty Breathing" + System.lineSeparator();
+
+ logger.info("Expected printed output: " + expectedOutput.replace(System.lineSeparator(), "\\n"));
+ logger.info("Actual printed output: " + outContent.toString().replace(System.lineSeparator(), "\\n"));
+
+ assertEquals(expectedOutput, outContent.toString(), "Should print the correct list of COVID-19 symptoms");
+ }
+}
+
```
\ No newline at end of file
From 2544a1a5179bbe58553683e1ac750c1767faa7fa Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Thu, 4 May 2023 12:18:55 +0530
Subject: [PATCH 138/178] .
---
02-CodeChallenge/14-FunctionalProgramming.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/02-CodeChallenge/14-FunctionalProgramming.md b/02-CodeChallenge/14-FunctionalProgramming.md
index 725c0142..c9f08272 100644
--- a/02-CodeChallenge/14-FunctionalProgramming.md
+++ b/02-CodeChallenge/14-FunctionalProgramming.md
@@ -241,7 +241,7 @@ Difficulty Breathing
```
-### Hints
+## Hints
1. Use the `stream()` method on the `symptoms` list to create a stream of symptoms.
2. Apply the `filter()` function on the stream, and pass the `Symptom::isCovidSymptom` method reference as a predicate to filter COVID-19 symptoms.
From 91d03e9c59b4c1a7444e5d3700741808d365aeef Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Thu, 4 May 2023 16:45:00 +0530
Subject: [PATCH 139/178] .
---
02-CodeChallenge/10-ArraysAndArrayList.md | 349 ++++++++++++++++++++++
1 file changed, 349 insertions(+)
create mode 100644 02-CodeChallenge/10-ArraysAndArrayList.md
diff --git a/02-CodeChallenge/10-ArraysAndArrayList.md b/02-CodeChallenge/10-ArraysAndArrayList.md
new file mode 100644
index 00000000..09ac4f25
--- /dev/null
+++ b/02-CodeChallenge/10-ArraysAndArrayList.md
@@ -0,0 +1,349 @@
+# Exercise 1: Merging Two Integer Arrays
+
+## Problem Statement
+
+You are given two integer arrays. Your task is to implement a program that merges these two arrays into a single array while preserving the order of the elements from the input arrays. The program should use the `mergeArrays` method to merge the input arrays.
+
+### Instructions
+
+1. Read the size and elements of the first array from the user.
+2. Read the size and elements of the second array from the user.
+3. Implement the `mergeArrays` method that takes two integer arrays as input and returns a new integer array containing all the elements of both input arrays. The elements in the returned array should preserve their order from the input arrays.
+4. Call the `mergeArrays` method with the input arrays and store the result in a variable called `mergedArray`.
+5. Print the merged array.
+
+### Input
+
+- The size of the first array (1 <= size1 <= 10^3)
+- The elements of the first array (-10^3 <= array1[i] <= 10^3)
+- The size of the second array (1 <= size2 <= 10^3)
+- The elements of the second array (-10^3 <= array2[i] <= 10^3)
+
+### Output
+
+- The merged array containing all the elements from both input arrays, preserving their order.
+
+### Example
+
+Input:
+
+```
+Enter the size of the first array: 3
+Enter the elements of the first array:
+1 2 3
+Enter the size of the second array: 4
+Enter the elements of the second array:
+4 5 6 7
+```
+
+Output:
+
+```
+Merged array: [1, 2, 3, 4, 5, 6, 7]
+```
+
+## Hints
+
+**Hint 1:** Start by initializing the merged array with the combined length of both input arrays.
+
+**Hint 2:** Use two separate loops or a single loop with two indices to iterate over both input arrays and copy their elements into the merged array.
+
+**Hint 3:** Keep track of the index in the merged array, and update it after adding an element from one of the input arrays.
+
+**Hint 4:** Be sure to return the merged array at the end of the `mergeArrays` method.
+
+
+## Solution Explanation
+
+In the provided solution, we implement the `mergeArrays` method to merge two given integer arrays, preserving the order of their elements. Here's a step-by-step explanation of the solution:
+
+1. We first create a new `mergedArray` with the combined length of both input arrays: `int[] mergedArray = new int[array1.length + array2.length];`
+
+```
+public static int[] mergeArrays(int[] array1, int[] array2) {
+ int[] mergedArray = new int[array1.length + array2.length];
+ // ...
+}
+```
+2. Next, we initialize an index variable `i` to keep track of the position in the merged array.
+
+```
+public static int[] mergeArrays(int[] array1, int[] array2) {
+ int[] mergedArray = new int[array1.length + array2.length];
+ int i = 0;
+ // ...
+}
+```
+3. We use a `for` loop to iterate over the first input array (`array1`) and copy its elements into the merged array. We increment the index `i` after adding each element.
+
+```
+public static int[] mergeArrays(int[] array1, int[] array2) {
+ int[] mergedArray = new int[array1.length + array2.length];
+ int i = 0;
+
+ for (int element : array1) {
+ mergedArray[i++] = element;
+ }
+ // ...
+}
+```
+
+4. Similarly, we use another `for` loop to iterate over the second input array (`array2`) and copy its elements into the merged array, again incrementing the index `i` after adding each element.
+
+```
+public static int[] mergeArrays(int[] array1, int[] array2) {
+ int[] mergedArray = new int[array1.length + array2.length];
+ int i = 0;
+
+ for (int element : array1) {
+ mergedArray[i++] = element;
+ }
+
+ for (int element : array2) {
+ mergedArray[i++] = element;
+ }
+ // ...
+}
+```
+
+5. Finally, we return the `mergedArray` containing all the elements from both input arrays.
+
+```
+public static int[] mergeArrays(int[] array1, int[] array2) {
+ int[] mergedArray = new int[array1.length + array2.length];
+ int i = 0;
+
+ for (int element : array1) {
+ mergedArray[i++] = element;
+ }
+
+ for (int element : array2) {
+ mergedArray[i++] = element;
+ }
+
+ return mergedArray;
+}
+```
+
+This solution successfully merges the two input arrays while maintaining the order of their elements.
+
+
+**Full Solution Code:**
+```
+import java.util.Arrays;
+import java.util.Scanner;
+
+public class MergeArrays {
+ public static void main(String[] args) {
+ Scanner scanner = new Scanner(System.in);
+
+ System.out.print("Enter the size of the first array: ");
+ int size1 = scanner.nextInt();
+ int[] array1 = new int[size1];
+
+ System.out.println("Enter the elements of the first array: ");
+ for (int i = 0; i < size1; i++) {
+ array1[i] = scanner.nextInt();
+ }
+
+ System.out.print("Enter the size of the second array: ");
+ int size2 = scanner.nextInt();
+ int[] array2 = new int[size2];
+
+ System.out.println("Enter the elements of the second array: ");
+ for (int i = 0; i < size2; i++) {
+ array2[i] = scanner.nextInt();
+ }
+
+ int[] mergedArray = mergeArrays(array1, array2);
+
+ System.out.println("Merged array: " + Arrays.toString(mergedArray));
+
+ scanner.close();
+ }
+
+ // Merges two integer arrays into one array while preserving their order
+ public static int[] mergeArrays(int[] array1, int[] array2) {
+ // Create a new array with the combined length of both input arrays
+ int[] mergedArray = new int[array1.length + array2.length];
+
+ // Initialize an index variable to keep track of the position in the merged array
+ int i = 0;
+
+ // Iterate over the first input array and copy its elements into the merged array
+ for (int element : array1) {
+ mergedArray[i++] = element;
+ }
+
+ // Iterate over the second input array and copy its elements into the merged array
+ for (int element : array2) {
+ mergedArray[i++] = element;
+ }
+
+ // Return the merged array containing all the elements from both input arrays
+ return mergedArray;
+ }
+}
+
+```
+
+## Student File
+
+```
+import java.util.Arrays;
+import java.util.Scanner;
+
+public class MergeArrays {
+ public static void main(String[] args) {
+ Scanner scanner = new Scanner(System.in);
+
+ System.out.print("Enter the size of the first array: ");
+ int size1 = scanner.nextInt();
+ int[] array1 = new int[size1];
+
+ System.out.println("Enter the elements of the first array: ");
+ for (int i = 0; i < size1; i++) {
+ array1[i] = scanner.nextInt();
+ }
+
+ System.out.print("Enter the size of the second array: ");
+ int size2 = scanner.nextInt();
+ int[] array2 = new int[size2];
+
+ System.out.println("Enter the elements of the second array: ");
+ for (int i = 0; i < size2; i++) {
+ array2[i] = scanner.nextInt();
+ }
+
+ int[] mergedArray = mergeArrays(array1, array2);
+
+ System.out.println("Merged array: " + Arrays.toString(mergedArray));
+
+ scanner.close();
+ }
+
+ // TODO: Implement the mergeArrays method that takes two integer arrays as input
+ // TODO: The method should return a new integer array containing all the elements of both input arrays
+ // TODO: The elements in the returned array should preserve their order from the input arrays
+ public static int[] mergeArrays(int[] array1, int[] array2) {
+ // You should create a new array with the combined length of both input arrays
+ // Then, iterate over the first input array and copy its elements into the new merged array
+ // Next, iterate over the second input array and copy its elements into the merged array
+ // Finally, return the merged array containing all the elements from both input arrays
+ }
+}
+
+```
+
+## Solution File
+
+```
+
+import java.util.Arrays;
+import java.util.Scanner;
+
+public class MergeArrays {
+ public static void main(String[] args) {
+ Scanner scanner = new Scanner(System.in);
+
+ System.out.print("Enter the size of the first array: ");
+ int size1 = scanner.nextInt();
+ int[] array1 = new int[size1];
+
+ System.out.println("Enter the elements of the first array: ");
+ for (int i = 0; i < size1; i++) {
+ array1[i] = scanner.nextInt();
+ }
+
+ System.out.print("Enter the size of the second array: ");
+ int size2 = scanner.nextInt();
+ int[] array2 = new int[size2];
+
+ System.out.println("Enter the elements of the second array: ");
+ for (int i = 0; i < size2; i++) {
+ array2[i] = scanner.nextInt();
+ }
+
+ int[] mergedArray = mergeArrays(array1, array2);
+
+ System.out.println("Merged array: " + Arrays.toString(mergedArray));
+
+ scanner.close();
+ }
+
+ public static int[] mergeArrays(int[] array1, int[] array2) {
+ int[] mergedArray = new int[array1.length + array2.length];
+
+ int i = 0;
+
+ for (int element : array1) {
+ mergedArray[i++] = element;
+ }
+
+ for (int element : array2) {
+ mergedArray[i++] = element;
+ }
+
+ return mergedArray;
+ }
+}
+
+
+```
+
+## Evaluation File
+
+```
+import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+
+import java.util.Arrays;
+import java.util.logging.Logger;
+
+public class Evaluate {
+
+ private final static Logger logger = Logger.getLogger(Evaluate.class.getName());
+
+ @Test
+ public void test_merge_empty_arrays() {
+ int[] array1 = {};
+ int[] array2 = {};
+ int[] expected = {};
+ int[] actual = MergeArrays.mergeArrays(array1, array2);
+ logger.info("Expected: " + Arrays.toString(expected) + ", Actual: " + Arrays.toString(actual));
+ assertArrayEquals(expected, actual, "Should return an empty array when both input arrays are empty");
+ }
+
+ @Test
+ public void test_merge_one_empty_array() {
+ int[] array1 = {1, 2, 3};
+ int[] array2 = {};
+ int[] expected = {1, 2, 3};
+ int[] actual = MergeArrays.mergeArrays(array1, array2);
+ logger.info("Expected: " + Arrays.toString(expected) + ", Actual: " + Arrays.toString(actual));
+ assertArrayEquals(expected, actual, "Should return the non-empty array when one input array is empty");
+ }
+
+ @Test
+ public void test_merge_arrays() {
+ int[] array1 = {1, 3, 5};
+ int[] array2 = {2, 4, 6};
+ int[] expected = {1, 3, 5, 2, 4, 6};
+ int[] actual = MergeArrays.mergeArrays(array1, array2);
+ logger.info("Expected: " + Arrays.toString(expected) + ", Actual: " + Arrays.toString(actual));
+ assertArrayEquals(expected, actual, "Should merge two arrays in ascending order");
+ }
+
+ @Test
+ public void test_merge_arrays_with_duplicates() {
+ int[] array1 = {1, 3, 5, 5, 7};
+ int[] array2 = {2, 4, 5, 6, 8};
+ int[] expected = {1, 3, 5, 5, 7, 2, 4, 5, 6, 8};
+ int[] actual = MergeArrays.mergeArrays(array1, array2);
+ logger.info("Expected: " + Arrays.toString(expected) + ", Actual: " + Arrays.toString(actual));
+ assertArrayEquals(expected, actual, "Should merge two arrays in ascending order and include duplicates");
+ }
+}
+
+
+```
\ No newline at end of file
From ab0ff2bd69177fcfb91bdec3f67fae152f36469c Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Thu, 4 May 2023 17:00:20 +0530
Subject: [PATCH 140/178] .
---
02-CodeChallenge/10-ArraysAndArrayList.md | 247 ++++++++++++++++++++++
1 file changed, 247 insertions(+)
diff --git a/02-CodeChallenge/10-ArraysAndArrayList.md b/02-CodeChallenge/10-ArraysAndArrayList.md
index 09ac4f25..4f74aabe 100644
--- a/02-CodeChallenge/10-ArraysAndArrayList.md
+++ b/02-CodeChallenge/10-ArraysAndArrayList.md
@@ -346,4 +346,251 @@ public class Evaluate {
}
+```
+
+
+
+
+
+
+# Exercise 2: Correct and Calculate Average of Marks
+
+## Problem Statement
+
+You have been given an incomplete Java program called `CorrectAndAverageMarks`. The goal of this program is to correct an array of student marks by removing negative values and then calculating the average of the corrected marks.
+
+**Instructions**
+
+1. Complete the `correctAndAverageMarks` method that takes an integer array `marks` as input. This method should correct the marks by removing any negative values and then calculate the average of the corrected marks.
+2. To remove negative values, use an `ArrayList` to store the corrected marks. Loop through the `marks` array and add only non-negative values to the `correctedMarks` list.
+3. Calculate the sum of the corrected marks and then find the average by dividing the sum by the size of the `correctedMarks` list.
+4. If all values in the `marks` array are negative, return 0 as the average.
+5. Test your implementation with the given input array in the `main` method.
+6.
+**Input Format:**
+
+- An integer array `marks` of length n (1 ≤ n ≤ 10^5), where each element mark (mark: -10^5 ≤ mark ≤ 10^5) represents a student's mark.
+
+**Output Format:**
+
+- An integer value representing the average of the corrected marks.
+
+**Example:**
+
+Suppose the given input array is:
+
+```
+int[] input = {95, 80, -5, 70, 88, -15, 65};
+```
+
+The `CorrectAndAverageMarks` program should output:
+
+```
+Average of corrected marks: 79
+```
+
+**Explanation:**
+
+1. Remove negative values: {95, 80, 70, 88, 65}
+2. Calculate the sum of the corrected marks: 95 + 80 + 70 + 88 + 65 = 398
+3. Calculate the average: 398 / 5 = 79
+4. The output is 79
+
+
+## Hints
+
+**Hint 1:** Create an `ArrayList` to store the corrected marks (non-negative values).
+
+**Hint 2:** Iterate through the input array and add non-negative values to the `correctedMarks` ArrayList, and keep track of the sum of the non-negative values.
+
+**Hint 3:** Check if the `correctedMarks` ArrayList is empty. If it is, return 0 as the average.
+
+**Hint 4:** Calculate the average by dividing the sum of the non-negative values by the size of the `correctedMarks` ArrayList. Return the calculated average.
+
+## Solution Explanation
+
+In the given solution, we aim to calculate the average of the corrected marks by removing any negative values from the input array. Here's a step-by-step explanation with the code:
+
+1. Create a method called `correctAndAverageMarks` that takes an integer array `marks` as input.
+
+```
+public static int correctAndAverageMarks(int[] marks) {
+ // ...
+}
+```
+2. Inside the method, create an `ArrayList` called `correctedMarks` to store the non-negative values and initialize a variable `sum` to store the sum of the non-negative values.
+
+```
+ArrayList correctedMarks = new ArrayList<>();
+int sum = 0;
+```
+
+3. Iterate through the input array using a for-each loop. If the value is non-negative (greater than or equal to 0), add it to the `correctedMarks` ArrayList and update the `sum`.
+
+```
+for (int mark : marks) {
+ if (mark >= 0) {
+ correctedMarks.add(mark);
+ sum += mark;
+ }
+}
+```
+
+4. After iterating through the input array, check if the `correctedMarks` ArrayList is empty. If it is, return 0 as the average. Otherwise, calculate the average by dividing the `sum` by the size of the `correctedMarks` ArrayList and return the result.
+
+```
+if (correctedMarks.isEmpty()) {
+ return 0;
+} else {
+ return sum / correctedMarks.size();
+}
+```
+
+5. In the `main` method, call the `correctAndAverageMarks` method with the input array and print the returned average.
+
+```
+int average = correctAndAverageMarks(input);
+System.out.println("Average of corrected marks: " + average);
+```
+
+The complete solution code calculates the average of the corrected marks by removing negative values from the input array as described above.
+
+**Full Solution Code:**
+
+```
+import java.util.ArrayList;
+import java.util.Arrays;
+
+public class CorrectAndAverageMarks {
+ public static void main(String[] args) {
+ int[] input = {95, 80, -5, 70, 88, -15, 65};
+
+ // Call the correctAndAverageMarks method with the input array and print the returned average
+ int average = correctAndAverageMarks(input);
+ System.out.println("Average of corrected marks: " + average);
+ }
+
+ public static int correctAndAverageMarks(int[] marks) {
+ // Create an ArrayList to store the non-negative values
+ ArrayList correctedMarks = new ArrayList<>();
+
+ // Initialize a variable to store the sum of the non-negative values
+ int sum = 0;
+
+ // Iterate through the input array
+ for (int mark : marks) {
+ // If the value is non-negative, add it to the correctedMarks ArrayList and update the sum
+ if (mark >= 0) {
+ correctedMarks.add(mark);
+ sum += mark;
+ }
+ }
+
+ // If the correctedMarks ArrayList is empty, return 0 as the average
+ // Otherwise, calculate the average by dividing the sum by the size of the correctedMarks ArrayList and return the result
+ if (correctedMarks.isEmpty()) {
+ return 0;
+ } else {
+ return sum / correctedMarks.size();
+ }
+ }
+}
+
+```
+
+## Student File
+
+```
+import java.util.ArrayList;
+import java.util.Arrays;
+
+public class CorrectAndAverageMarks {
+ public static void main(String[] args) {
+ int[] input = {95, 80, -5, 70, 88, -15, 65};
+
+ int average = correctAndAverageMarks(input);
+ System.out.println("Average of corrected marks: " + average);
+ }
+
+ // TODO: Implement the correctAndAverageMarks method that takes an integer array as input
+ // TODO: The method should correct the marks by removing any negative values and then calculate the average
+ // TODO: If all values are negative, return 0 as the average
+ public static int correctAndAverageMarks(int[] marks) {
+
+ }
+}
+
+
+```
+
+
+## Solution File
+
+```
+
+ import java.util.ArrayList;
+ import java.util.Arrays;
+
+ public class CorrectAndAverageMarks {
+ public static void main(String[] args) {
+ int[] input = {95, 80, -5, 70, 88, -15, 65};
+ int average = correctAndAverageMarks(input);
+ System.out.println("Average of corrected marks: " + average);
+ }
+
+ public static int correctAndAverageMarks(int[] marks) {
+ ArrayList correctedMarks = new ArrayList<>();
+ int sum = 0;
+ for (int mark : marks) {
+ if (mark >= 0) {
+ correctedMarks.add(mark);
+ sum += mark;
+ }
+ }
+ if (correctedMarks.isEmpty()) {
+ return 0;
+ } else {
+ return sum / correctedMarks.size();
+ }
+ }
+ }
+
+
+
+```
+
+## Evaluation File
+
+```
+import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import java.util.logging.Logger;
+
+public class Evaluate {
+
+ private final static Logger logger = Logger.getLogger(Evaluate.class.getName());
+
+ @Test
+ public void test_correct_and_average_marks() {
+ int[] input1 = {95, 80, -5, 70, 88, -15, 65};
+ int expected1 = 79;
+ int actual1 = CorrectAndAverageMarks.correctAndAverageMarks(input1);
+ logger.info("Input 1 Expected: " + expected1 + ", Actual: " + actual1);
+ assertEquals(expected1, actual1, "Should return the correct average of corrected marks");
+
+ int[] input2 = {-5, -10, -15};
+ int expected2 = 0;
+ int actual2 = CorrectAndAverageMarks.correctAndAverageMarks(input2);
+ logger.info("Input 2 Expected: " + expected2 + ", Actual: " + actual2);
+ assertEquals(expected2, actual2, "Should return 0 when all marks are negative");
+
+ int[] input3 = {};
+ int expected3 = 0;
+ int actual3 = CorrectAndAverageMarks.correctAndAverageMarks(input3);
+ logger.info("Input 3 Expected: " + expected3 + ", Actual: " + actual3);
+ assertEquals(expected3, actual3, "Should return 0 when input array is empty");
+ }
+}
+
```
\ No newline at end of file
From f93f296e74b12dde49263f3cf6ac5c6d948dd7f2 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Fri, 5 May 2023 15:29:13 +0530
Subject: [PATCH 141/178] .
---
02-CodeChallenge/12-Collections.md | 292 +++++++++++++++++++++++++++++
1 file changed, 292 insertions(+)
create mode 100644 02-CodeChallenge/12-Collections.md
diff --git a/02-CodeChallenge/12-Collections.md b/02-CodeChallenge/12-Collections.md
new file mode 100644
index 00000000..bfcd43ba
--- /dev/null
+++ b/02-CodeChallenge/12-Collections.md
@@ -0,0 +1,292 @@
+
+# Exercise 1: Finding Duplicate Characters in a String using HashMap in Java
+
+## Problem Statement
+
+The given code defines a class `DuplicateCharFinder` which contains a method `findDuplicateChars()` to find the duplicate characters in a given input string using a `HashMap`. However, the method `findDuplicateChars()` is incomplete and needs to be implemented.
+
+### Instructions
+
+Please complete the implementation of the `findDuplicateChars()` method in the `DuplicateCharFinder` class.
+
+1. Iterate through the characters of the input string and add characters to the `charCountMap` with their counts.
+2. Iterate through the `charCountMap` and add characters with count > 1 to the `duplicateCharMap`.
+3. Return the `HashMap` object containing only duplicate characters.
+
+### Steps to complete the implementation
+
+1. Initialize two `HashMap` objects: `charCountMap` and `duplicateCharMap`.
+2. Iterate through the characters of the input string using a for-each loop:
+ - If the `charCountMap` contains the character, increment its count in the map.
+ - If the `charCountMap` does not contain the character, add it to the map with a count of 1.
+3. Iterate through the `charCountMap` using a for-each loop:
+ - If the count of a character in the `charCountMap` is greater than 1, add it to the `duplicateCharMap` with its count.
+4. Return the `duplicateCharMap`.
+
+
+### Example
+
+**Input:**
+
+```
+Enter a string: programming
+```
+
+**Output:**
+
+```
+Duplicate characters in the input string:
+r: 2
+g: 2
+m: 2
+```
+
+**Input:**
+
+```
+Enter a string: hello world
+```
+
+**Output:**
+
+```
+Duplicate characters in the input string:
+l: 3
+o: 2
+```
+
+
+## Hints
+
+1. To find duplicate characters in a string, you need to keep track of the count of each character.
+2. Use a `HashMap` to store the characters and their counts.
+3. Iterate through the characters of the input string and add them to the `HashMap`.
+4. While adding the characters to the `HashMap`, check if the character is already present in the map or not. If it's present, increment the count. If it's not present, add the character to the map with a count of 1.
+5. After adding all the characters to the `HashMap`, iterate through the map and add only those characters to a new `HashMap` which have a count greater than 1.
+6. Return the new `HashMap` containing only the duplicate characters.
+7. Use a Scanner object to read the input string from the user.
+8. Handle the case when no duplicate characters are found in the input string.
+
+
+
+## Solution Explanation
+
+The given problem requires us to find duplicate characters in a string. We can solve this problem using a `HashMap` to store the characters and their counts.
+
+We first initialize two `HashMap` objects: `charCountMap` and `duplicateCharMap`. We then iterate through the characters of the input string and add them to the `charCountMap`. While adding the characters, we check if the character is already present in the `charCountMap` or not. If it's present, we increment the count of the character. If it's not present, we add the character to the `charCountMap` with a count of 1.
+
+Once we have added all the characters to the `charCountMap`, we iterate through the map and add only those characters to the `duplicateCharMap` which have a count greater than 1. Finally, we return the `duplicateCharMap` which contains only the duplicate characters.
+
+In the `main()` method, we use a `Scanner` object to read the input string from the user. We then call the `findDuplicateChars()` method and store the result in the `resultMap`. We then iterate through the `resultMap` and print the duplicate characters along with their counts. If no duplicate characters are found in the input string, we print a message saying "No duplicate characters found."
+
+Here's the complete code solution:
+
+```
+import java.util.HashMap;
+import java.util.Map.Entry;
+import java.util.Scanner;
+
+public class DuplicateCharFinder {
+
+ public static HashMap findDuplicateChars(String input) {
+ HashMap charCountMap = new HashMap<>();
+ HashMap duplicateCharMap = new HashMap<>();
+
+ // Iterate through the characters of the input string and add them to the charCountMap
+ for (char c : input.toCharArray()) {
+ if (charCountMap.containsKey(c)) {
+ charCountMap.put(c, charCountMap.get(c) + 1);
+ } else {
+ charCountMap.put(c, 1);
+ }
+ }
+
+ // Iterate through the charCountMap and add only the duplicate characters to the duplicateCharMap
+ for (Entry entry : charCountMap.entrySet()) {
+ if (entry.getValue() > 1) {
+ duplicateCharMap.put(entry.getKey(), entry.getValue());
+ }
+ }
+
+ // Return the HashMap object containing only duplicate characters
+ return duplicateCharMap;
+ }
+
+ public static void main(String[] args) {
+ Scanner scanner = new Scanner(System.in);
+ System.out.print("Enter a string: ");
+ String input = scanner.nextLine();
+
+ // Call the findDuplicateChars method and store the result in a HashMap
+ HashMap resultMap = findDuplicateChars(input);
+
+ // Print the duplicate characters along with their counts
+ System.out.println("Duplicate characters in the input string:");
+ boolean hasDuplicate = false;
+ for (Entry entry : resultMap.entrySet()) {
+ System.out.println(entry.getKey() + ": " + entry.getValue());
+ hasDuplicate = true;
+ }
+
+ // Handle the case when no duplicate characters are found in the input string
+ if (!hasDuplicate) {
+ System.out.println("No duplicate characters found.");
+ }
+
+ scanner.close();
+ }
+}
+```
+
+
+## Student File
+
+```
+import java.util.HashMap;
+import java.util.Map.Entry;
+import java.util.Scanner;
+
+public class DuplicateCharFinder {
+
+ public static HashMap findDuplicateChars(String input) {
+ HashMap charCountMap = new HashMap<>();
+ HashMap duplicateCharMap = new HashMap<>();
+
+ // TODO: Write your code
+
+ // Return the HashMap object containing only duplicate characters
+ return duplicateCharMap;
+ }
+
+ public static void main(String[] args) {
+ Scanner scanner = new Scanner(System.in);
+ System.out.print("Enter a string: ");
+ String input = scanner.nextLine();
+
+ // Call the findDuplicateChars method and store the result in a HashMap
+ HashMap resultMap = findDuplicateChars(input);
+
+ // Print the duplicate characters along with their counts
+ System.out.println("Duplicate characters in the input string:");
+ boolean hasDuplicate = false;
+ for (Entry entry : resultMap.entrySet()) {
+ System.out.println(entry.getKey() + ": " + entry.getValue());
+ hasDuplicate = true;
+ }
+
+ // Handle the case when no duplicate characters are found in the input string
+ if (!hasDuplicate) {
+ System.out.println("No duplicate characters found.");
+ }
+
+ scanner.close();
+ }
+}
+
+```
+
+
+## Solution File
+
+```
+import java.util.HashMap;
+import java.util.Map.Entry;
+import java.util.Scanner;
+
+public class DuplicateCharFinder {
+
+ public static HashMap findDuplicateChars(String input) {
+ HashMap charCountMap = new HashMap<>();
+ HashMap duplicateCharMap = new HashMap<>();
+
+ // Iterate through the characters of the input string and add them to the charCountMap
+ for (char c : input.toCharArray()) {
+ if (charCountMap.containsKey(c)) {
+ charCountMap.put(c, charCountMap.get(c) + 1);
+ } else {
+ charCountMap.put(c, 1);
+ }
+ }
+
+ // Iterate through the charCountMap and add only the duplicate characters to the duplicateCharMap
+ for (Entry entry : charCountMap.entrySet()) {
+ if (entry.getValue() > 1) {
+ duplicateCharMap.put(entry.getKey(), entry.getValue());
+ }
+ }
+
+ // Return the HashMap object containing only duplicate characters
+ return duplicateCharMap;
+ }
+
+ public static void main(String[] args) {
+ Scanner scanner = new Scanner(System.in);
+ System.out.print("Enter a string: ");
+ String input = scanner.nextLine();
+
+ // Call the findDuplicateChars method and store the result in a HashMap
+ HashMap resultMap = findDuplicateChars(input);
+
+ // Print the duplicate characters along with their counts
+ System.out.println("Duplicate characters in the input string:");
+ boolean hasDuplicate = false;
+ for (Entry entry : resultMap.entrySet()) {
+ System.out.println(entry.getKey() + ": " + entry.getValue());
+ hasDuplicate = true;
+ }
+
+ // Handle the case when no duplicate characters are found in the input string
+ if (!hasDuplicate) {
+ System.out.println("No duplicate characters found.");
+ }
+
+ scanner.close();
+ }
+}
+
+```
+
+
+## Evaluation File
+
+```
+import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import java.util.HashMap;
+import java.util.logging.Logger;
+
+public class Evaluate {
+
+ private static final Logger logger = Logger.getLogger(Evaluate.class.getName());
+
+ @Test
+ public void test_find_duplicate_chars_with_duplicates() {
+ String input = "hello world";
+ HashMap expected = new HashMap<>();
+ expected.put('l', 3);
+ expected.put('o', 2);
+ HashMap actual = DuplicateCharFinder.findDuplicateChars(input);
+ logger.info("Expected: " + expected + ", Actual: " + actual);
+ assertEquals(expected, actual, "Should return the correct duplicate characters and their counts");
+ }
+
+ @Test
+ public void test_find_duplicate_chars_without_duplicates() {
+ String input = "abcdefg";
+ HashMap expected = new HashMap<>();
+ HashMap actual = DuplicateCharFinder.findDuplicateChars(input);
+ logger.info("Expected: " + expected + ", Actual: " + actual);
+ assertEquals(expected, actual, "Should return an empty HashMap when there are no duplicate characters");
+ }
+
+ @Test
+ public void test_find_duplicate_chars_with_empty_input() {
+ String input = "";
+ HashMap expected = new HashMap<>();
+ HashMap actual = DuplicateCharFinder.findDuplicateChars(input);
+ logger.info("Expected: " + expected + ", Actual: " + actual);
+ assertEquals(expected, actual, "Should return an empty HashMap when the input string is empty");
+ }
+}
+
+```
\ No newline at end of file
From 48c340b6bafccb0e0f2bff8e3b12989eda26be7b Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sun, 7 May 2023 00:17:58 +0530
Subject: [PATCH 142/178] .
---
01-Quiz/Q07-Conditionals.md | 0
01-Quiz/Q09-ReferenceTypes.md | 400 ++++++++++++++++++++++++++++++++++
2 files changed, 400 insertions(+)
create mode 100644 01-Quiz/Q07-Conditionals.md
create mode 100644 01-Quiz/Q09-ReferenceTypes.md
diff --git a/01-Quiz/Q07-Conditionals.md b/01-Quiz/Q07-Conditionals.md
new file mode 100644
index 00000000..e69de29b
diff --git a/01-Quiz/Q09-ReferenceTypes.md b/01-Quiz/Q09-ReferenceTypes.md
new file mode 100644
index 00000000..c27f7e57
--- /dev/null
+++ b/01-Quiz/Q09-ReferenceTypes.md
@@ -0,0 +1,400 @@
+## Step 01: Introducing Reference Types
+
+**Question 1**
+
+What is the purpose of reference variables in Java?
+
+A. To store primitive values
+B. To store objects on the Heap
+C. To store the memory location of an object
+
+**Answer: C**
+
+**Question 2**
+
+What is the main difference between reference types and primitive types in Java?
+
+A. Primitive types are stored on the Stack, reference types on the Heap B. Primitive types are stored on the Heap, reference types on the Stack C. Both are stored on the Heap
+
+**Answer: A**
+
+**Question 3**
+
+In the following code snippet, where are the objects `jupiter` and `dog` stored?
+
+```
+class Planet { ... }
+Planet jupiter = new Planet();
+jupiter ==> Planet@31a5c39e
+
+class Animal { ... }
+Animal dog = new Animal(12);
+dog ==> Animal@27c20538
+```
+
+A. Stack
+B. Heap
+C. Both Stack and Heap
+
+**Answer: B**
+
+
+## Step 02: References: Usage And Puzzles
+
+### Question 1
+
+What is the value of a reference variable that is not initialized by the programmer in Java?
+
+A. 0
+B. Empty
+C. Null
+
+Answer: C. Null
+
+### Question 2
+
+What happens when you compare two reference variables in Java?
+
+A. It compares the values stored inside the referenced objects.
+B. It compares the memory locations where the objects are stored.
+C. It compares the size of the objects.
+
+Answer: B. It compares the memory locations where the objects are stored.
+
+### Question 3
+
+What happens when you assign one reference variable to another in Java?
+
+A. It creates a copy of the entire referenced object.
+B. It only copies the reference.
+C. It creates a new object with the same values as the referenced object.
+
+Answer: B. It only copies the reference.
+
+
+## Step 03: Introducing String Quiz
+
+### Question 1
+
+What is a string in Java?
+
+A. A sequence of numbers
+**B. A sequence of characters**
+C. A sequence of symbols
+
+### Question 2
+
+What is the output of the following code:
+
+```
+String str = "Test";
+System.out.println(str.charAt(2));
+```
+
+A. 'e'
+**B. 's'**
+C. 'T'
+
+### Question 3
+
+What does the substring method of the String class return?
+
+A. A sequence of numbers
+**B. A sequence of characters**
+C. A sequence of symbols
+
+### Correct answers
+
+1. B. A sequence of characters
+2. B. 's'
+3. B. A sequence of characters
+
+## Step 04: Programming Exercise PE-01, And String Utilities
+
+### Quiz
+
+1. What does the `indexOf()` method in the String class do?
+2. A. Returns the position of a character in a string.
+3. B. Returns the starting position of a substring in a string.
+4. C. Both of the above.
+5. D. None of the above.
+
+ **Answer:** C. Both of the above.
+
+6. How does the `endsWith()` method determine if a string ends with a given suffix?
+- A. It returns the position of the last occurrence of the suffix in the string.
+- B. It returns true if the string ends with the given suffix, false otherwise.
+- C. It returns false if the string ends with the given suffix, true otherwise.
+- D. None of the above.
+
+ **Answer:** B. It returns true if the string ends with the given suffix, false otherwise.
+
+7. When using the `equals()` method, what is the result if the string is identical to the argument?
+- A. Returns true.
+- B. Returns false.
+- C. Returns the position of the first occurrence of the argument in the string.
+- D. None of the above.
+
+ **Answer:** A. Returns true.
+
+## Step 05: String Immutability
+
+1. What is the meaning of the word "immutable"?
+ - A. Changeable
+ - **B. Unchangeable**
+ - C. Mutable
+
+2. Can the value of a string object be changed after it is created?
+- A. Yes
+- **B. No**
+
+3. What does the method `concat()` do?
+- A. Changes the original value of a string object
+- **B. Returns a new string object by joining the contents of two string objects**
+- C. Trims a string object
+
+4. What happens to the original string object when the method `toUpperCase()` is used on it?
+- A. The original string object is changed to upper case
+- **B. The original string object remains unchanged, a new string object is returned with the changed value**
+
+6. What is the output of the following code:
+
+
+```
+String str = "in28Minutes";
+str = str.concat(" is awesome");
+```
+
+- **A. "in28Minutes is awesome"**
+- B. "in28Minutes"
+- C. "in28Minutes is awesome" and "in28Minutes"
+
+## Step 06: More String Utilities
+
+Q1. What is the result of the following code:
+
+```
+int i = 20;
+System.out.println("Value is " + i + 20);
+```
+
+ - A. Value is 40
+ - B. Value is 2020
+ - **C. Value is 2040**
+
+Q2. What is the result of the following code:
+
+```
+String.join(",", "2", "3", "4");
+```
+
+ - **A. "2,3,4"**
+ - B. "23,4"
+ - C. "234"
+
+Q3. What is the result of the following code:
+
+```
+"abcd".replace("ab", "xyz");
+```
+
+ - **A. "xyzcd"**
+ - B. "xyzabcd"
+ - C. "abcdxyz"
+
+
+
+
+## Step 07: Storing mutable text
+
+Question 1: What is the difference between StringBuffer and StringBuilder?
+
+- A. StringBuffer is mutable while StringBuilder is immutable
+- B. StringBuilder is mutable while StringBuffer is immutable
+- C. Both StringBuffer and StringBuilder are immutable
+
+Answer: B. StringBuilder is mutable while StringBuffer is immutable
+
+Question 2: What is the main advantage of using StringBuilder over StringBuffer?
+
+A. StringBuilder is thread-safe
+B. StringBuilder offers better performance in both execution-time and memory usage
+C. StringBuilder is a built-in class in Java
+
+Answer: B. StringBuilder offers better performance in both execution-time and memory usage
+
+Question 3: Can we modify a string literal using StringBuffer?
+
+A. Yes, we can modify a string literal using StringBuffer
+B. No, we cannot modify a string literal using StringBuffer
+C. It depends on the situation
+
+Answer: B. No, we cannot modify a string literal using StringBuffer
+
+
+
+
+## Step 08: Introducing Wrapper Classes
+
+Question 1: What is the purpose of using Wrapper Classes in Java?
+
+A. To access type information about the corresponding primitive type
+B. To promote primitive data to an object reference type
+C. To move primitive type data around data structures
+
+Answer: B. To promote primitive data to an object reference type
+
+Question 2: What is Auto-Boxing in Java?
+
+A. The process of promoting primitive data to an object reference type
+B. The process of converting an object reference type to a primitive data type
+C. The process of converting a primitive data type to an object reference type
+
+Answer: C. The process of converting a primitive data type to an object reference type
+
+Question 3: Can we modify the value of a wrapper class once it is assigned?
+
+A. Yes, we can modify the value of a wrapper class
+B. No, the value of a wrapper class is immutable
+C. It depends on the type of wrapper class being used.
+
+Answer: B. No, the value of a wrapper class is immutable
+
+
+
+## Step 09: Creating Wrapper Objects
+
+
+1. What are Wrapper Classes in Java?
+- A. Classes that provide a mechanism to convert primitive data types into objects
+- B. Classes that provide a mechanism to convert objects into primitive data types
+- C. Both of the above
+- D. None of the above
+**Answer: C. Both of the above**
+
+2. What is the difference between creating a Wrapper object using 'new' and 'valueOf()'?
+- A. There is no difference
+- B. 'new' creates a new object every time, whereas 'valueOf()' reuses existing objects with the same value
+- C. 'new' reuses existing objects with the same value, whereas 'valueOf()' creates a new object every time
+- D. None of the above
+**Answer: B. 'new' creates a new object every time, whereas 'valueOf()' reuses existing objects with the same value**
+
+3. Are Wrapper Classes mutable in Java?
+- A. Yes
+- B. No
+- C. Depends on the implementation
+- D. None of the above
+**Answer: B. No**
+
+
+
+
+## Step 10: Auto-Boxing, And Some Wrapper Constants
+
+1. What is Auto-Boxing in Java?
+- A. A feature that provides new functionality to the Java language
+- B. A mechanism to make code more readable
+- **C. A mechanism to upgrade a primitive data type to its corresponding object type**
+- D. None of the above
+
+2. What is the mechanism used by Auto-Boxing in Java?
+- A. It uses the 'new' operator to create new objects every time
+- **B. It uses the 'valueOf()' method to create objects**
+- C. It uses the 'toString()' method to create objects
+- D. None of the above
+
+3. Are there any constants available on Wrapper Classes in Java to check the size and range of values they can store?
+- A. No
+- **B. Yes**
+- C. Depends on the implementation
+- D. None of the above
+
+
+## Step 11: The Java Date API Quiz
+
+1. What is the main purpose of the Java Date API?
+- a. To perform arithmetic operations on date and time objects
+- b. To provide an interface for date and time classes
+- c. To provide a framework for date and time classes
+- d. To provide a library for date and time classes
+
+ Answer: b
+
+2. What is the main difference between LocalDate, LocalTime, and LocalDateTime?
+- a. They are used for different purposes
+- b. They are different classes in Java
+- c. They are used to represent different values for date and time
+- d. They are used for different date and time formats
+
+ Answer: c
+
+3. What is the difference between the `LocalDate.now()` and `LocalDate.of()` methods in the Java Date API?
+- a. `LocalDate.now()` returns the current date and time, while `LocalDate.of()` returns a specific date and time
+- b. `LocalDate.now()` returns the current date, while `LocalDate.of()` returns a specific date
+- c. `LocalDate.now()` returns the current time, while `LocalDate.of()` returns a specific time
+- d. `LocalDate.now()` returns a date and time object, while `LocalDate.of()` returns a date object
+
+ Answer: b
+
+
+## Step 12: Playing With java.time.LocalDate Quiz
+
+1. What information can you retrieve from a LocalDate object?
+- a. Date information such as Day/Month/Year and related attributes
+- b. Time information such as Hour/Minute/Second and related attributes
+- c. Both date and time information
+- d. None of the above
+
+ Answer: a
+
+3. Are LocalDate, LocalTime, and LocalDateTime objects mutable? a. Yes b. No
+
+ Answer: b
+
+4. What is the result of the following code snippet?
+
+
+```
+LocalDate today = LocalDate.now();
+LocalDate tomorrow = today.plusDays(1);
+System.out.println(today.isBefore(tomorrow));
+```
+
+a. True
+b. False
+c. Error
+
+Answer: a
+
+## Step 13: Comparing LocalDate Objects Quiz
+
+1. What is the purpose of the `isBefore()` and `isAfter()` methods in the Java Date API?
+- a. To compare the order of two LocalDate objects
+- b. To determine if a LocalDate object is earlier or later than a specific date
+- c. To compare the value of two LocalDate objects
+- d. To determine if a LocalDate object is equal to a specific date
+
+ Answer: a
+
+3. What is the result of the following code snippet?
+
+
+```
+LocalDate today = LocalDate.now();
+LocalDate yesterday = LocalDate.of(2018, 01, 31);
+System.out.println(today.isAfter(yesterday));
+```
+
+a. True
+b. False
+c. Error
+
+Answer: a
+
+3. Can you compare LocalTime and LocalDateTime objects using the `isBefore()` and `isAfter()` methods?
+- a. Yes
+- b. No
+
+
+
+`Answer: a`
\ No newline at end of file
From 6c8e3db47df6cb2ff2c39084e3d8f43daacaeff1 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sun, 7 May 2023 00:26:21 +0530
Subject: [PATCH 143/178] .
---
01-Quiz/Q07-Conditionals.md | 415 ++++++++++++++++++++++++++++++++++++
1 file changed, 415 insertions(+)
diff --git a/01-Quiz/Q07-Conditionals.md b/01-Quiz/Q07-Conditionals.md
index e69de29b..0ad20143 100644
--- a/01-Quiz/Q07-Conditionals.md
+++ b/01-Quiz/Q07-Conditionals.md
@@ -0,0 +1,415 @@
+## Step 01: The if and if-else Conditionals:
+
+1. What is the if statement used for?
+- a) To execute some code when a boolean condition is true
+- b) To execute some code when a boolean condition is false
+- c) To execute some code regardless of the boolean condition
+
+Answer: a)
+
+2. What is the difference between if and if-else statements?
+- a) There is no difference, they do the same thing
+- b) If statement executes code only when the condition is true, whereas if-else statement executes code when the condition is false
+- c) If statement executes code only when the condition is false, whereas if-else statement executes code when the condition is true
+
+Answer: b)
+
+3. What is the output of the following code snippet?
+
+```
+int i = 10;
+if(i < 5) {
+ System.out.println("i is less than 5");
+} else if(i > 20) {
+ System.out.println("i is greater than 20");
+} else {
+ System.out.println("i is between 5 and 20");
+}
+```
+a) i is less than 5
+b) i is greater than 20
+c) i is between 5 and 20
+
+Answer: c)
+
+
+
+## Step 02: The if-else if-else Conditional:
+
+1. What is the purpose of the if-else if-else statement?
+- a) To execute some code when a boolean condition is true
+- b) To execute some code when multiple conditions are true
+- c) To execute some code when one and only one condition is true
+
+Answer: c)
+
+2. What happens if multiple conditions in the if-else if-else statement evaluate to true?
+- a) All corresponding code blocks are executed
+- b) Only the first corresponding code block is executed
+- c) Only the last corresponding code block is executed
+
+Answer: b)
+
+3. What is the output of the following code snippet?
+
+```
+int i = 15;
+if(i < 5) {
+ System.out.println("i is less than 5");
+} else if(i > 20) {
+ System.out.println("i is greater than 20");
+} else if(i < 10) {
+ System.out.println("i is less than 10");
+} else {
+ System.out.println("i is between 10 and 20");
+}
+```
+
+- a) i is less than 5
+- b) i is greater than 20
+- c) i is less than 10
+- d) i is between 10 and 20
+
+Answer: d)
+
+
+## Step 03: Puzzles on if:
+
+1. What is the output of the following code snippet?
+
+```
+public static void puzzleOne() {
+ int k = 15;
+ if(k > 20) {
+ System.out.println(1);
+ } else if(k > 10) {
+ System.out.println(2);
+ } else if(k < 20) {
+ System.out.println(3);
+ } else {
+ System.out.println(4);
+ }
+}
+```
+a) 1
+b) 2
+c) 3
+d) 4
+
+Answer: b)
+
+2. What is the output of the following code snippet?
+
+```
+public static void puzzleTwo() {
+ int l = 15;
+ if(l < 20)
+ System.out.println("l < 20");
+ if(l > 20)
+ System.out.println("l > 20");
+ else
+ System.out.println("Who Am I?");
+}
+```
+
+a) l < 20
+b) l > 20
+c) Who Am I?
+
+Answer: c)
+
+3. What is the output of the following code snippet?
+
+```
+public static void puzzleThree() {
+ int m = 15;
+ if(m > 20)
+ if(m < 20)
+ System.out.println("m > 20"); else
+ System.out.println("Who Am I?");
+}
+```
+
+a) m > 20
+b) Who Am I?
+c) Nothing is printed.
+
+Answer: c)
+
+4. What is the output of the following code snippet?
+
+```
+int i = 0;
+if(i) {
+ System.out.println("i");
+}
+```
+
+a) i
+b) Compiler Error
+c) Nothing is printed.
+
+Answer: b)
+
+5. What is the output of the following code snippet?
+
+```
+public static void puzzleFive() {
+ int number = 5;
+ if(number < 0)
+ number = number + 10;
+ number++;
+ System.out.println(number);
+}
+```
+
+a) 4
+b) 5
+c) 6
+
+Answer: c)
+
+
+## Step 04: Reading User Input
+
+1. What is the purpose of using the Scanner class in Java?
+- a) To scan user input from the console
+- b) To read input from a file
+- c) To generate random numbers
+
+Answer: a
+
+2. What do you need to pass as a parameter to the Scanner constructor?
+3. - a) System.in
+4. b) System.out
+5. c) System.error
+
+Answer: a
+
+3. How do you read an integer input from the console using the Scanner class?
+- a) scanner.nextInt()
+- b) scanner.readInt()
+- c) scanner.getInt()
+
+Answer: a
+
+
+## Step : 5
+
+Here are three multiple choice questions based on the step:
+
+1. What is the purpose of the following code snippet?
+
+```
+Scanner scanner = new Scanner(System.in);
+```
+
+a) To initialize the Scanner class
+b) To import the Scanner class
+c) To create an instance of the Scanner class
+
+Answer: c) To create an instance of the Scanner class
+
+2. What does the following line of code do?
+
+```
+int number1 = Scanner.nextInt();
+```
+
+a) Imports the next integer from the keyboard
+b) Initializes the value of `number1` to the next integer from the keyboard
+c) Creates an instance of the `nextInt` method
+
+Answer: b) Initializes the value of `number1` to the next integer from the keyboard
+
+3. What does the following code snippet do?
+
+```
+System.out.println("Your Inputs Are:");
+System.out.println("Number1: " + number1);
+System.out.println("Number2: " + number2);
+System.out.println("Choice: " + choice);
+```
+
+a) Imports the values of `number1`, `number2`, and `choice` from the keyboard
+b) Writes the values of `number1`, `number2`, and `choice` to the console
+c) Initializes the values of `number1`, `number2`, and `choice`
+
+Answer: b) Writes the values of `number1`, `number2`, and `choice` to the console
+
+# Step 06: Menu-Challenge - Reading Input, Computing Result, Displaying Output
+
+## Quiz
+
+1. What is the purpose of the if-else-else if statement in the code?
+- a. To check for 4 favorable conditions
+- b. To handle invalid operation choice
+- c. To handle both favorable conditions and invalid operation choice
+- d. None of the above
+
+Answer: c. To handle both favorable conditions and invalid operation choice
+
+2. What does the statement "System.out.println("Result = " + (number1 + number2));" do in the code?
+- a. Prints the sum of number1 and number2
+- b. Prints the difference of number1 and number2
+- c. Prints the product of number1 and number2
+- d. Prints the quotient of number1 and number2
+
+Answer: a. Prints the sum of number1 and number2
+
+3. What is the output when choice is 5?
+- a. Result = 55
+- b. Invalid Operation
+- c. Number1: 25
+- d. Number2: 35
+
+Answer: b. Invalid Operation
+
+## Step 07: Introducing switch
+
+### Quiz 1
+
+Which of the following is NOT true about a switch statement in Java?
+
+A) A switch statement is used to test multiple conditions
+
+B) The default clause is executed when none of the cases match
+
+C) The switch statement can handle the default possibility
+
+D) The switch statement is used to test only one condition
+
+Answer: D
+
+### Quiz 2
+
+What is the purpose of the break statement in a switch statement in Java?
+
+A) To break out of the switch after a successful match
+
+B) To continue to the next case in the switch
+
+C) To stop the execution of the program
+
+D) To continue to the default clause in the switch
+
+Answer: A
+
+### Quiz 3
+
+What will the following code snippet output in Java?
+
+```
+int number = 2;
+switch(number) {
+ case 1:
+ System.out.println(1);
+ case 2:
+ System.out.println(2);
+ case 3:
+ System.out.println(3);
+ default:
+ System.out.println("default");
+}
+```
+
+A) 1
+
+B) 2
+
+C) 3
+
+D) 1, 2, 3, default
+
+Answer: D
+
+
+## Step 09: Comparing The if Family, And switch
+
+### Quiz
+
+1. What type of conditions can be evaluated using an if-family conditional?
+- a. Only boolean conditions
+- b. Only integer values
+- c. Both boolean and integer values
+- d. None of the above
+
+ Correct Answer: a. Only boolean conditions
+
+2. What is the advantage of using a switch conditional over an if-family conditional?
+- a. More readable and compact
+- b. Can be used to check for only integer values
+- c. More strict rules
+- d. More versatile
+
+ Correct Answer: a. More readable and compact
+
+3. What is the disadvantage of using a switch conditional over an if-family conditional? -
+- a. Can lead to subtle errors in the program
+- b. More versatile
+- c. Can only check for boolean conditions
+- d. Not as strict as if-family conditional
+
+ Correct Answer: a. Can lead to subtle errors in the program
+
+
+
+## Step 10: Programming Exercise PE-03
+
+### Question 1
+
+What is the name of the day represented by the number `3` in the `determineNameOfDay` method?
+
+A. Monday
+B. Tuesday
+C. Wednesday
+D. Thursday
+
+Correct answer: C. Wednesday
+
+### Question 2
+
+What is the name of the month represented by the number `9` in the `determinenameofMonth` method?
+
+A. January
+B. February
+C. March
+D. September
+
+Correct answer: D. September
+
+### Question 3
+
+Is the day represented by the number `1` considered to be a week day in the `isWeekDay` method?
+
+A. Yes
+B. No
+
+Correct answer: A. Yes
+
+
+## Step 12: Introducing ?:, The Ternary Operator
+
+#### Question 1:
+
+What is the purpose of the ternary operator ?: in Java?
+
+A. To perform addition of two operands
+B. To perform subtraction of two operands
+**C. To perform conditional operations**
+
+#### Question 2:
+
+What should be the return type of both expressions in the ternary operator ?: in Java?
+
+A. Both expressions can return any type of value
+B. Both expressions should return different types of value
+**C. Both expressions should return values of the same type**
+
+#### Question 3:
+
+What is the syntax of the ternary operator ?: in Java?
+
+A. result = (expression-if-condition-true ? condition : expression:if-condition-false);
+B. result = (expression-if-condition-false ? condition : expression-if-condition-true);
+**C. result = (condition ? expression-if-condition-true : expression-if-condition-false);**
\ No newline at end of file
From 117eb74b576c3cbfcf975bf0c1993cb94357b41d Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sun, 7 May 2023 00:35:09 +0530
Subject: [PATCH 144/178] .
---
...-IntroductionToObjectOrientedProgrammin.md | 720 ------------------
Archive/Ref.md | 62 --
txt_help.md | 62 --
3 files changed, 844 deletions(-)
delete mode 100644 Archive/05-IntroductionToObjectOrientedProgrammin.md
delete mode 100644 Archive/Ref.md
delete mode 100644 txt_help.md
diff --git a/Archive/05-IntroductionToObjectOrientedProgrammin.md b/Archive/05-IntroductionToObjectOrientedProgrammin.md
deleted file mode 100644
index a2f9495e..00000000
--- a/Archive/05-IntroductionToObjectOrientedProgrammin.md
+++ /dev/null
@@ -1,720 +0,0 @@
-## Exercise 1: Implementing Encapsulation Techniques in the VideoGame Class
-
-
-
-### Instructions
-
-#### Task 1: Implement VideoGame class attributes
-
-1. In the given `VideoGameRunner` class, add the following attributes to the `VideoGame` class:
- - `title` of type `String`
- - `numberOfCopies` of type `int`
-
-#### Task 2: Implement methods for VideoGame class
-
-1. Implement the following methods for the `VideoGame` class:
- - `setTitle(String gameTitle)`: Sets the title of the video game.
- - `getTitle()`: Returns the title of the video game.
- - `setNumberOfCopies(int numberOfCopies)`: Sets the number of copies if the provided number is greater than or equal to 0.
- - `getNumberOfCopies()`: Returns the number of copies.
- - `increaseCopies(int howMuch)`: Increases the number of copies by the given amount.
- - `decreaseCopies(int howMuch)`: Decreases the number of copies by the given amount but ensures that the number of copies does not go below 0.
-
-
-#### Task 3: Test the VideoGame class in the main method
-
-1. In the `main` method of the `VideoGameRunner` class, create three instances of the `VideoGame` class and set their titles as follows:
-
- - Create an instance named `rdr2` and set its title to "Red Dead Redemption 2".
- - Create an instance named `tw3` and set its title to "The Witcher 3".
- - Create an instance named `botw` and set its title to "Breath of the Wild".
-2. Print the titles of the three video game instances (`rdr2`, `tw3`, and `botw`).
-
-3. Increase the number of copies for each video game instance as follows:
-
- - Increase the number of copies for `rdr2` by 12.
- - Increase the number of copies for `tw3` by 18.
- - Increase the number of copies for `botw` by 24.
-4. Decrease the number of copies for each video game instance as follows:
-
- - Decrease the number of copies for `rdr2` by 6.
- - Decrease the number of copies for `tw3` by 12.
- - Decrease the number of copies for `botw` by 18.
-5. Print the number of copies for each video game instance (`rdr2`, `tw3`, and `botw`).
-
-
-
-### Hints
-
-#### Task 1: Implement VideoGame class attributes
-
-**Hint 1:** To add attributes to a class, declare them within the class using the appropriate data type.
-
-**Hint 2:** You need to add two attributes: a `String` for the `title` and an `int` for the `numberOfCopies`.
-
-#### Task 2: Implement methods for VideoGame class
-
-**Hint 1:** To create a method, use the following syntax: `access_modifier return_type methodName(parameters) { /* method body */ }`.
-
-**Hint 2:** For example, the `setTitle` method should have a `void` return type and a single `String` parameter.
-
-**Hint 3:** To set the number of copies only if the provided number is greater than or equal to 0, use an `if` statement in the `setNumberOfCopies` method.
-
-**Hint 4:** The `increaseCopies` and `decreaseCopies` methods should use the `setNumberOfCopies` method to update the `numberOfCopies` attribute.
-
-#### Task 3: Test the VideoGame class in the main method
-
-**Hint 1:** To create an instance of a class, use the `new` keyword followed by the class name and parentheses.
-
-**Hint 2:** To call a method on an instance of a class, use the dot (.) operator followed by the method name and its arguments.
-
-**Hint 3:** Use `System.out.println()` to print the titles and number of copies for each video game instance.
-
-
-### Solution Explanation
-
-
-The given problem code is incomplete and needs to be modified to include the necessary attributes and methods in the `VideoGame` class. Below is the step-by-step explanation of the solution code.
-
-#### Task 1: Implement VideoGame class attributes
-
-We start by adding the required attributes `title` and `numberOfCopies` to the `VideoGame` class.
-
-```
-private String title;
-private int numberOfCopies;
-```
-
-#### Task 2: Implement methods for VideoGame class
-
-Next, we implement the required methods for the `VideoGame` class.
-
-1. Set and get methods for `title` attribute:
-
-```
-public void setTitle(String gameTitle) {
- title = gameTitle;
-}
-
-public String getTitle() {
- return title;
-}
-```
-
-2. Set and get methods for `numberOfCopies` attribute with a condition to ensure the number of copies is non-negative:
-
-```
-public void setNumberOfCopies(int numberOfCopies) {
- if (numberOfCopies >= 0) {
- this.numberOfCopies = numberOfCopies;
- }
-}
-
-public int getNumberOfCopies() {
- return numberOfCopies;
-}
-```
-
-3. Methods to increase and decrease the number of copies:
-
-```
-public void increaseCopies(int howMuch) {
- setNumberOfCopies(numberOfCopies + howMuch);
-}
-
-public void decreaseCopies(int howMuch) {
- setNumberOfCopies(numberOfCopies - howMuch);
-}
-```
-
-#### Task 3: Test the VideoGame class in the main method
-
-Finally, we test the `VideoGame` class in the `main` method by creating instances, setting titles, increasing and decreasing the number of copies, and printing their titles and number of copies.
-
-```
-public static void main(String[] args) {
- VideoGame rdr2 = new VideoGame();
- rdr2.setTitle("Red Dead Redemption 2");
- VideoGame tw3 = new VideoGame();
- tw3.setTitle("The Witcher 3");
- VideoGame botw = new VideoGame();
- botw.setTitle("Breath of the Wild");
-
- System.out.println(rdr2.getTitle());
- System.out.println(tw3.getTitle());
- System.out.println(botw.getTitle());
-
- rdr2.increaseCopies(12);
- tw3.increaseCopies(18);
- botw.increaseCopies(24);
- rdr2.decreaseCopies(6);
- tw3.decreaseCopies(12);
- botw.decreaseCopies(18);
-
- System.out.println(rdr2.getNumberOfCopies());
- System.out.println(tw3.getNumberOfCopies());
- System.out.println(botw.getNumberOfCopies());
-}
-```
-
-This solution code demonstrates the proper implementation of encapsulation techniques and completes the `VideoGame` class as required by the problem statement.
-
-### Student File
-
-**VideoGameRunner.java**
-
-```
-
-public class VideoGameRunner {
-
- static class VideoGame {
- // Complete the code
- }
-
- public static void main(String[] args) {
- // VideoGame rdr2 = new VideoGame();
- // rdr2.setTitle("Red Dead Redemption 2");
- // Complete the code
- }
-}
-
-```
-
-
-
-
-### Solution File
-
-**VideoGameRunner.java**
-
-```
-public class VideoGameRunner {
-
- static class VideoGame {
- private String title;
- private int numberOfCopies;
-
- public void setTitle(String gameTitle) {
- title = gameTitle;
- }
-
- public String getTitle() {
- return title;
- }
-
- public void setNumberOfCopies(int numberOfCopies) {
- if (numberOfCopies >= 0) {
- this.numberOfCopies = numberOfCopies;
- }
- }
-
- public int getNumberOfCopies() {
- return numberOfCopies;
- }
-
- public void increaseCopies(int howMuch) {
- setNumberOfCopies(numberOfCopies + howMuch);
- }
-
- public void decreaseCopies(int howMuch) {
- setNumberOfCopies(numberOfCopies - howMuch);
- }
- }
-
- public static void main(String[] args) {
- VideoGame rdr2 = new VideoGame();
- rdr2.setTitle("Red Dead Redemption 2");
- VideoGame tw3 = new VideoGame();
- tw3.setTitle("The Witcher 3");
- VideoGame botw = new VideoGame();
- botw.setTitle("Breath of the Wild");
-
- System.out.println(rdr2.getTitle());
- System.out.println(tw3.getTitle());
- System.out.println(botw.getTitle());
-
- rdr2.increaseCopies(12);
- tw3.increaseCopies(18);
- botw.increaseCopies(24);
- rdr2.decreaseCopies(6);
- tw3.decreaseCopies(12);
- botw.decreaseCopies(18);
-
- System.out.println(rdr2.getNumberOfCopies());
- System.out.println(tw3.getNumberOfCopies());
- System.out.println(botw.getNumberOfCopies());
- }
-}
-
-```
-
-
-### Evaluation File
-
-**Evaluate.java**
-
-```
-
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-
-import java.util.logging.Logger;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-public class Evaluate {
-
- private VideoGameRunner.VideoGame videoGame;
- private static final Logger LOGGER = Logger.getLogger(Evaluate.class.getName());
-
- @BeforeEach
- public void setUp() {
- LOGGER.info("Setting up a new VideoGame instance for the tests...");
- videoGame = new VideoGameRunner.VideoGame();
- }
-
- @Test
- public void testSetTitleAndGetTitle() {
- LOGGER.info("Running testSetTitleAndGetTitle...");
- String testTitle = "Test Game";
- LOGGER.info("Setting title to: " + testTitle);
- videoGame.setTitle(testTitle);
- LOGGER.info("Getting the title and checking if it matches the expected value...");
- assertEquals(testTitle, videoGame.getTitle());
- LOGGER.info("testSetTitleAndGetTitle passed.");
- }
-
- @Test
- public void testSetNumberOfCopiesAndGetNumberOfCopies() {
- LOGGER.info("Running testSetNumberOfCopiesAndGetNumberOfCopies...");
- int testCopies = 10;
- LOGGER.info("Setting number of copies to: " + testCopies);
- videoGame.setNumberOfCopies(testCopies);
- LOGGER.info("Getting the number of copies and checking if it matches the expected value...");
- assertEquals(testCopies, videoGame.getNumberOfCopies());
- LOGGER.info("testSetNumberOfCopiesAndGetNumberOfCopies passed.");
- }
-
- @Test
- public void testIncreaseCopies() {
- LOGGER.info("Running testIncreaseCopies...");
- int initialCopies = 5;
- int increaseCopiesBy = 5;
- LOGGER.info("Setting initial number of copies to: " + initialCopies);
- videoGame.setNumberOfCopies(initialCopies);
- LOGGER.info("Increasing number of copies by: " + increaseCopiesBy);
- videoGame.increaseCopies(increaseCopiesBy);
- LOGGER.info("Getting the number of copies and checking if it matches the expected value...");
- assertEquals(initialCopies + increaseCopiesBy, videoGame.getNumberOfCopies());
- LOGGER.info("testIncreaseCopies passed.");
- }
-
- @Test
- public void testDecreaseCopies() {
- LOGGER.info("Running testDecreaseCopies...");
- int initialCopies = 10;
- int decreaseCopiesBy = 5;
- LOGGER.info("Setting initial number of copies to: " + initialCopies);
- videoGame.setNumberOfCopies(initialCopies);
- LOGGER.info("Decreasing number of copies by: " + decreaseCopiesBy);
- videoGame.decreaseCopies(decreaseCopiesBy);
- LOGGER.info("Getting the number of copies and checking if it matches the expected value...");
- assertEquals(initialCopies - decreaseCopiesBy, videoGame.getNumberOfCopies());
- LOGGER.info("testDecreaseCopies passed.");
- }
-}
-
-```
-
-
-
-
-
-
-## Exercise 2: Implementing Vehicle Engine Control and Speed Tracking
-
-
-
-### Instructions
-
-
-#### Objective
-
-In this exercise, you are asked to complete the implementation of a simple `Vehicle` class and a `VehicleRunner` class that demonstrates its usage.
-
-#### Instructions
-
-1. Complete the implementation of the `Vehicle` class inside the `VehicleRunner` class. The `Vehicle` class should have the following properties:
-
- - `speed`: An integer representing the speed of the vehicle.
- - `type`: A string representing the type of the vehicle, e.g., "Car", "Truck", "Bike".
-2. Implement two constructors for the `Vehicle` class:
-
- - A constructor that takes two parameters: `speed` and `type`. The `speed` should be set only if the value is greater than 0. Otherwise, the default speed should be 10. The `type` should always be set.
- - A default constructor that sets the `speed` to 10 and the `type` to "Bike".
-3. Implement the following methods for the `Vehicle` class:
-
- - `startEngine()`: This method should print "Engine started!".
- - `stopEngine()`: This method should print "Engine stopped!" and set the `speed` to 0.
- - `getSpeed()`: This method should return the current `speed` of the vehicle.
- - `getType()`: This method should return the current `type` of the vehicle.
-4. In the `main()` method of the `VehicleRunner` class, create three `Vehicle` instances with different speed and type values:
-
- - `car`: Speed 30, Type "Car".
- - `truck`: Speed 20, Type "Truck".
- - `bike`: Default constructor.
-5. Start the engine of all three vehicles and print their initial speed and type.
-
-6. Stop the engine of all three vehicles and print their final speed.
-
-
-#### Example
-
-Below is an example of the incomplete code provided to the student:
-
-```
-public class VehicleRunner {
- public static class Vehicle {
- // Write your code
- }
-
- public static void main(String[] args) {
- // Vehicle car = new Vehicle(30, "Car");
- // Write your code
- }
-}
-```
-
-After completing the exercise, the output should look like this:
-```
-Engine started!
-Engine started!
-Engine started!
-Earlier Car Speed is : 30, Type: Car
-Earlier Truck Speed is : 20, Type: Truck
-Earlier Bike Speed is : 10, Type: Bike
-Engine stopped!
-Engine stopped!
-Engine stopped!
-Stopped Car Speed is : 0
-Stopped Truck Speed is : 0
-Stopped Bike Speed is : 0
-```
-
-
-### Hints
-
-
-Here are some hints for completing the given incomplete exercise code:
-
-1. Inside the `Vehicle` class, you need to declare two instance variables:
-
- - `speed` of type `int`
- - `type` of type `String`
-2. Create a constructor for the `Vehicle` class that takes two parameters:
-
- - `int speed`
- - `String type` Inside the constructor, initialize the instance variables with the given parameters.
-3. Create a default constructor for the `Vehicle` class. In this constructor, set default values for the instance variables:
-
- - Set `speed` to `10`
- - Set `type` to `"Bike"`
-4. Add a method `startEngine()` to the `Vehicle` class that prints "Engine started!" when called.
-
-5. Add a method `stopEngine()` to the `Vehicle` class that prints "Engine stopped!" when called and sets the `speed` of the vehicle to `0`.
-
-6. Create getter methods for the `speed` and `type` instance variables in the `Vehicle` class:
-
- - `public int getSpeed()`
- - `public String getType()`
-7. In the `main` method of the `VehicleRunner` class, create three instances of the `Vehicle` class:
-
- - `Vehicle car = new Vehicle(30, "Car");`
- - `Vehicle truck = new Vehicle(20, "Truck");`
- - `Vehicle bike = new Vehicle();`
-8. Start the engine of each vehicle by calling the `startEngine()` method on each instance.
-
-9. Print the initial speed and type of each vehicle by calling the `getSpeed()` and `getType()` methods.
-
-10. Stop the engine of each vehicle by calling the `stopEngine()` method on each instance.
-
-11. Print the final speed of each vehicle after stopping the engine by calling the `getSpeed()` method.
-
-
-### Solution Explanation
-
-
-
-In this exercise, we're asked to complete the given incomplete `VehicleRunner` class by implementing the `Vehicle` class, its methods, and then creating instances of the `Vehicle` class in the `main` method. Here's the step-by-step explanation of the solution:
-
-### Implementing the Vehicle class
-
-1. First, we declare two instance variables for the `Vehicle` class:
- - `speed` of type `int`
- - `type` of type `String`
-
-```
-private int speed;
-private String type;
-```
-
-2. Next, we create a constructor for the `Vehicle` class that takes two parameters:
- - `int speed`
- - `String type` Inside the constructor, we initialize the instance variables with the given parameters.
-
-```
-public Vehicle(int speed, String type) {
- if (speed > 0) {
- this.speed = speed;
- }
- this.type = type;
-}
-```
-
-3. We then create a default constructor for the `Vehicle` class. In this constructor, we set default values for the instance variables:
- - Set `speed` to `10`
- - Set `type` to `"Bike"`
-
-```
-public Vehicle() {
- this.speed = 10;
- this.type = "Bike";
-}
-```
-
-4. We add a method `startEngine()` to the `Vehicle` class that prints "Engine started!" when called.
-
-```
-public void startEngine() {
- System.out.println("Engine started!");
-}
-```
-
-5. We add another method `stopEngine()` to the `Vehicle` class that prints "Engine stopped!" when called and sets the `speed` of the vehicle to `0`.
-
-```
-public void stopEngine() {
- System.out.println("Engine stopped!");
- this.speed = 0;
-}
-```
-
-6. We create getter methods for the `speed` and `type` instance variables in the `Vehicle` class:
- - `public int getSpeed()`
- - `public String getType()`
-
-```
-public int getSpeed() {
- return speed;
-}
-
-public String getType() {
- return type;
-}
-```
-
-### Creating instances and calling methods in the main method
-
-7. In the `main` method of the `VehicleRunner` class, we create three instances of the `Vehicle` class:
-
-```
-Vehicle car = new Vehicle(30, "Car");
-Vehicle truck = new Vehicle(20, "Truck");
-Vehicle bike = new Vehicle();
-```
-
-8. We start the engine of each vehicle by calling the `startEngine()` method on each instance:
-
-```
-car.startEngine();
-truck.startEngine();
-bike.startEngine();
-```
-
-9. We print the initial speed and type of each vehicle by calling the `getSpeed()` and `getType()` methods:
-
-```
-System.out.println("Earlier Car Speed is : " + car.getSpeed() + ", Type: " + car.getType());
-System.out.println("Earlier Truck Speed is : " + truck.getSpeed() + ", Type: " + truck.getType());
-System.out.println("Earlier Bike Speed is : " + bike.getSpeed() + ", Type: " + bike.getType());
-```
-
-10. We stop the engine of each vehicle by calling the `stopEngine()` method on each instance:
-
-```
-car.stopEngine();
-truck.stopEngine();
-bike.stopEngine();
-```
-
-11. Finally, we print the final speed of each vehicle after stopping the engine by calling the `getSpeed()` method:
-
-```
-System.out.println("Stopped Car Speed is : " + car.getSpeed());
-System.out.println("Stopped Truck Speed is : " + truck.getSpeed());
-System.out.println("Stopped Bike Speed is : " + bike.getSpeed());
-```
-
-With this, we have successfully completed the implementation of the `VehicleRunner` class and its inner `Vehicle` class.
-
-### Student File
-
-**VehicleRunner.java**
-
-```
-
-public class VehicleRunner {
- public static class Vehicle {
- // Write your code
- }
-
- public static void main(String[] args) {
- // Vehicle car = new Vehicle(30, "Car");
- // Write your code
- }
-
-
-}
-```
-
-
-
-
-### Solution File
-
-**VehicleRunner.java**
-
-```
-public class VehicleRunner {
- public static class Vehicle {
- private int speed;
- private String type;
-
- public Vehicle(int speed, String type) {
- if (speed > 0) {
- this.speed = speed;
- }
- this.type = type;
- }
-
- public Vehicle() {
- this.speed = 10;
- this.type = "Bike";
- }
-
- public void startEngine() {
- System.out.println("Engine started!");
- }
-
- public void stopEngine() {
- System.out.println("Engine stopped!");
- this.speed = 0;
- }
-
- public int getSpeed() {
- return speed;
- }
-
- public String getType() {
- return type;
- }
- }
-
- public static void main(String[] args) {
- Vehicle car = new Vehicle(30, "Car");
- Vehicle truck = new Vehicle(20, "Truck");
- Vehicle bike = new Vehicle();
-
- car.startEngine();
- truck.startEngine();
- bike.startEngine();
-
- System.out.println("Earlier Car Speed is : " + car.getSpeed() + ", Type: " + car.getType());
- System.out.println("Earlier Truck Speed is : " + truck.getSpeed() + ", Type: " + truck.getType());
- System.out.println("Earlier Bike Speed is : " + bike.getSpeed() + ", Type: " + bike.getType());
-
- car.stopEngine();
- truck.stopEngine();
- bike.stopEngine();
-
- System.out.println("Stopped Car Speed is : " + car.getSpeed());
- System.out.println("Stopped Truck Speed is : " + truck.getSpeed());
- System.out.println("Stopped Bike Speed is : " + bike.getSpeed());
- }
-
-
-}
-
-```
-
-
-### Evaluation File
-
-**Evaluate.java**
-
-```
-
-import org.junit.jupiter.api.Test;
-import static org.junit.jupiter.api.Assertions.*;
-
-public class Evaluate {
- @Test
- public void testStartEngine() {
- VehicleRunner.Vehicle car = new VehicleRunner.Vehicle(30, "Car");
- VehicleRunner.Vehicle truck = new VehicleRunner.Vehicle(20, "Truck");
- VehicleRunner.Vehicle bike = new VehicleRunner.Vehicle();
-
- car.startEngine();
- truck.startEngine();
- bike.startEngine();
-
- System.out.println("Car Speed after starting engine: " + car.getSpeed());
- System.out.println("Truck Speed after starting engine: " + truck.getSpeed());
- System.out.println("Bike Speed after starting engine: " + bike.getSpeed());
-
- assertEquals(30, car.getSpeed());
- assertEquals(20, truck.getSpeed());
- assertEquals(10, bike.getSpeed());
- }
-
- @Test
- public void testStopEngine() {
- VehicleRunner.Vehicle car = new VehicleRunner.Vehicle(30, "Car");
- VehicleRunner.Vehicle truck = new VehicleRunner.Vehicle(20, "Truck");
- VehicleRunner.Vehicle bike = new VehicleRunner.Vehicle();
-
- car.startEngine();
- truck.startEngine();
- bike.startEngine();
-
- car.stopEngine();
- truck.stopEngine();
- bike.stopEngine();
-
- System.out.println("Car Speed after stopping engine: " + car.getSpeed());
- System.out.println("Truck Speed after stopping engine: " + truck.getSpeed());
- System.out.println("Bike Speed after stopping engine: " + bike.getSpeed());
-
- assertEquals(0, car.getSpeed());
- assertEquals(0, truck.getSpeed());
- assertEquals(0, bike.getSpeed());
- }
-
- @Test
- public void testGetType() {
- VehicleRunner.Vehicle car = new VehicleRunner.Vehicle(30, "Car");
- VehicleRunner.Vehicle truck = new VehicleRunner.Vehicle(20, "Truck");
- VehicleRunner.Vehicle bike = new VehicleRunner.Vehicle();
-
- System.out.println("Car type: " + car.getType());
- System.out.println("Truck type: " + truck.getType());
- System.out.println("Bike type: " + bike.getType());
-
- assertEquals("Car", car.getType());
- assertEquals("Truck", truck.getType());
- assertEquals("Bike", bike.getType());
- }
-}
-
-
-```
\ No newline at end of file
diff --git a/Archive/Ref.md b/Archive/Ref.md
deleted file mode 100644
index 4583b03d..00000000
--- a/Archive/Ref.md
+++ /dev/null
@@ -1,62 +0,0 @@
-## 1
-
-```
-import java.util.Scanner;
-
-public class UdemyCourseAccess {
-
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
-
- System.out.print("Are you logged in? (yes/no): ");
- String loggedIn = scanner.nextLine();
-
- if (loggedIn.equalsIgnoreCase("yes")) {
- System.out.print("Are you enrolled in the in28Minutes course? (yes/no): ");
- String enrolled = scanner.nextLine();
-
- if (enrolled.equalsIgnoreCase("yes")) {
- System.out.println("Welcome to the in28Minutes Course!");
- } else {
- System.out.println("Please enroll in the in28Minutes course.");
- }
- } else {
- System.out.println("Please log in to Udemy.");
- }
-
- scanner.close();
- }
-}
-```
-
-
-## 2
-
-```
-import java.util.Scanner;
-
-public class UdemyCourseAccess {
-
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
-
- System.out.print("Are you logged in? (1 for yes, 0 for no): ");
- int loggedIn = scanner.nextInt();
-
- if (loggedIn == 1) {
- System.out.print("Are you enrolled in the in28Minutes course? (1 for yes, 0 for no): ");
- int enrolled = scanner.nextInt();
-
- if (enrolled == 1) {
- System.out.println("Welcome to the in28Minutes Course!");
- } else {
- System.out.println("Please enroll in the in28Minutes course.");
- }
- } else {
- System.out.println("Please log in to Udemy.");
- }
-
- scanner.close();
- }
-}
-```
\ No newline at end of file
diff --git a/txt_help.md b/txt_help.md
deleted file mode 100644
index f4aed4f1..00000000
--- a/txt_help.md
+++ /dev/null
@@ -1,62 +0,0 @@
-
-
-# Month Name Printer
-
-## Problem Statement
-
-You are tasked with implementing a Java program that takes an integer input representing the month number (1-12) and prints the corresponding month name.
-
-### Instructions
-
-1. **TODO:** Implement the `getMonthName()` method which takes an integer `monthNumber` as a parameter and returns the corresponding month name as a string. If the given `monthNumber` is invalid (not in the range of 1-12), the method should return `null`.
-
-2. **TODO:** In the `main()` method, prompt the user to enter the month number (1-12). Call the `getMonthName()` method with the entered month number as an argument and store the result in a variable named `monthName`.
-
-3. **TODO:** Use an `if-else` statement to check if the `monthName` is `null`. If it is, print "Invalid month number entered." If it's not `null`, print "The name of month number [monthNumber] is [monthName]."
-
-
-### Input Format
-
-The input is a single integer `monthNumber` (1 ≤ monthNumber ≤ 12).
-
-```
-4
-```
-
-## Output Format
-
-The output is a single line with the month name corresponding to the given `monthNumber`. If the `monthNumber` is invalid, the output is "Invalid month number entered."
-
-```
-The name of month number 4 is April.
-```
-
-### Example
-
-**Input:**
-
-```
-Enter the month number (1-12):
-4
-```
-
-**Output:**
-
-```
-The name of month number 4 is April.
-```
-
-**Input:**
-
-```
-Enter the month number (1-12):
-0
-```
-
-**Output:**
-
-```
-Invalid month number entered.
-```
-
-
From f7283649a8bafe775fc26c4ca19383ddb520ea6f Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sun, 7 May 2023 00:36:54 +0530
Subject: [PATCH 145/178] .
---
01-Quiz/7MAY2023/Q10-ArraysAndArrayList.md | 0
01-Quiz/7MAY2023/Q11-ObjectOrientedProgrammingAgain.md | 0
01-Quiz/7MAY2023/Q12-Collections.md | 0
3 files changed, 0 insertions(+), 0 deletions(-)
create mode 100644 01-Quiz/7MAY2023/Q10-ArraysAndArrayList.md
create mode 100644 01-Quiz/7MAY2023/Q11-ObjectOrientedProgrammingAgain.md
create mode 100644 01-Quiz/7MAY2023/Q12-Collections.md
diff --git a/01-Quiz/7MAY2023/Q10-ArraysAndArrayList.md b/01-Quiz/7MAY2023/Q10-ArraysAndArrayList.md
new file mode 100644
index 00000000..e69de29b
diff --git a/01-Quiz/7MAY2023/Q11-ObjectOrientedProgrammingAgain.md b/01-Quiz/7MAY2023/Q11-ObjectOrientedProgrammingAgain.md
new file mode 100644
index 00000000..e69de29b
diff --git a/01-Quiz/7MAY2023/Q12-Collections.md b/01-Quiz/7MAY2023/Q12-Collections.md
new file mode 100644
index 00000000..e69de29b
From 5034a90a3819ebca8420e61b34d3ca7f9ec067d5 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sun, 7 May 2023 10:07:53 +0530
Subject: [PATCH 146/178] .
---
01-Quiz/7MAY2023/Q12-Collections.md | 402 ++++++++++++++++++++++++++++
1 file changed, 402 insertions(+)
diff --git a/01-Quiz/7MAY2023/Q12-Collections.md b/01-Quiz/7MAY2023/Q12-Collections.md
index e69de29b..2ab0050c 100644
--- a/01-Quiz/7MAY2023/Q12-Collections.md
+++ b/01-Quiz/7MAY2023/Q12-Collections.md
@@ -0,0 +1,402 @@
+## Step 00: Collections Overview
+
+//Question 1
+//What are Collections in Java?
+a) Collections is a package in Java
+**b) Collections are in-built implementations available to support dynamic data structures in Java programs.**
+c) Collections are used to sort static data structures in Java programs.
+
+//Question 2
+//What are some common collections?
+**a) List, Set, Queue, Map**
+b) Stack, Heap, Tree
+c) Graph, Queue, Hash Table
+
+//Question 3
+//What is List Interface used for?
+**a) List Interface is used to implement an ordered collection in Java programs.**
+b) List Interface is used to implement an unordered collection in Java programs.
+c) List Interface is used to implement a stack data structure in Java programs.
+
+
+## Step 00: Comparator for ArrayList.sort()
+
+```
+package collections;
+import java.util.Collections;
+import java.util.List;
+import java.util.ArrayList;
+import java.util.Comparator;
+
+public class StudentsCollectionRunner {
+ public static void main(String[] args) {
+ List students = List.of(new Student(1, "Ranga"),
+ new Student(100, "Adam"),
+ new Student(2, "Eve"));
+
+ ArrayList studentsAl = new ArrayList<>(students);
+ System.out.println(studentsAl);
+ studentsAl.sort(new AscStudentComparator());
+ System.out.println("Asc : " + studentsAl);
+ studentsAl.sort(new DescStudentComparator());
+ System.out.println("Desc : " + studentsAl);
+ }
+}
+```
+
+**Question 1:** What is the purpose of the `StudentsCollectionRunner` class?
+
+- A) To sort a list of students by their names
+- B) To sort a list of students by their IDs in ascending and descending order
+- C) To create a new student object
+
+**Answer:** B) To sort a list of students by their IDs in ascending and descending order
+
+**Question 2:** What is the output of the following code?
+
+```
+ArrayList studentsAl = new ArrayList<>(students);
+studentsAl.sort(new DescStudentComparator());
+System.out.println("Desc : " + studentsAl);
+```
+
+- A) [100 Adam, 2 Eve, 1 Ranga]
+- B) [1 Ranga, 2 Eve, 100 Adam]
+- C) [100 Adam, 1 Ranga, 2 Eve]
+
+**Answer:** A) [100 Adam, 2 Eve, 1 Ranga]
+
+**Question 3:** Which interface is used to provide the custom sorting order for `studentsAl`?
+
+- A) `Comparable`
+- B) `Comparator`
+- C) `Iterable`
+
+**Answer:** B) `Comparator`
+
+## Step 01: The Set interface
+
+Mathematically, a set is a collection of unique items. Similarly, the Java Set interface also specifies a contract for collections having unique elements.
+
+If object1.equals(object2) returns true, then only one of object1 and object2 have a place in a Set implementation. There is no positional element access provided by the Set implementations.
+
+**Question 1:** How does the Java Set interface handle duplicates?
+
+- A) It stores all duplicate elements
+- B) It only stores the first occurrence of an element
+- C) It throws an exception when duplicates are added
+
+**Answer:** B) It only stores the first occurrence of an element
+
+**Question 2:** What does the `equals` method need to return for two objects to be considered equal and treated as duplicates by a Set implementation?
+
+- A) `true`
+- B) `false`
+- C) It depends on the specific implementation
+
+**Answer:** A) `true`
+
+**Question 3:** What is one feature that is not provided by the Set interface?
+
+- A) Iteration over elements
+- B) Removing elements
+- C) Positional element access
+
+**Answer:** C) Positional element access
+
+## Step 02: Understanding Data Structures
+
+### Hash Table
+
+**Question 1:** What is a hash table?
+
+- A) A table of sorted elements
+- B) A table of unique elements
+- C) A data structure that combines efficient element access and element insertion/deletion
+
+**Answer:** C) A data structure that combines efficient element access and element insertion/deletion
+
+**Question 2:** What is a bucket in a hash table?
+
+- **A) A slot in the table where elements are inserted and chained together**
+- B) A subset of elements in the table that share the same hash value
+- C) A container used to store the hash function
+
+
+# Step 17: PriorityQueue
+
+```
+Queue queue = new PriorityQueue<>();
+queue.addAll(List.of("Apple", "Zebra", "Monkey", "Cat"));
+```
+
+1. What is the output of `queue.poll()` after adding the elements to the PriorityQueue?
+
+ - A. "Apple"
+ - B. "Zebra"
+ - C. "Cat"
+ - D. "Monkey"
+
+ Answer: A
+
+2. What is the default ordering of elements in a PriorityQueue?
+
+ - A. Descending order
+ - B. Ascending order based on natural order
+ - C. Insertion order
+ - D. Random order
+
+ Answer: B
+
+3. What is the output of `queue.poll()` after executing `queue.poll()` three times?
+
+ - A. "Cat"
+ - B. "Monkey"
+ - C. "Zebra"
+ - D. null
+
+ Answer: D
+
+
+# Step 18: Custom Priority PriorityQueue
+
+```
+Queue queue = new PriorityQueue<>(new StringLengthComparator());
+queue.addAll(List.of("Zebra", "Monkey", "Cat"));
+```
+
+1. What is the output of `queue.poll()` after adding the elements to the PriorityQueue?
+
+ - A. "Zebra"
+ - B. "Monkey"
+ - C. "Cat"
+ - D. null
+
+ Answer: C
+
+2. What interface must be implemented to specify a custom priority order in a PriorityQueue?
+
+ - A. Comparable
+ - B. Comparator
+ - C. PriorityQueue
+ - D. Queue
+
+ Answer: B
+
+3. What is the output of the following code snippet after executing `queue.poll()` three times?
+
+
+```
+Queue queue = new PriorityQueue<>(new StringLengthComparator());
+queue.addAll(List.of("Zebra", "Monkey", "Cat"));
+queue.poll();
+queue.poll();
+queue.poll();
+queue.poll();
+```
+
+- A. null
+- B. "Cat"
+- C. "Monkey"
+- D. "Zebra"
+
+Answer: D
+
+# Step 19: Basic Map Operations
+
+```
+Map map = Map.of("A", 3, "B", 5, "Z", 10);
+```
+
+1. What is the size of `map`?
+
+ - A. 3
+ - B. 4
+ - C. 5
+ - D. 6
+
+ Answer: A
+
+2. What is the value associated with the key "Z" in `map`?
+
+ - A. 3
+ - B. 5
+ - C. 10
+ - D. null
+
+ Answer: C
+
+3. What is the output of `map.containsValue(4)`?
+
+ - A. true
+ - B. false
+ - C. compilation error
+ - D. runtime error
+
+ Answer: B
+
+
+# Step 20: Mutable Maps
+
+```
+Map map = Map.of("A", 3, "B", 5, "Z", 10);
+Map hashMap = new HashMap<>(map);
+```
+
+1. What is the output of `hashMap.put("F", 5)`?
+
+ - A. 5
+ - B. null
+ - C. "F"
+ - D. compilation error
+
+ Answer: B
+
+
+
+## Step 21: Map Implementations
+
+```
+HashMap hashMap = new HashMap<>();
+hashMap.put("Z", 5);
+hashMap.put("A", 15);
+hashMap.put("F", 25);
+hashMap.put("L", 250);
+hashMap // {A=15, F=25, Z=5, L=250}
+
+LinkedHashMap linkedHashMap = new LinkedHashMap<>();
+linkedHashMap.put("Z", 5);
+linkedHashMap.put("A", 15);
+linkedHashMap.put("F", 25);
+linkedHashMap.put("L", 250);
+linkedHashMap // {Z=5, A=15, F=25, L=250}
+
+TreeMap treeMap = new TreeMap<>();
+treeMap.put("Z", 5);
+treeMap.put("A", 15);
+treeMap.put("F", 25);
+treeMap.put("L", 250);
+treeMap // {A=15, F=25, L=250, Z=5}
+```
+
+### Question 1
+
+Which of the following map implementations maintains natural sorted order of the keys?
+
+A. HashMap
+B. LinkedHashMap
+C. TreeMap
+
+Answer: C
+
+### Question 2
+
+Which of the following map implementations does not guarantee the order of stored elements?
+
+A. HashMap
+B. LinkedHashMap
+C. TreeMap
+
+Answer: A
+
+### Question 3
+
+Which of the following map implementations maintains insertion order of elements?
+
+A. HashMap
+B. LinkedHashMap
+C. TreeMap
+
+Answer: B
+
+## Step 22: Basic Map Operations
+
+```
+Map map = Map.of("A", 3, "B", 5, "Z", 10);
+map // {Z=10, A=3, B=5}
+map.get("Z") // 10
+map.get("A") // 3
+map.get("C") // null
+map.size() // 3
+map.isEmpty() // false
+map.containsKey("A") // true
+map.containsKey("F") // false
+map.containsValue(3) // true
+map.containsValue(4) // false
+map.keySet() // [Z, A, B]
+map.values() // [10, 3, 5]
+```
+
+### Question 1
+
+What is the output of the following code?
+
+```
+Map map = Map.of("A", 1, "B", 2, "C", 3);
+map.put("D", 4);
+System.out.println(map.size());
+```
+
+A. 3
+B. 4
+C. 5
+D. Compilation error
+
+Answer: D (Map.of() method creates an immutable map, hence put() operation cannot be performed)
+
+### Question 2
+
+What is the output of the following code?
+
+```
+Map map = Map.of("A", 1, "B", 2, "C", 3);
+System.out.println(map.containsValue(2));
+```
+
+A. true
+B. false
+C. Compilation error
+
+Answer: A
+
+### Question 3
+
+What is the output of the following code?
+
+```
+Map map = Map.of("A", 1, "B", 2, "C", 3);
+System.out.println(map.keySet());
+```
+
+A. ["A", "B", "C"]
+B. [1, 2, 3]
+C. ["A"], ["B"], ["C"]
+D. Compilation error
+
+Answer: A
+
+## Step 23: Sorting Collections
+
+Question 1: Which data structure always maintains the natural sorted order of its elements?
+a) HashSet
+b) LinkedHashMap
+c) TreeMap
+d) PriorityQueue
+
+Answer: c) TreeMap
+
+Question 2: Which interface provides a contract to implement collections of elements in the form of (key, value) pairs?
+a) List
+b) Set
+c) Queue
+d) Map
+
+Answer: d) Map
+
+Question 3: What is the main difference between a HashMap and a TreeMap?
+a) HashMap stores elements in natural sorted order while TreeMap is unordered.
+b) HashMap maintains insertion order while TreeMap is unsorted.
+c) HashMap and TreeMap are both unordered and unsorted.
+d) HashMap is based on a hash table while TreeMap is stored in a tree data structure and maintains natural sorted order.
+
+Answer: d) HashMap is based on a hash table while TreeMap is stored in a tree data structure and maintains natural sorted order.
\ No newline at end of file
From 8ffaebc1e8f4dee502ea7b10cdbcbc965c40cd76 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sun, 7 May 2023 10:10:27 +0530
Subject: [PATCH 147/178] .
---
01-Quiz/7MAY2023/Q12-Collections.md | 24 ++++++++++++------------
1 file changed, 12 insertions(+), 12 deletions(-)
diff --git a/01-Quiz/7MAY2023/Q12-Collections.md b/01-Quiz/7MAY2023/Q12-Collections.md
index 2ab0050c..29ccf2ee 100644
--- a/01-Quiz/7MAY2023/Q12-Collections.md
+++ b/01-Quiz/7MAY2023/Q12-Collections.md
@@ -1,22 +1,22 @@
## Step 00: Collections Overview
-//Question 1
+Question 1
//What are Collections in Java?
-a) Collections is a package in Java
-**b) Collections are in-built implementations available to support dynamic data structures in Java programs.**
-c) Collections are used to sort static data structures in Java programs.
+- a) Collections is a package in Java
+- **b) Collections are in-built implementations available to support dynamic data structures in Java programs.**
+- c) Collections are used to sort static data structures in Java programs.
-//Question 2
+Question 2
//What are some common collections?
-**a) List, Set, Queue, Map**
-b) Stack, Heap, Tree
-c) Graph, Queue, Hash Table
+- **a) List, Set, Queue, Map**
+- b) Stack, Heap, Tree
+- c) Graph, Queue, Hash Table
-//Question 3
+Question 3
//What is List Interface used for?
-**a) List Interface is used to implement an ordered collection in Java programs.**
-b) List Interface is used to implement an unordered collection in Java programs.
-c) List Interface is used to implement a stack data structure in Java programs.
+- **a) List Interface is used to implement an ordered collection in Java programs.**
+- b) List Interface is used to implement an unordered collection in Java programs.
+- c) List Interface is used to implement a stack data structure in Java programs.
## Step 00: Comparator for ArrayList.sort()
From bd17633341349644d720ce38865c2349073a1d79 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sun, 7 May 2023 10:12:24 +0530
Subject: [PATCH 148/178] .
---
01-Quiz/7MAY2023/Q12-Collections.md | 64 ++++++++++++++---------------
1 file changed, 32 insertions(+), 32 deletions(-)
diff --git a/01-Quiz/7MAY2023/Q12-Collections.md b/01-Quiz/7MAY2023/Q12-Collections.md
index 29ccf2ee..a2434eb7 100644
--- a/01-Quiz/7MAY2023/Q12-Collections.md
+++ b/01-Quiz/7MAY2023/Q12-Collections.md
@@ -283,9 +283,9 @@ treeMap // {A=15, F=25, L=250, Z=5}
Which of the following map implementations maintains natural sorted order of the keys?
-A. HashMap
-B. LinkedHashMap
-C. TreeMap
+- A. HashMap
+- B. LinkedHashMap
+- C. TreeMap
Answer: C
@@ -293,9 +293,9 @@ Answer: C
Which of the following map implementations does not guarantee the order of stored elements?
-A. HashMap
-B. LinkedHashMap
-C. TreeMap
+- A. HashMap
+- B. LinkedHashMap
+- C. TreeMap
Answer: A
@@ -303,9 +303,9 @@ Answer: A
Which of the following map implementations maintains insertion order of elements?
-A. HashMap
-B. LinkedHashMap
-C. TreeMap
+- A. HashMap
+- B. LinkedHashMap
+- C. TreeMap
Answer: B
@@ -337,10 +337,10 @@ map.put("D", 4);
System.out.println(map.size());
```
-A. 3
-B. 4
-C. 5
-D. Compilation error
+- A. 3
+- B. 4
+- C. 5
+- D. Compilation error
Answer: D (Map.of() method creates an immutable map, hence put() operation cannot be performed)
@@ -353,9 +353,9 @@ Map map = Map.of("A", 1, "B", 2, "C", 3);
System.out.println(map.containsValue(2));
```
-A. true
-B. false
-C. Compilation error
+- A. true
+- B. false
+- C. Compilation error
Answer: A
@@ -368,35 +368,35 @@ Map map = Map.of("A", 1, "B", 2, "C", 3);
System.out.println(map.keySet());
```
-A. ["A", "B", "C"]
-B. [1, 2, 3]
-C. ["A"], ["B"], ["C"]
-D. Compilation error
+- A. ["A", "B", "C"]
+- B. [1, 2, 3]
+- C. ["A"], ["B"], ["C"]
+- D. Compilation error
Answer: A
## Step 23: Sorting Collections
Question 1: Which data structure always maintains the natural sorted order of its elements?
-a) HashSet
-b) LinkedHashMap
-c) TreeMap
-d) PriorityQueue
+- a) HashSet
+- b) LinkedHashMap
+- c) TreeMap
+- d) PriorityQueue
Answer: c) TreeMap
Question 2: Which interface provides a contract to implement collections of elements in the form of (key, value) pairs?
-a) List
-b) Set
-c) Queue
-d) Map
+- a) List
+- b) Set
+- c) Queue
+- d) Map
Answer: d) Map
Question 3: What is the main difference between a HashMap and a TreeMap?
-a) HashMap stores elements in natural sorted order while TreeMap is unordered.
-b) HashMap maintains insertion order while TreeMap is unsorted.
-c) HashMap and TreeMap are both unordered and unsorted.
-d) HashMap is based on a hash table while TreeMap is stored in a tree data structure and maintains natural sorted order.
+- a) HashMap stores elements in natural sorted order while TreeMap is unordered.
+- b) HashMap maintains insertion order while TreeMap is unsorted.
+- c) HashMap and TreeMap are both unordered and unsorted.
+- d) HashMap is based on a hash table while TreeMap is stored in a tree data structure and maintains natural sorted order.
Answer: d) HashMap is based on a hash table while TreeMap is stored in a tree data structure and maintains natural sorted order.
\ No newline at end of file
From 8805d42236e01ec844ccd4778472d310ad692b69 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sun, 7 May 2023 10:13:06 +0530
Subject: [PATCH 149/178] .
---
01-Quiz/{7MAY2023 => }/Q12-Collections.md | 0
1 file changed, 0 insertions(+), 0 deletions(-)
rename 01-Quiz/{7MAY2023 => }/Q12-Collections.md (100%)
diff --git a/01-Quiz/7MAY2023/Q12-Collections.md b/01-Quiz/Q12-Collections.md
similarity index 100%
rename from 01-Quiz/7MAY2023/Q12-Collections.md
rename to 01-Quiz/Q12-Collections.md
From bce3b6f933f73f2317b5d1ce596bbdb896c03299 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sun, 7 May 2023 10:20:22 +0530
Subject: [PATCH 150/178] .
---
01-Quiz/7MAY2023/Q10-ArraysAndArrayList.md | 349 +++++++++++++++++++++
1 file changed, 349 insertions(+)
diff --git a/01-Quiz/7MAY2023/Q10-ArraysAndArrayList.md b/01-Quiz/7MAY2023/Q10-ArraysAndArrayList.md
index e69de29b..ae95114c 100644
--- a/01-Quiz/7MAY2023/Q10-ArraysAndArrayList.md
+++ b/01-Quiz/7MAY2023/Q10-ArraysAndArrayList.md
@@ -0,0 +1,349 @@
+## Step 01: The Need For Array Quiz
+
+1. Why do we need arrays?
+- a. To store different types of data.
+- b. To store similar types of data.
+- c. To store data in an unorganized manner.
+
+ **b. To store similar types of data.**
+
+2. What is the use of indexing operator, ‘[]’ in arrays? a. To access elements from the array. b. To store elements in the array. c. To change the elements in the array.
+
+ **a. To access elements from the array.**
+
+3. What is the purpose of enhanced for loop in arrays?
+- a. To store elements in the array.
+- b. To access elements from the array.
+- c. To iterate through all elements in the array.
+
+ **c. To iterate through all elements in the array.**
+
+
+## Step 02: Storing and Accessing Array Values Quiz
+
+1. What is the purpose of using the new operator in arrays? a. To initialize an array with specific values. b. To create an array with a specific size. c. To assign values to an array.
+
+ **b. To create an array with a specific size.**
+
+2. How can we access elements from an array?
+- a. By using the indexing operator, ‘[]’.
+- b. By using the length property of the array.
+- c. By using the for loop.
+
+ **a. By using the indexing operator, ‘[]’.**
+
+3. What is the length property in arrays used for?
+- a. To find the size of an array.
+- b. To find the number of elements in an array.
+- c. To find the value of an element in an array.
+
+ **b. To find the number of elements in an array.**
+
+
+## Step 04: Array Initialization, Data Types and Exceptions Quiz
+
+1. What is the value of an array element of type int when it is not initialized?
+- a. Null
+- b. False
+- c. 0
+
+ **c. 0**
+
+2. What is the value of an array element of type boolean when it is not initialized?
+- a. Null
+- b. False
+- c. 0
+
+ **b. False**
+
+3. What is the declaration part of an array definition not allowed to include?
+- a. The type of elements stored in the array.
+- b. The dimension of the array.
+- c. The name of the array.
+
+ **b. The dimension of the array.**
+
+
+
+## Step 05: Array Utilities Quiz
+
+1. What is the purpose of the method `Arrays.fill`?
+- a. To compare two arrays
+- b. To fill an array with a specified value
+- c. To perform an in-position sorting of elements
+- d. To store zero or more number of elements in an array
+
+ **Answer: b. To fill an array with a specified value**
+
+3. What is the output of the following code?
+
+ ```
+ int[] marks = new int[5];
+ Arrays.fill(marks, 100);
+ System.out.println(marks);
+ ```
+
+ - a. [100,100,100,100,100]
+ - b. [0,0,0,0,0]
+ - c. 100,100,100,100,100
+ - d. I@6c49835d
+
+ **Answer: a. [100,100,100,100,100]**
+
+4. What is the result of the following code?
+
+```
+ int[] array1 = {1, 2, 3};
+ int[] array2 = {1, 2, 3};
+ Arrays.equals(array1, array2);
+```
+
+ - a. false
+ - b. true
+ - c. [1,2,3]
+ - d. I@6c49835d
+
+ **Answer: b. true**
+
+# Step 06: Classroom Exercise CE-AA-02
+
+Create a multiple-choice quiz based on the concepts taught in this step:
+
+**Question 1:** Which of the following utility methods can be used to get the total number of marks of a `Student` object?
+
+- A) `getNumberOfmarks()`
+- B) `getTotalSumOfMarks()`
+- C) `getAverageMarks()`
+
+**Answer:** A) `getNumberOfmarks()`
+
+**Question 2:** Which of the following is an implementation of the `Student` class as an array?
+
+- A) `Student student = new Student(name, list-of-marks);`
+- B) `int[] marks = {99, 98, 100};`
+- C) `BigDecimal average = student.getAverageMarks();`
+
+**Answer:** B) `int[] marks = {99, 98, 100};`
+
+**Question 3:** Which of the following utility methods can be used to get the maximum mark of a `Student` object?
+
+- A) `getNumberOfmarks()`
+- B) `getMaximumMark()`
+- C) `getMinimumMark()`
+
+**Answer:** B) `getMaximumMark()`
+
+# Step 08: Variable Arguments - The Basics
+
+Create a multiple-choice quiz based on the concepts taught in this step:
+
+**Question 1:** What is the critical part when creating a method which can accept a variable number of arguments?
+
+- A) The `int` data type
+- B) The `...` symbol
+- C) The `Arrays.toString()` method
+
+**Answer:** B) The `...` symbol
+
+**Question 2:** What is the output of the following code snippet?
+
+```
+class Something {
+ public void doSomething(int... values) {
+ System.out.println(Arrays.toString(values));
+ }
+}
+Something thing = new Something();
+thing.doSomething(1, 2, 3);
+```
+
+- A) `[1, 2]`
+- B) `[1, 2, 3]`
+- C) `1 2 3`
+
+**Answer:** B) `[1, 2, 3]`
+
+**Question 3:** Where should the variable arguments list be placed in the parameter list passed to a method?
+
+- A) At the beginning
+- B) In the middle
+- C) At the end
+
+**Answer:** C) At the end
+
+# Step 09: Variable Argument Methods For Student
+
+Create a multiple-choice quiz based on the concepts taught in this step:
+
+**Question 1:** Which of the following is an example of a variable argument method in the `Student` class?
+
+- A) `public int getNumberOfMarks()`
+- B) `public int[] getMarks()`
+- C) `public Student(String name, int... marks)`
+
+**Answer:** C) `public Student(String name, int... marks)`
+
+**Question 2:** What is the output of the following code snippet?
+
+```
+Student student = new Student("Ranga", 97, 98, 100);
+System.out.println(student.getNumberOfMarks());
+```
+
+- A) `3`
+- B) `97, 98, 100`
+- C) `295`
+
+**Answer:** A) `3`
+
+**Question 3:** What happens if you pass the wrong data type to a variable argument method?
+
+- A) The Java compiler will throw an error.
+- B) The program will run, but with unexpected results.
+- C) The program will crash.
+
+**Answer:** A) The Java compiler will throw an error.
+
+# Step 10: Arrays - Some Puzzles And Exercises
+
+Create a multiple-choice quiz based on the concepts taught in this step:
+
+**Question 1:** When creating an array of objects, what does the array hold?
+
+- A) The actual objects themselves
+- B) Copies of the objects
+- C) References to the created objects
+
+**Answer:** C) References to the created objects
+
+**Question 2:** What is the output of the following code snippet?
+
+```
+Person[] persons = new Person[3];
+persons[0] = new Person();
+persons[2] = new Person();
+System.out.println(persons[1]);
+```
+
+- A) `null`
+- B) An error will be thrown
+- C) A memory address
+
+**Answer:** A) `null`
+
+**Question 3:** What is the output of the following code snippet?
+
+```
+String[] textValues = {"Apple", "Ball", "Cat"};
+System.out.println(textValues[2].charAt(0));
+```
+
+- A) `A`
+- B) `B`
+- C) `C`
+
+**Answer:** C) `C`
+
+### Step 11: Problems With Arrays
+
+Question 1: Why is it difficult to add or remove elements in an array?
+
+- A) Because the size of an array is fixed
+- B) Because arrays are only for primitive types
+- C) Because arrays cannot store non-homogeneous types
+
+Answer: A
+
+Question 2: How can we add an element to an array?
+
+- A) By increasing the size of the array dynamically
+- B) By decreasing the size of the array dynamically
+- C) By converting the array to an ArrayList
+
+Answer: A
+
+Question 3: What is the drawback of adding or removing elements from an array?
+
+- A) It can cause an ArrayIndexOutOfBoundsException
+- B) It can be very inefficient
+- C) It can cause a NullPointerException
+
+Answer: B
+
+### Step 12: Introducing ArrayList
+
+Question 1: What is the main advantage of ArrayList over arrays?
+
+- A) ArrayList can store only primitive types
+- B) ArrayList provides operations to add and remove elements
+- C) ArrayList has a fixed size
+
+Answer: B
+
+Question 2: How do you remove an element from an ArrayList?
+
+- A) Using the remove() method
+- B) Using the delete() method
+- C) Using the clear() method
+
+Answer: A
+
+Question 3: What is the warning message displayed when adding non-homogeneous types to an ArrayList?
+
+- A) "Type safety: The method add(Object) belongs to the raw type ArrayList. References to generic type ArrayList should be parameterized."
+- B) "Unchecked call to add(E) as a member of the raw type java.util.ArrayList"
+- C) "Type mismatch: cannot convert from int to String"
+
+Answer: B
+
+### Step 13: Refactoring Student To Use ArrayList
+
+Question 1: How can we create an ArrayList that can hold only String values?
+
+- A) ArrayList items = new ArrayList()
+- B) ArrayList items = new ArrayList()
+- C) ArrayList items = new ArrayList()
+
+Answer: A
+
+Question 2: What method can be used to find the maximum value in an ArrayList?
+
+- A) Collections.max()
+- B) ArrayList.max()
+- C) ArrayList.getMaximum()
+
+Answer: A
+
+Question 3: How can we add a mark to a Student using ArrayList?
+
+- A) Using the addMark() method
+- B) Using the add() method of ArrayList
+- C) Using the add() method of the Student class
+
+Answer: A
+
+### Step 14: Enhancing Student Further
+
+Question 1: How can we remove a mark from a Student using ArrayList?
+
+- A) Using the remove() method of ArrayList
+- B) Using the removeMark() method
+- C) Using the delete() method of ArrayList
+
+Answer: B
+
+Question 2: What is the output of `System.out.println(student)` in the main method of Step 14?
+
+- A) Ranga[97,98,100]
+- B) Ranga[97,98,100,35]
+- C) Ranga[97,100,35]
+
+Answer: C
+
+Question 3: How can we find the minimum value in an ArrayList?
+
+- A) Collections.min()
+- B) ArrayList.minimum()
+- C) ArrayList.getMin()
+
+Answer: A
\ No newline at end of file
From 1da13d3175acbc7077101f1b200ed7cd257c0570 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sun, 7 May 2023 10:22:47 +0530
Subject: [PATCH 151/178] .
---
01-Quiz/{7MAY2023 => }/Q10-ArraysAndArrayList.md | 0
1 file changed, 0 insertions(+), 0 deletions(-)
rename 01-Quiz/{7MAY2023 => }/Q10-ArraysAndArrayList.md (100%)
diff --git a/01-Quiz/7MAY2023/Q10-ArraysAndArrayList.md b/01-Quiz/Q10-ArraysAndArrayList.md
similarity index 100%
rename from 01-Quiz/7MAY2023/Q10-ArraysAndArrayList.md
rename to 01-Quiz/Q10-ArraysAndArrayList.md
From 981c59e34c9981a214b8dd45e0a0b8d4fb7607ca Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sun, 7 May 2023 21:55:49 +0530
Subject: [PATCH 152/178] Update Q11-ObjectOrientedProgrammingAgain.md
---
.../Q11-ObjectOrientedProgrammingAgain.md | 460 ++++++++++++++++++
1 file changed, 460 insertions(+)
diff --git a/01-Quiz/7MAY2023/Q11-ObjectOrientedProgrammingAgain.md b/01-Quiz/7MAY2023/Q11-ObjectOrientedProgrammingAgain.md
index e69de29b..21d5bf1e 100644
--- a/01-Quiz/7MAY2023/Q11-ObjectOrientedProgrammingAgain.md
+++ b/01-Quiz/7MAY2023/Q11-ObjectOrientedProgrammingAgain.md
@@ -0,0 +1,460 @@
+## Step 01: Objects Revisited - State And Behavior
+
+
+//What defines an object's state?
+- a) Its methods
+- b) Its behavior
+- c) Its attributes
+
+Answer: c
+
+//What delivers messages to an object?
+- a) Attributes
+- b) Methods
+ -c) Constructors
+
+Answer: b
+
+//What is the effect of behavior on an object's state?
+- a) No effect
+ -b) Positive effect
+ -c) Negative effect
+
+Answer: b`
+
+## Step 02: Managing class state
+
+What corresponds to the state of a class?
+- a) Member variables
+- b) Methods
+- c) Constructors
+
+Answer: a
+
+//What is the purpose of constructors in a class?
+- a) To define behavior
+ - b) To create objects
+- c) To set attributes
+
+Answer: b
+
+//What is the purpose of the toString() method in a class?
+- a) To define behavior
+- b) To create objects
+- c) To provide a string representation of the object's state
+
+Answer: c
+
+## Step 03: Augmenting Fan With Behavior
+
+
+
+//What is the state attribute that needs to be exposed to change by Fan object users?
+- a) make
+- b) color
+- c) isOn
+- d) speed
+
+Answer: c, d
+
+//What is the purpose of the switchOn() and switchOff() methods in the Fan class?
+- a) To toggle the isOn state attribute
+- b) To toggle the speed state attribute
+- c) To create a new Fan object
+
+Answer: a
+
+//What is the purpose of the setSpeed() method in the Fan class?
+- a) To toggle the isOn state attribute
+- b) To toggle the speed state attribute
+- c) To create a new Fan object
+
+Answer: b
+
+## Step 04: Programming Exercise PE-OOP-01
+
+//What are the state attributes of a Rectangle object?
+- a) Length and width
+- b) Height and width
+- c) Length and breadth
+
+Answer: a
+
+//What is the purpose of the area() method in the Rectangle class?
+- a) To calculate the perimeter of the rectangle
+- b) To calculate the area of the rectangle
+- c) To set the length of the rectangle
+
+Answer: b
+
+//What is the purpose of the perimeter() method in the Rectangle class?
+- a) To calculate the perimeter of the rectangle
+- b) To calculate the area of the rectangle
+- c) To set the length of the rectangle
+
+Answer: a
+
+
+### Step 06: Understanding Object Composition
+
+Question 1: What are the state attributes of the Fan class?
+
+- A) make, radius, color, isOn, speed
+- B) brand, diameter, hue, isRunning, velocity
+- C) manufacturer, size, tone, isActive, rate
+
+Answer: A) make, radius, color, isOn, speed
+
+Question 2: What is object composition?
+
+- A) Combining primitive types into a complex object
+- B) Creating multiple objects of the same type
+- C) Combining different objects to create a more complex object
+
+Answer: C) Combining different objects to create a more complex object
+
+Question 3: What is the purpose of constructors in object composition?
+
+- A) To create new objects of a class
+- B) To modify the state of an object
+- C) To add behaviors to an object
+
+Answer: A) To create new objects of a class
+
+### Step 07: Programming Exercise PE-OOP-02
+
+Question 1: What are the attributes of the Book class?
+
+- A) Id, Name, Author
+- B) Title, Author, Description
+- C) Id, Title, Author
+
+Answer: A) Id, Name, Author
+
+Question 2: What is the purpose of the Review class?
+
+- A) To manage Books
+- B) To manage Authors
+- C) To manage reviews associated with a Book
+
+Answer: C) To manage reviews associated with a Book
+
+Question 3: What is the output of the following code?
+
+```
+Book book = new Book(123, "Object Oriented Programming With Java", "Ranga");
+book.addReview(new Review(10, "Great Book", 4));
+book.addReview(new Review(101, "Awesome", 5));
+System.out.println(book);
+```
+
+- A) Book-123, Object Oriented Programming With Java, Ranga, [(Review-10, Great Book", 4), (Review-101, Awesome, 5)]
+- B) Book-123, Object Oriented Programming With Java, Ranga, [(10, Great Book, 4), (101, Awesome, 5)]
+- C) Book-123, Object Oriented Programming With Java, Ranga, [(Review-10, Great Book", 5), (Review-101, Awesome, 4)]
+
+Answer: A) Book-123, Object Oriented Programming With Java, Ranga, [(Review-10, Great Book", 4), (Review-101, Awesome, 5)]
+
+### Step 07: The Need For Inheritance
+
+Question 1: What is Inheritance in Object Oriented Programming?
+
+- A) A mechanism of code reuse
+- B) A mechanism to create new objects
+- C) A mechanism to modify existing objects
+
+Answer: A) A mechanism of code reuse
+
+Question 2: What is a superclass in Inheritance relationship?
+
+- A) A class that extends another class
+- B) A class that inherits from another class
+- C) A class that is neither extended nor inherited
+
+Answer: B) A class that is inherited from another class
+
+Question 3: How does a subclass access fields and methods of its superclass?
+
+- A) By using the keyword 'super'
+- B) By using the keyword 'this'
+- C) By using the keyword 'extends'
+
+Answer: A) By using the keyword 'super'
+
+
+### Step 09: Quiz
+
+1. What is the Object class in Java?
+
+- A. A user-defined class.
+- B. A package in Java system.
+- C. A built-in Java library class.
+
+Answer: C
+
+2. Which methods of the Object class are available to objects of the Person class?
+
+- A. toString(), hashCode(), and notify().
+- B. setString(), setInt(), and notify().
+- C. toString(), getName(), and setEmail().
+
+Answer: A
+
+3. What happens when the statement `System.out.println(person)` is executed in the StudentRunner.java file?
+
+- A. The `toString()` method of the Person class is called.
+- B. The `hashCode()` method of the Person class is called.
+- C. The `notify()` method of the Person class is called.
+
+Answer: A
+
+
+# Step 12: Constructors, And Calling super()
+
+**Question 1**: What does the `super` keyword do in Java?
+a. Allows a subclass to access the attributes present in the superclass
+b. Creates a new instance of a superclass
+c. Allows a superclass to access the attributes present in the subclass
+
+**Answer**: a. Allows a subclass to access the attributes present in the superclass
+
+**Question 2**: What is the output of the `EmployeeRunner` class in Snippet-01?
+a. Employee Name: null, Email: null, Phone Number: null, Title: null, Employer: null, Employee Grade: , Salary: null
+b. Employee Name: Ranga, Email: [in28minutes@gmail.com](mailto:in28minutes@gmail.com), Phone Number: 123-456-7890, Title: Programmer Analyst, Employer: In28Minutes, Employee Grade: A, Salary: 50000.0000
+c. Error: super-class default constructor not found
+
+**Answer**: b. Employee Name: Ranga, Email: [in28minutes@gmail.com](mailto:in28minutes@gmail.com), Phone Number: 123-456-7890, Title: Programmer Analyst, Employer: In28Minutes, Employee Grade: A, Salary: 50000.0000
+
+**Question 3**: What is the output of the `EmployeeRunner` class in Snippet-10 after calling `setSalary()`?
+a. Employee Name: null, Email: null, Phone Number: null, Title: null, Employer: null, Employee Grade: , Salary: null
+b. Employee Name: Ranga, Email: [in28minutes@gmail.com](mailto:in28minutes@gmail.com), Phone Number: 123-456-7890, Title: Programmer Analyst, Employer: In28Minutes, Employee Grade: A, Salary: null
+c. Employee Name: Ranga, Email: [in28minutes@gmail.com](mailto:in28minutes@gmail.com), Phone Number: 123-456-7890, Title: Programmer Analyst, Employer: In28Minutes, Employee Grade: A, Salary: 50000.0000
+
+**Answer**: c. Employee Name: Ranga, Email: [in28minutes@gmail.com](mailto:in28minutes@gmail.com), Phone Number: 123-456-7890, Title: Programmer Analyst, Employer: In28Minutes, Employee Grade: A, Salary: 50000.0000
+
+# Step 13: Multiple Inheritance, Reference Variables And instanceof
+
+**Question 1**: Can a Java class directly inherit from two or more classes?
+a. Yes
+b. No
+
+**Answer**: b. No
+
+**Question 2**: What is the output of the `Dog` object's `toString()` method in Snippet-02?
+a. Dog@23a6e47f
+b. Pet Groom
+c. null
+
+**Answer**: a. Dog@23a6e47f
+
+**Question 3**: What is the output of the `instanceof` operator when `pet instanceof String` is executed in Snippet-02?
+a. Pet cannot be converted to java.lang.String
+b. true
+c. false
+
+**Answer**: a. Pet cannot be converted to java.lang.String
+
+# Step 14: Introducing Abstract Classes. Here are three questions with answer options:
+
+1. What is an abstract method?
+- A) A method without any parameters
+- B) A method with a method definition
+- C) A method without a method definition
+ Answer: C
+
+2. Can an abstract class be instantiated? A) Yes B) No
+Answer: B
+
+3. What is a concrete class?
+- A) A class that can be instantiated
+- B) A class that cannot be instantiated
+- C) A class with a method definition
+Answer: A
+
+
+
+
+
+## Step 14: Introducing Abstract Classes
+
+1. What is an abstract method?
+ A) A method without any parameters
+ B) A method with a method definition
+ C) A method without a method definition
+ Answer: C
+
+2. Can an abstract class be instantiated?
+ A) Yes
+ B) No
+ Answer: B
+
+3. What is a concrete class?
+ A) A class that can be instantiated
+ B) A class that cannot be instantiated
+ C) A class with a method definition
+ Answer: A`
+
+### Step 15: Abstract Classes - Design Aspects
+
+**Question 1:** What is the purpose of an abstract class?
+
+- A) To provide implementation for all its methods
+- B) To declare methods without providing implementation
+- C) To create a hierarchy of classes
+
+**Answer:** B) To declare methods without providing implementation
+
+**Question 2:** What is the advantage of using an abstract class to create a recipe hierarchy?
+
+- A) It allows for the order of steps to be defined
+- B) It allows for the implementation of each step to be defined by the sub-classes
+- C) It allows for the creation of multiple recipe types easily
+
+**Answer:** B) It allows for the implementation of each step to be defined by the sub-classes
+
+**Question 3:** Which design pattern is used in the recipe hierarchy example?
+
+- A) Observer pattern
+- B) Decorator pattern
+- C) Template method pattern
+
+**Answer:** C) Template method pattern
+
+### Step 16: Abstract Classes - Puzzles
+
+**Question 1:** Can an abstract class be created without any abstract member methods?
+
+- A) Yes
+- B) No
+
+**Answer:** A) Yes
+
+**Question 2:** Can an abstract class have member variables?
+
+- A) Yes
+- B) No
+
+**Answer:** A) Yes
+
+**Question 3:** Can an abstract class have non-abstract methods?
+
+- A) Yes
+- B) No
+
+**Answer:** A) Yes
+
+### Step 17: Introducing Interfaces
+
+**Question 1:** What is an interface in Java?
+
+- A) A class that provides implementation for all its methods
+- B) A class that declares methods without providing implementation
+- C) A class that cannot be instantiated but can be implemented by other classes
+
+**Answer:** C) A class that cannot be instantiated but can be implemented by other classes
+
+**Question 2:** Who provides the implementation of methods declared in an interface?
+
+- A) The interface itself
+- B) The implementing classes
+- C) The superclass of the interface
+
+**Answer:** B) The implementing classes
+
+**Question 3:** How can an interface be used to enforce a contract for its implementors?
+
+- A) By providing default implementations for its methods
+- B) By declaring methods without providing implementation
+- C) By creating a hierarchy of interfaces
+
+**Answer:** B) By declaring methods without providing implementation
+
+
+### Step 18: Using Interfaces To Design APIs
+
+Which of the following is not a way to ensure compatibility between teams working on different parts of an application?
+
+- a) Define an interface for the external team to implement
+- b) Work on the parts of the application simultaneously
+- c) Define an algorithm for the external team to implement directly into the application
+
+Answer: c
+
+----------
+
+What is the purpose of defining an interface between two teams working on different parts of an application?
+
+- a) To allow teams to work independently without worrying about compatibility issues
+- b) To define a contract between the two teams
+- c) To ensure that both teams use the same programming language
+
+Answer: b
+
+----------
+
+Which of the following is an implementation of the ComplexAlgorithm interface?
+
+- a) OneComplexAlgorithm
+- b) ActualComplexAlgorithm
+- c) Both a and b
+
+Answer: b
+
+### Step 19: Interfaces - Puzzles And Interesting Facts
+
+Which of the following is true about interfaces in Java?
+
+- a) An interface can be extended by another interface
+- b) An implementation of an interface needs to implement all methods declared in the interface and its super interfaces
+- c) Interfaces can have member variables
+
+Answer: a
+
+----------
+
+Which of the following is not a way to provide a default implementation for a method in an interface?
+
+- a) Include the keyword "default" in the method signature
+- b) Provide a body for the method in the interface definition
+- c) Override the method in the implementation class
+
+Answer: c
+
+----------
+
+Why is providing default method implementations useful in building and extending frameworks?
+
+- a) It allows for a new method to be added to an interface without breaking the implementation classes
+- b) It ensures that all implementation classes have the same behavior for the default method
+- c) It reduces the amount of code needed to implement the interface
+
+Answer: a
+
+### Step 20: abstract class And interface : A Comparison
+
+Which of the following is a primary use case for an interface?
+
+- a) Generalizing behavior by creating a super class
+- b) Defining a contract between two software components
+- c) Implementing multiple interfaces in a single class
+
+Answer: b
+
+----------
+
+Which of the following is a syntactical difference between an interface and an abstract class?
+
+- a) An interface can have member variable declarations, but an abstract class cannot
+- b) An abstract class can have private methods, but an interface cannot have any methods declared as private
+- c) An interface can extend multiple interfaces, but an abstract class can only extend one class or abstract class
+
+Answer: c
+
+----------
+
+What is the purpose of creating an abstract class?
+
+- a) To define a contract between two software components
+- b) To generalize behavior by creating a super class
+- c) To provide a default implementation for a method in an interface
+
+Answer: b
From 9e5c910d867d7eb566d4627a237d3d2aa2d65096 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sun, 7 May 2023 21:56:28 +0530
Subject: [PATCH 153/178] .
---
01-Quiz/{7MAY2023 => }/Q11-ObjectOrientedProgrammingAgain.md | 0
1 file changed, 0 insertions(+), 0 deletions(-)
rename 01-Quiz/{7MAY2023 => }/Q11-ObjectOrientedProgrammingAgain.md (100%)
diff --git a/01-Quiz/7MAY2023/Q11-ObjectOrientedProgrammingAgain.md b/01-Quiz/Q11-ObjectOrientedProgrammingAgain.md
similarity index 100%
rename from 01-Quiz/7MAY2023/Q11-ObjectOrientedProgrammingAgain.md
rename to 01-Quiz/Q11-ObjectOrientedProgrammingAgain.md
From 987017fd947bdbbc8d3246338e102027938523d9 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Thu, 11 May 2023 22:50:08 +0530
Subject: [PATCH 154/178] .
---
...ogrammingWithJShell-MultiplicationTable.md | 66 +++++++++++++++++++
1 file changed, 66 insertions(+)
diff --git a/01-Quiz/Q01-IntroductionToJavaProgrammingWithJShell-MultiplicationTable.md b/01-Quiz/Q01-IntroductionToJavaProgrammingWithJShell-MultiplicationTable.md
index 1e6ba027..b8a365f6 100644
--- a/01-Quiz/Q01-IntroductionToJavaProgrammingWithJShell-MultiplicationTable.md
+++ b/01-Quiz/Q01-IntroductionToJavaProgrammingWithJShell-MultiplicationTable.md
@@ -11,6 +11,16 @@
**Answer: a. JavaShell**
+JShell stands for Java Shell.
+
+Introduced in Java 9, JShell is a Read-Eval-Print Loop (REPL) tool that allows developers to run Java statements and expressions interactively in the console without having to wrap them in classes or methods. This is particularly useful for testing small bits of code, learning new features, or prototyping.
+
+To explain why the other options are incorrect:
+
+b. JavaScriptShell - This is not accurate because JShell is a feature of Java, not JavaScript. These are two different programming languages with distinct features and use cases.
+
+c. JupyterShell - This option is not correct either. Jupyter is a separate open-source project that provides a web-based interactive computing environment for multiple programming languages, including Python, Julia, and R. It has no direct connection with Java or JShell.
+
----------
2. What is the purpose of JShell?
@@ -19,7 +29,15 @@
c. To debug Java code
**Answer: b. To evaluate and execute Java code and provide immediate results**
+JShell is designed to evaluate and execute Java code and provide immediate results. This is a feature known as a Read-Eval-Print Loop (REPL), which is common in scripting languages but was introduced in Java with the release of Java 9.
+To further explain:
+
+a. To create graphical user interfaces - While Java is indeed used to create graphical user interfaces (GUIs), this is not the primary purpose of JShell. GUI creation in Java typically involves using libraries such as Swing or JavaFX, not JShell.
+
+b. To evaluate and execute Java code and provide immediate results - This is the correct answer. JShell allows developers to input Java code directly and see results immediately, without needing to compile or run a full program. This makes JShell a useful tool for testing snippets of code, learning new features of the language, or prototyping.
+
+c. To debug Java code - While you could potentially use JShell to test and debug small snippets of code, this is not its primary function. Traditional debugging usually involves tools that can step through code, inspect variable values, set breakpoints, and so on. JShell is more of an interactive console for running code and seeing immediate results.
----------
3. What command can be used to exit JShell?
@@ -28,7 +46,17 @@
c. /quit
**Answer: b. /exit**
+The command to exit JShell is indeed /exit.
+
+Here's a breakdown of each option:
+a. /end - This is not a valid command in JShell. JShell doesn't recognize this command and will give you an error if you try to use it.
+
+b. /exit - This is the correct answer. Using the /exit command in JShell will terminate the session and return you to your system's command line.
+
+c. /quit - This is not a valid command in JShell. Similar to /end, JShell doesn't recognize this command and will give you an error if you try to use it.
+
+It's worth noting that JShell also supports a variety of other slash commands (/) for various functions. For instance, /help will provide a list of all available commands and /list will show you all the code you've entered during your current JShell session.
## Step 03: Welcome to Problem Solving
@@ -39,12 +67,36 @@
- b) Subdivision
- c) Deductive Reasoning
- Answer: b) Subdivision
+
+The correct answer is indeed b) Subdivision.
+
+Here's the explanation for each option:
+
+a) Reverse Engineering - This is a process where you start with a finished product and then work backward to understand how it was made. This method is often used in software engineering to understand the source code of a program when the source code is not available. In the context of the question, reverse engineering does not apply.
+
+b) Subdivision - This is the correct answer. In problem-solving, subdivision is a technique where a complex problem is broken down into smaller, more manageable parts. This is a common technique in programming and is often used to simplify the process of writing code. In the context of the multiplication table program, subdivision is used to break down the complex problem of generating a multiplication table into simpler tasks like iterating over numbers and printing individual rows of the table.
+
+c) Deductive Reasoning - This is a process of reasoning from one or more general statements to reach a logically certain conclusion. While this is a valuable problem-solving skill, it's not the primary technique being employed in this situation. The task of creating a multiplication table is more about systematically applying a set of rules (i.e., the multiplication operation) to a range of inputs, rather than drawing conclusions from general principles.
+
+
+
2. What is the result of 5 * 3?
- a) 8
- b) 10
- c) 15
- Answer: c) 15
+
+The correct answer is indeed c) 15.
+
+Here's the explanation:
+
+Multiplication is one of the basic operations in arithmetic. When you multiply 5 by 3, you are essentially adding 5 three times.
+
+So, 5 * 3 = 5 + 5 + 5 = 15
+
+Therefore, the result of 5 times 3 is 15, making option c) the correct answer.
+
3. How many times do we repeat the calculation in this step?
- a) 5 times
@@ -68,6 +120,13 @@
- b) 5
- c) 3
- Answer: a) 5, 3
+
+The correct answer is a) 5, 3.
+
+In the expression 5 * 3, 5 and 3 are the operands. In general, an operand in programming and mathematics is a term of a mathematical operation that takes part in the operation.
+
+In this case, the operation is multiplication (*), and the two numbers (5 and 3) that are being multiplied are the operands. So, the numbers 5 and 3 are the values on which the multiplication operation is performed. Hence, the answer is a) 5, 3.
+
3. What is the modulo operator in Java?
- a) *
@@ -75,6 +134,13 @@
- c) +
- Answer: b) %
+The correct answer is b) %.
+
+In Java, the modulo operator is represented by the percentage symbol (%). This operator returns the remainder of a division operation. For example, if you divide 10 by 3, the remainder is 1. So, in Java, the expression 10 % 3 would yield the result 1.
+
+This operator is useful for many programming tasks such as determining if a number is even or odd (a number is even if it's divisible by 2 with no remainder, so num % 2 would be 0), or wrapping values within a certain range (like getting the remainder of a division by the size of an array to always get a valid index).
+
+Therefore, the modulo operator in Java is % (option b).
## Step 05: Programming Exercise PE-1 (With Solutions)
From 8b90951b1843d79fd878e588e960e00c25a23bd8 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sat, 13 May 2023 23:34:20 +0530
Subject: [PATCH 155/178] .
---
...troductionToMethods-MultiplicationTable.md | 238 ++++++++++++++++++
1 file changed, 238 insertions(+)
create mode 100644 00-Quiz-Explanation/Q02-IntroductionToMethods-MultiplicationTable.md
diff --git a/00-Quiz-Explanation/Q02-IntroductionToMethods-MultiplicationTable.md b/00-Quiz-Explanation/Q02-IntroductionToMethods-MultiplicationTable.md
new file mode 100644
index 00000000..2eea244b
--- /dev/null
+++ b/00-Quiz-Explanation/Q02-IntroductionToMethods-MultiplicationTable.md
@@ -0,0 +1,238 @@
+# 1
+
+In Java, `void` is a keyword used in method signatures. It indicates that the method does not return any value.
+
+When you define a method in Java, you typically specify the type of value the method will return. For example, if a method returns an integer, you would write `int` before the method's name. However, some methods don't need to return a value; they just perform an action. For these methods, you would use the `void` keyword to indicate that no value is returned.
+
+So, for option B) "The method does not return any value", this is the correct usage of the `void` keyword in Java. It's not associated with returning an integer (option A) or a boolean (option C), or any other type of value. That's why B) is the correct answer.
+# 2
+
+The correct answer is C) `sayHelloWorldTwice();`.
+
+Here's why:
+
+When calling a method in Java, you need to use the method name followed by parentheses. If the method accepts any arguments, they would go inside the parentheses. If it doesn't, the parentheses would be empty. So, `sayHelloWorldTwice()` is the correct syntax to call the method.
+
+However, in Java, you typically follow a statement with a semicolon (`;`). This is a kind of "period" that signifies the end of a complete instruction. So to properly call the method in a Java program, you would write `sayHelloWorldTwice();`.
+
+So, option A) `sayHelloWorldTwice` is incorrect because it is missing the parentheses and the semicolon. Option B) `sayHelloWorldTwice()` is partially correct because it includes the parentheses, but it is missing the semicolon. Option C) `sayHelloWorldTwice();` is the correct way to call a method in a Java program because it includes both the parentheses and the semicolon.
+
+# 3
+
+The correct answer is C) Defining and invoking methods are two different steps.
+
+Here's why:
+
+A) Defining a method automatically executes its statement body: This statement is incorrect. When you define a method in your Java code, it doesn't automatically get executed. It's only when you call or invoke this method in your code that the statements inside the method body get executed.
+
+B) Defining a method and invoking it are the same thing: This statement is also incorrect. Defining a method means you are writing down the method's code, specifying its name, return type, parameters, and the statements it will execute. Invoking or calling a method means you are telling your program to execute the statements inside a method that has already been defined. So, these are two distinct steps in the process of using methods in Java.
+
+C) Defining and invoking methods are two different steps: This statement is correct. As explained above, defining a method involves writing out the method's code and properties, while invoking a method involves executing the statements in the method. These are two separate actions that you perform at different times in your code. Therefore, option C is the correct answer.
+
+# 4
+
+The correct answer is A) `void printHelloWorld() { System.out.println("Hello World"); }`.
+
+Here's why:
+
+A) `void printHelloWorld() { System.out.println("Hello World"); }`: This is the correct syntax for defining a method in Java. The `void` keyword indicates that the method doesn't return any value. `printHelloWorld()` is the method name with no parameters, followed by the method body enclosed in curly braces `{}`. Inside the method body, `System.out.println("Hello World");` is a statement that prints the string "Hello World" to the console.
+
+B) `printHelloWorld() { System.out.println("Hello World"); }`: This syntax is incorrect because it's missing the return type of the method. In Java, you must specify the return type before the method name. In this case, it should be `void` since the method doesn't return any value.
+
+C) `void printHelloWorld { System.out.println("Hello World"); }`: This syntax is incorrect because it's missing the parentheses `()` after the method name. In Java, you must use parentheses after the method name, even if the method doesn't take any parameters. So, it should be `printHelloWorld()`.
+
+Therefore, option A is the correct answer.
+
+# 5
+
+
+The correct answer is B) `method_one`.
+
+In Java, both variables and method names:
+
+- Must begin with a letter, an underscore (`_`), or a dollar sign (`$`). They cannot start with a digit, so option A) `1stMethod` is not valid.
+- Can contain letters, digits, underscores, or dollar signs. However, they cannot contain hyphens or other special characters, so option C) `first-Method` is not valid.
+- Are case-sensitive. This means `myMethod`, `mymethod`, and `MYMETHOD` would be considered different method names.
+- Should not be Java reserved words. There are certain keywords like `int`, `void`, `class`, etc., which have a special meaning in Java and therefore cannot be used as method or variable names.
+
+So, option B) `method_one` is a valid method name because it starts with a letter and contains only letters and an underscore. This makes `method_one` the correct answer.
+
+# 6
+
+The correct answer is A) `/methods`.
+
+Here's why:
+
+A) `/methods`: This command lists all the methods that are currently defined in the JShell session. Therefore, this is the correct answer.
+
+B) `/list`: This command lists all the snippets of code you've entered in the current JShell session, not just the methods. So, while this command will show the methods along with other types of code snippets (like variable definitions, statements, etc.), it's not the best answer because it doesn't list just the methods.
+
+C) `/edit`: This command opens an editor where you can write or modify your code. It doesn't list the methods that are currently defined in the JShell session.
+
+So, option A) `/methods` is the correct answer because it's the command that specifically lists all the methods in the current JShell session.
+
+
+# 7
+
+The correct answer is B) Allows you to modify the method definition in a separate editor window.
+
+Here's why:
+
+A) Lists the code of the specified method: This statement is incorrect. The `/edit` command doesn't list the code of the specified method. For that, you'd typically use the `/list` command in JShell.
+
+B) Allows you to modify the method definition in a separate editor window: This statement is correct. The `/edit` command in JShell opens a text editor window where you can write or modify your code, including method definitions.
+
+C) Saves the session method definitions to a file: This statement is incorrect. The `/edit` command doesn't save the session method definitions to a file. For saving the session, you would use the `/save` command in JShell.
+
+Therefore, option B is the correct answer.
+
+# 8
+
+The correct answer is A) `void methodName(ArgType argName) { method-body }`.
+
+Here's why:
+
+A) `void methodName(ArgType argName) { method-body }`: This is the correct syntax for defining a method with an argument in Java. It starts with the `void` keyword to specify that the method doesn't return any value. `methodName` is the name of the method, and `(ArgType argName)` are the argument type and name. The method body, which contains the statements to be executed, is enclosed in curly braces `{}`.
+
+B) `methodName(ArgType argName) { method-body }`: This syntax is incorrect because it's missing the return type of the method. In Java, you must specify the return type before the method name, even if the return type is `void` (meaning the method doesn't return any value).
+
+C) `methodName(ArgType argName) { method-body; }`: This syntax is incorrect for two reasons. Firstly, it's missing the return type of the method, which should be specified before the method name. Secondly, the semicolon after `method-body` is unnecessary. In Java, a semicolon is used to end a statement, but it's not used after the closing brace of a method, class, or control structure.
+
+Therefore, option A is the correct answer.
+
+# 9
+
+The correct answer is A)
+
+```
+void printNumbers(int n) {
+ for (int i = 1; i <= n; i++) {
+ System.out.println(i);
+ }
+}
+```
+
+Here's why:
+
+A) This method is correct. It starts from 1 (`int i = 1`), and the loop continues as long as `i` is less than or equal to `n` (`i <= n`). So it includes `n` in the output, and all numbers are printed from 1 to `n` (inclusive).
+
+B) This method is almost correct, but it doesn't print the number `n`. The condition `i < n` means the loop will stop when `i` is equal to `n`, so `n` is not included in the output.
+
+C) This method starts from 0 (`int i = 0`), so it doesn't start from 1 as the question specifies. Also, similar to option B, it doesn't print the number `n` because of the condition `i < n`.
+
+Therefore, option A is the correct answer. It correctly prints all integers from 1 to `n` (inclusive).
+
+# 10
+
+The correct answer is C) The program will fail to compile due to incompatible types.
+
+Here's why:
+
+A) The program will compile and run without any errors: This statement is incorrect. If a method is defined to accept an integer argument, you can't call it with a string argument. This would be a type mismatch, and the Java compiler would not allow it.
+
+B) The program will throw a runtime error: This statement is incorrect. This situation wouldn't result in a runtime error, but a compile-time error. Java is a statically typed language, which means type checking is done at compile time. If you try to pass a string argument to a method that expects an integer, the Java compiler will catch this error and fail to compile the program.
+
+C) The program will fail to compile due to incompatible types: This statement is correct. If you try to call a method with an argument of a type that the method isn't defined to accept, the Java compiler will throw an error about incompatible types, and the program will fail to compile. So, option C is the correct answer.
+
+# 11
+
+The correct answer is A) The ability to have multiple methods with the same name in a class, but with different types of arguments.
+
+Here's why:
+
+A) The ability to have multiple methods with the same name in a class, but with different types of arguments: This statement is correct. This is known as method overloading in Java. Method overloading allows you to define multiple methods with the same name but with different parameter lists (which can vary in number, types, or order of arguments). The compiler uses these differences to determine which version of the method to call.
+
+B) The ability to have multiple methods with the same name and the same types of arguments in a class: This statement is incorrect. In Java, it's not possible to have multiple methods with the exact same name and parameter list within the same class. This would cause a compilation error because the compiler wouldn't be able to distinguish between the methods.
+
+C) The ability to have a single method with an arbitrary number of arguments: This statement is incorrect. This describes varargs (variable arguments) in Java, not method overloading. A varargs parameter allows a method to accept zero or multiple arguments of the same type, but it's not related to method overloading.
+
+Therefore, option A is the correct answer.
+
+# 12
+
+The correct answers are A) The two methods are overloaded methods, B) The two methods have the same name and different number of arguments, and C) The two methods have the same name and the same types of arguments.
+
+Here's why:
+
+A) The two methods are overloaded methods: This statement is correct. Method overloading in Java is the ability to create multiple methods of the same name, but with different parameters. These two methods have the same name (`printName`), but different parameters, so they are examples of overloaded methods.
+
+B) The two methods have the same name and different number of arguments: This statement is correct. Both methods have the name `printName`, but the first method takes two arguments (a first name and a last name), while the second method takes three arguments (a first name, a middle name, and a last name).
+
+C) The two methods have the same name and the same types of arguments: This statement is correct. Both methods have the same name (`printName`), and both accept only `String` arguments. The fact that they take a different number of arguments doesn't change the fact that the types of their arguments are the same.
+
+Therefore, all options A, B, and C are correct.
+
+# 13
+
+The correct answer is A) The output will be 3 and 6.
+
+Here's why:
+
+The method `sum(int a, int b)` is called with arguments 1 and 2, so it will print the sum of these two numbers, which is 3.
+
+The method `sum(int a, int b, int c)` is called with arguments 1, 2, and 3, so it will print the sum of these three numbers, which is 6.
+
+Therefore, the output of this code will be:
+
+Copy code
+
+`3
+6`
+
+B) The output will be 3 and 5: This is incorrect because the second method call will sum 1, 2, and 3, which equals 6, not 5.
+
+C) The code will not compile due to method overloading: This is incorrect. Method overloading (having multiple methods with the same name but different parameters) is a valid feature of Java, so this code will compile and run correctly. Therefore, option A is the correct answer.
+
+# 14
+
+The correct answer is C) A method can accept any number of arguments, and they can be of different types.
+
+Here's why:
+
+A) A method can only accept up to 2 arguments: This statement is incorrect. A method in Java can accept more than two arguments. The number of arguments is only limited by the maximum size of a method's parameter list, which is well beyond practical usage scenarios.
+
+B) A method can accept any number of arguments, but they must be of the same type: This statement is partially correct but not fully. It's true in the context of varargs (variable arguments), where a method can accept any number of arguments, but they must be of the same type. However, in general, a method can accept arguments of different types.
+
+C) A method can accept any number of arguments, and they can be of different types: This statement is correct. A method in Java can accept multiple arguments, and these arguments can be of different types. Each argument must have a type and a name. Therefore, option C is the correct answer.
+
+# 15
+
+The correct answer is A) To reduce code duplication by allowing methods with the same name but different arguments.
+
+Here's why:
+
+A) To reduce code duplication by allowing methods with the same name but different arguments: This statement is correct. Method overloading is a way to create methods that perform similar tasks but with different parameters. This enables more readable and maintainable code and reduces the need for different method names for similar tasks.
+
+B) To allow a method to return different types of values based on the input arguments: This statement is incorrect. The return type of a method in Java is not influenced by method overloading. The return type of a method is determined at the time of defining the method and does not change based on the arguments passed during the method call.
+
+C) To create multiple methods with the same name and the same number of arguments, but with different implementation: This statement is incorrect. While method overloading does involve creating multiple methods with the same name, these methods must differ in their parameter lists (either in the number, type, or order of parameters). If two methods have the same name and the same parameter list, Java would not be able to distinguish between them, leading to a compile-time error.
+
+Therefore, option A is the correct answer.
+
+# 16
+
+The correct answers are A) To end the execution of the method and B) To return the result of a computation to the calling code.
+
+Here's why:
+
+A) To end the execution of the method: This statement is correct. When a return statement is executed, the method execution is stopped, and control is returned back to the caller.
+
+B) To return the result of a computation to the calling code: This statement is correct. The primary purpose of the return statement is to return the result of a computation or an operation to the caller. The returned value can then be used in the calling code.
+
+C) To print the output of the method: This statement is incorrect. The return statement does not print anything. Printing is usually done using System.out.println() or similar methods in Java. The return statement is used to return values back to the caller, not to output them.
+
+Therefore, options A and B are the correct answers.
+
+# 17
+
+The correct answer is B) It enables sharing computed results with other code and methods, and improves breaking down a problem into sub-problems.
+
+Here's why:
+
+A) It allows the method to print the result of the computation: This statement is incorrect. The return mechanism in a method does not provide any printing capabilities. To print something, you would typically use System.out.println() or similar methods in Java. The return statement is used to return values from a method back to the calling code.
+
+B) It enables sharing computed results with other code and methods, and improves breaking down a problem into sub-problems: This statement is correct. Using return statements in methods allows for the results of computations to be used elsewhere in the program, such as in other methods or as part of further computations. This helps in breaking down complex problems into smaller, more manageable sub-problems by allowing different parts of the code to handle different sub-tasks and share their results.
+
+C) It simplifies the syntax of the method: This statement is incorrect. The return statement doesn't necessarily simplify the syntax of a method. It's a tool to pass results back to the caller, not to simplify the syntax.
+
+Therefore, option B is the correct answer.
\ No newline at end of file
From cec806b24aad7bf40c8fbd9af9ac97bf1008ee63 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sun, 21 May 2023 13:27:51 +0530
Subject: [PATCH 156/178] .
---
...-IntroductionToObjectOrientedProgrammin.md | 259 +++++++++++
.../Q06-PrimitiveDataTypesAndAlternatives.md | 331 ++++++++++++++
.../Archive/Q07-Conditionals.md | 381 ++++++++++++++++
.../Archive/Q09-ReferenceTypes.md | 429 ++++++++++++++++++
.../Q11-ObjectOrientedProgrammingAgain.md | 285 ++++++++++++
5 files changed, 1685 insertions(+)
create mode 100644 00-Quiz-Explanation/Archive/Q05-IntroductionToObjectOrientedProgrammin.md
create mode 100644 00-Quiz-Explanation/Archive/Q06-PrimitiveDataTypesAndAlternatives.md
create mode 100644 00-Quiz-Explanation/Archive/Q07-Conditionals.md
create mode 100644 00-Quiz-Explanation/Archive/Q09-ReferenceTypes.md
create mode 100644 00-Quiz-Explanation/Archive/Q11-ObjectOrientedProgrammingAgain.md
diff --git a/00-Quiz-Explanation/Archive/Q05-IntroductionToObjectOrientedProgrammin.md b/00-Quiz-Explanation/Archive/Q05-IntroductionToObjectOrientedProgrammin.md
new file mode 100644
index 00000000..9ffbdae8
--- /dev/null
+++ b/00-Quiz-Explanation/Archive/Q05-IntroductionToObjectOrientedProgrammin.md
@@ -0,0 +1,259 @@
+### Question 1
+
+What is a class in Object Oriented Programming?
+
+ * A) An instance of an object. `Incorrect: An instance of a class is an object, not the class itself`.
+ * B) A template for creating objects. `Correct: A class in Object Oriented Programming is a blueprint or template for creating objects`.
+ * C) A function to perform actions. `Incorrect: Functions (methods in Java) can be part of a class, but they are not the definition of a class`【23†source】.
+
+### Question 2
+
+What are the two main components of an object in Object Oriented Programming?
+
+ * A) State and Behavior. `Correct: An object in Object Oriented Programming consists of state (represented by attributes or properties) and behavior (represented by methods)`.
+ * B) Template and Instance. `Incorrect: These terms relate to the concept of classes and objects, but they are not the components of an object`.
+ * C) Functions and Variables. `Incorrect: While objects can contain variables (fields) and functions (methods), in the context of Object-Oriented Programming they are usually referred to as state (fields) and behavior (methods)`【24†source】.
+
+### Question 3
+
+Which of the following methods in a class sets the title attribute?
+
+ * A) setTitle(String bookTitle). `Correct: This method follows the common naming convention for a setter method, which is used to set the value of a field`.
+ * B) getTitle(). `Incorrect: This method is typically a getter method, used to retrieve the value of a field, not to set it`.
+ * C) setBook(String title). `Incorrect: While the method name implies it could set some information related to a book, it's not clear that it sets the title`【25†source】.
+
+### Question 4
+
+In a class representing a vehicle, what is the purpose of the this keyword when used within a method?
+
+ * A) To access a static variable. `Incorrect: The this keyword is used to refer to the current instance of a class, not to access static variables`.
+ * B) To differentiate between a member variable and a method argument with the same name. `Correct: The this keyword is often used in this context to avoid confusion or name clashes between a field (member variable) and a parameter`.
+ * C) To call a method within the same class. `Incorrect: While this can be used to call a method within the same class, its primary function is to reference the current object instance`【26†source】.
+
+### Question 5
+
+What is the primary purpose of using access modifiers such as public and private in Object-Oriented Programming?
+
+ * A) To make code more readable. `Incorrect: While good use of access modifiers can make code more readable by clearly indicating which parts of the code are intended for external access, this is not their primary purpose`.
+ * B) To control what external objects can access within a given object. `Correct: Access modifiers are primarily used to control the level of access other objects have to an object's fields and methods`.
+ * C) To define the scope of a variable. `Incorrect: Access modifiers do influence scope, but their primary function is to control access, not to define scope`【27†source】.
+
+### Question 6
+
+What is the purpose of private keyword in Java?
+
+ * A) To make a variable or method accessible only within the class. `Correct: The private access modifier restricts access to the field or method to the class in which it is declared`.
+ * B) To make a variable or method accessible outside the class. `Incorrect: The private keyword makes a variable or method less accessible, not more. A public keyword would make a variable or method accessible outside the class`.
+ * C) To make a variable or method static. `Incorrect: The keyword for making a variable or method static is static, not private`【28†source】.
+
+### Question 7
+
+What are the methods used to access and modify private member variables in a class?
+
+ * A) Public methods. `Incorrect: While technically correct, since getter and setter methods are usually public, this is too broad of a term`.
+ * B) Getter and Setter methods. `Correct: Getter and Setter methods are specifically used to access and modify private member variables in a class`.
+ * C) Static methods. `Incorrect: While static methods can access and modify static variables, they are not typically used to access and modify instance variables`【29†source】.
+
+### Question 8
+
+What is the main principle that is violated when an object directly accesses the state of another object without using any methods?
+
+ * A) Inheritance. `Incorrect: Inheritance is a principle that allows a class to inherit fields and methods from another class. It is not related to the direct access of another object's state`.
+ * B) Encapsulation. `Correct: Encapsulation is the principle that an object's state should be accessed and modified through its methods, not directly`.
+ * C) Polymorphism. `Incorrect: Polymorphism is a principle that allows a method to behave differently depending on the object that it is acting upon. It is not related to the direct access of another object's state`【30†source】.
+
+### Question 9
+
+In a Java class, what is the purpose of a getter method?
+
+ * A) To modify the value of a private member variable. `Incorrect: A getter method is used to access or retrieve the value of a private member variable, not to modify it`.
+ * B) To access the value of a private member variable. `Correct: A getter method's purpose is to access or retrieve the value of a private member variable`.
+ * C) To perform a calculation with a private member variable. `Incorrect: While a getter method might be used as part of a calculation, its primary purpose is to retrieve the value of a variable, not to perform calculations`【31†source】.
+
+### Question 10
+
+Which of the following best describes the concept of state in Object-Oriented Programming?
+
+ * A) The condition of an object at a given time, represented by member variables. `Correct: In Object-Oriented Programming, the state of an object is the data it contains at any given moment, represented by its member variables`.
+ * B) The actions an object can perform, represented by methods. `Incorrect: This describes behavior, not state`.
+ * C) The relationship between two objects. `Incorrect: While relationships between objects are a significant aspect of OOP, they don't define the state of an individual object`【32†source】.
+
+### Question 11
+
+What is the primary reason for using a getter method in a Java class?
+
+ * A) To ensure that an object's member variables are accessed according to the encapsulation principle. `Correct: Getter methods are used to provide access to an object's data while still maintaining the principles of encapsulation`.
+ * B) To define a new method that performs a calculation with an object's member variables. `Incorrect: While a getter method can be used as part of a calculation, that's not the primary reason to use one`.
+ * C) To initialize an object's member variables with default values. `Incorrect: Initialization of member variables is usually done in constructors or with direct assignment, not with getter methods`【33†source】.
+
+### Question 12
+
+Which of the following correctly defines a getter method for a private member variable name in a Java class?
+
+ * A) `Correct: This is the conventional way to define a getter method in Java. It's public, has a return type matching the variable type, and returns the private variable`.
+
+```java
+public String getName() {
+ return name;
+}
+```
+- B) `Incorrect: This seems to be a setter method rather than a getter method, as it takes a parameter and assigns it to the variable`.
+
+```java
+public void getName(String newName) {
+ name = newName;
+}
+```
+
+- C) `Incorrect: This method signature includes a parameter, which is unusual for a getter method. Additionally, it might create confusion between the method parameter and the class field`.
+
+```java
+public String getName(String name) {
+ return this.name;
+}
+```
+
+【34†source】.
+
+### Question 13
+
+What is the primary purpose of a getter method?
+
+- A) To modify the value of an object's private member variable. `Incorrect: Getter methods are used to access or return the value of a private member variable, not to modify it`.
+- B) To allow controlled access to an object's private member variable. `Correct: The primary purpose of a getter method is to provide controlled access to an object's private member variable`.
+- C) To set a default value for an object's private member variable. `Incorrect: Default values for an object's private member variables are usually set in a constructor or at the time of variable declaration, not in a getter method`【35†source】.
+
+### Question 14
+
+Consider the following code snippet. What will be the output?
+
+```java
+public class MotorBike {
+ private int speed;
+
+ public int getSpeed() {
+ return speed;
+ }
+}
+
+public class MotorBikeRunner {
+ public static void main(String[] args) {
+ MotorBike bike = new MotorBike();
+ System.out.println("Current Bike Speed is : " + bike.getSpeed());
+ }
+}
+```
+
+- A) The code will not compile because the speed variable is not initialized. `Incorrect: In Java, instance variables are automatically initialized to a default value if not explicitly initialized. For integer variables, this default value is 0`.
+- B) The output will be: Current Bike Speed is : 0. `Correct: Since the speed variable is not explicitly initialized, its value is set to the default value of 0`.
+- C) The output will be: Current Bike Speed is : null. `Incorrect: Null is the default value for object references and not for primitive types like int`【36†source】.
+
+### Question 15
+
+What are the default values for object member variables when they are not explicitly initialized?
+
+- A) null for reference types, and the type's minimum value for primitive types. `Incorrect: While reference types are initialized to null, primitive types are not initialized to their minimum value`.
+- B) null for reference types, and 0 for primitive types. `Correct: Reference types are initialized to null and primitive types like int, char, float, boolean etc., are initialized to 0, '\u0000', 0.0f, and false respectively`.
+- C) The type's maximum value for primitive types, and null for reference types. `Incorrect: Primitive types are not initialized to their maximum value`【37†source】.
+
+### Question 16
+
+What is one of the advantages of encapsulation in Object-Oriented Programming?
+
+- A) Code Reuse. `Incorrect: Code reuse is associated more with inheritance and polymorphism than with encapsulation`.
+- B) Code Compression. `Incorrect: Encapsulation does not inherently lead to code compression`.
+- C) Code Simplification. `Correct: Encapsulation simplifies code by hiding its complexity. It allows the encapsulating object to change its internal implementation without affecting the code that uses the object`【38†source】.
+### Question 17
+
+In the given example, which method is responsible for setting the speed of a MotorBike object while ensuring it is not negative?
+
+- A) setSpeed(). `Correct: The setSpeed() method is typically responsible for setting the speed of a MotorBike object. It can include validation to ensure the speed is not negative`.
+- B) increaseSpeed(). `Incorrect: The increaseSpeed() method might increase the speed of the MotorBike object, but it is not responsible for directly setting the speed`.
+- C) decreaseSpeed(). `Incorrect: The decreaseSpeed() method might decrease the speed of the MotorBike object, but it is not responsible for directly setting the speed`【39†source】.
+
+### Question 18
+
+How can code duplication be reduced when implementing validation checks for the increaseSpeed() and decreaseSpeed() methods?
+
+- A) By using separate validation checks for each method. `Incorrect: Using separate validation checks for each method would actually lead to code duplication`.
+- B) By calling the setSpeed() method with appropriate parameters inside both methods. `Correct: By calling the setSpeed() method (which could contain the necessary validation checks) from within the increaseSpeed() and decreaseSpeed() methods, we can reuse the validation logic and thus reduce code duplication`.
+- C) By using a global validation check. `Incorrect: Using a global validation check can be problematic as it may not apply universally to all situations and can lead to code coupling`【40†source】.
+
+### Question 19
+
+What is the purpose of encapsulation in the context of protecting an object's state?
+
+- A) To prevent other objects from directly accessing the object's state. `Correct: Encapsulation is a principle of Object-Oriented Programming that helps protect an object's state by hiding its data (fields) and providing methods for data access and manipulation`.
+- B) To allow other objects to directly access the object's state. `Incorrect: Encapsulation does not allow other objects to directly access the object's state, instead, it provides controlled access via methods`.
+- C) To create a new object with the same state as the original object. `Incorrect: Encapsulation does not deal with creating new objects with the same state as existing ones`【41†source】.
+
+### Question 20
+
+In the given example, which method is used to start the MotorBike?
+
+- A) begin(). `Incorrect: The method name to start the MotorBike is not given in the question. However, in conventional programming practice, methods such as "start" or "run" are often used`.
+- B) start(). `Correct: In common practice, the method to start a MotorBike or similar objects could be named "start"`.
+- C) initiate(). `Incorrect: Although "initiate" could be a valid method name, it's not as commonly used as "start"`【42†source】.
+
+### Question 22
+
+What is the purpose of a constructor in a Java class?
+
+- a) To create an instance of the class with the specified initial state. `Correct: A constructor in Java is used to create an instance of a class and can initialize the state of the object`.
+- b) To perform calculations on the class variables. `Incorrect: While constructors can contain code that performs calculations, this is not their primary purpose`.
+- c) To modify the state of an object after it has been created. `Incorrect: Constructors are used to initialize an object when it is created, not to modify its state after creation`.
+- d) To destroy an object when it is no longer needed. `Incorrect: In Java, destruction of objects is managed by the Garbage Collector, not by constructors`【43†source】.
+
+### Question 6
+
+What is a default constructor in Java?
+
+- a) A constructor that is automatically provided by the compiler if no other constructors are defined. `Correct: If no constructors are defined in a Java class, the compiler automatically provides a default constructor with no arguments`.
+- b) A constructor with a single argument. `Incorrect: The number of arguments has no bearing on whether a constructor is considered default`.
+- c) A constructor that takes an unlimited number of arguments. `Incorrect: A default constructor does not take an unlimited number of arguments, it takes no arguments`.
+- d) A constructor that initializes all instance variables to their default values. `Incorrect: While a default constructor can be used to initialize variables, its defining feature is that it is provided by the compiler when no other constructors are defined`【44†source】.
+
+### Question 23
+
+What is a constructor in Java?
+
+- a) A special method with the same name as the class. `Correct: A constructor is a special method in a class, with the same name as the class`.
+- b) A method that returns a value. `Incorrect: Constructors do not return a value`.
+- c) A method that can be called directly. `Incorrect: Constructors are not called directly; they are called when an instance of the class is created using the new keyword`.
+- d) A method that can only accept zero arguments. `Incorrect: Constructors can take any number of arguments, including zero`【45†source】.
+
+### Question 24
+
+How is a constructor invoked in Java?
+
+- a) By calling the method directly. `Incorrect: Constructors are not called directly, they are invoked when an instance of the class is created`.
+- b) By using the new keyword while creating an object of the class. `Correct: Constructors are invoked using the new keyword when an object of the class is created`.
+- c) By declaring the constructor as static. `Incorrect: Static methods belong to the class, not the instance of the class. Constructors are not static and cannot be declared as such`.
+- d) By using the this keyword while creating an object of the class. `Incorrect: The this keyword refers to the current instance of the class and is not used to invoke a constructor`【46†source】.
+
+### Question 25
+
+Can a constructor accept multiple arguments in Java?
+
+- a) No, a constructor can only accept zero or one argument. `Incorrect: A constructor in Java can accept any number of arguments`.
+- b) Yes, a constructor can accept multiple arguments. `Correct: A constructor in Java can accept multiple arguments`.
+- c) Only the default constructor can accept multiple arguments. `Incorrect: The default constructor does not take any arguments`.
+- d) It depends on the access modifiers of the constructor. `Incorrect: The number of arguments a constructor can take does not depend on its access modifiers`【47†source】.
+
+### Question 26
+
+What is a default constructor in Java?
+
+- a) A constructor that accepts no arguments. `Correct: A default constructor is a no-argument constructor`.
+- b) A constructor that is defined by the programmer. `Incorrect: A default constructor is provided by the compiler if no constructor is defined by the programmer`.
+- c) A constructor that is generated by the compiler when no constructor is defined. `Correct: If no constructor is defined in the class, the Java compiler automatically provides a default constructor`.
+- d) A constructor that is called automatically when an object is created. `Incorrect: While all constructors are invoked when an object is created, not all are default constructors`【48†source】.
+
+### Question 27
+
+What happens when a class has no constructor defined in Java?
+
+- a) The code fails to compile. `Incorrect: If a class in Java does not have a constructor defined, the code will still compile`.
+- b) A default constructor is generated by the compiler. `Correct: If no constructor is explicitly defined in a Java class, the compiler automatically generates a default constructor`.
+- c) The code compiles and runs without any issues. `Incorrect: While the code would still compile and could run without issues, this answer is misleading because it does not mention the automatic generation of a default constructor`.
+- d) The class cannot be instantiated. `Incorrect: Even if a constructor is not defined, a class can still be instantiated using the default constructor`【49†source】.
\ No newline at end of file
diff --git a/00-Quiz-Explanation/Archive/Q06-PrimitiveDataTypesAndAlternatives.md b/00-Quiz-Explanation/Archive/Q06-PrimitiveDataTypesAndAlternatives.md
new file mode 100644
index 00000000..879dd81e
--- /dev/null
+++ b/00-Quiz-Explanation/Archive/Q06-PrimitiveDataTypesAndAlternatives.md
@@ -0,0 +1,331 @@
+Step 01: The Integer Types
+
+Question 1: Which of the following wrapper classes corresponds to the int primitive type in Java?
+
+- A) Byte (Incorrect: The `Byte` class corresponds to the byte primitive type, not int.)
+- B) Integer (Correct: The `Integer` class is the wrapper class for the `int` primitive type. It provides methods to work with int values.)
+- C) Short (Incorrect: The `Short` class corresponds to the short primitive type, not int.)
+
+Explanation:
+
+- Option A is incorrect because the `Byte` class corresponds to the byte primitive type, not int.
+- Option B is correct because the `Integer` class is the wrapper class specifically designed to work with int values.
+- Option C is incorrect because the `Short` class corresponds to the short primitive type, not int.
+
+Question 2: What is the maximum value of a short data type in Java?
+
+- A) 127
+- B) 32767 (Correct: The maximum value of a `short` is 32767)
+- C) 2147483647 (Incorrect: The value 2147483647 is the maximum value for the `int` data type, not short.)
+
+Explanation:
+
+- Option A is incorrect because 127 is the maximum value for the `byte` data type, not short.
+- Option B is correct because 32767 is the maximum value for the `short` data type in Java.
+- Option C is incorrect because 2147483647 is the maximum value for the `int` data type, not short.
+
+Question 3: What type of cast is used to store a smaller data value in a larger data type variable?
+
+- A) Implicit cast (Correct: Implicit casting is used to automatically convert a smaller data type to a larger data type)
+- B) Explicit cast
+
+Explanation:
+
+- Option A is correct because implicit casting is used to automatically convert a smaller data type to a larger data type without any loss of data.
+- Option B is incorrect because explicit casting is used when converting a larger data type to a smaller data type and requires explicit specification.
+
+
+
+Step 02: Integer Representations, And Other Puzzles
+
+Question 1: What are the three number systems supported by Java for integers?
+
+- A) Decimal, Octal, and Binary
+- B) Decimal, Octal, and Hexadecimal (Correct: The three number systems supported by Java for integers are decimal, octal, and hexadecimal)
+- C) Decimal, Binary, and Hexadecimal (Incorrect: Binary is also a number system supported by Java for integers)
+
+Explanation:
+
+- Option A is incorrect because it doesn't include hexadecimal, which is one of the number systems supported by Java for integers.
+- Option B is correct because decimal, octal, and hexadecimal are the three number systems supported by Java for integers.
+- Option C is incorrect because it includes binary, but it doesn't include octal.
+
+Question 2: Which of the following is the correct representation for the value 16 in a hexadecimal system?
+
+- A) 0x10 (Correct: In a hexadecimal system, 16 is represented as 0x10)
+- B) 010 (Incorrect: This represents the value 10 in an octal system)
+- C) 0x16 (Incorrect: This represents the value 22 in a hexadecimal system)
+
+Explanation:
+
+- Option A is correct because in a hexadecimal system, the prefix "0x" is used, followed by the digits representing the value. Therefore, 16 is represented as 0x10.
+- Option B is incorrect because "010" represents the value 10 in an octal system, not hexadecimal.
+- Option C is incorrect because "0x16" represents the value 22 in a hexadecimal system, not 16.
+
+Question 3: What is the difference between prefix and post-fix increment operators in Java?
+
+- A) Prefix increment takes place before the assignment, and post-fix increment takes place after the assignment. (Correct: Prefix increment happens before the assignment, while postfix increment happens after the assignment.)
+- B) Prefix increment takes place after the assignment, and post-fix increment takes place before the assignment. (Incorrect: The order of increment is reversed in the explanation)
+- C) There is no difference between prefix and post-fix increment operators in Java. (Incorrect: There is a difference in the order of increment)
+
+Explanation:
+
+- Option A is correct because prefix increment (++variable) happens before the assignment, meaning the variable is incremented and then used in the expression.
+- Option B is incorrect because the explanation states that postfix increment happens before the assignment, which is incorrect.
+- Option C is incorrect because there is indeed a difference between prefix and postfix increment operators in Java.
+
+
+
+Step 03: Classroom Exercise CE-01 (With Solutions)
+
+Question 1: What is the purpose of the BiNumber class?
+
+- A) To store a single integer and perform basic arithmetic operations
+- B) To store a pair of integers and perform basic arithmetic operations (Correct: The purpose of the BiNumber class is to store a pair of integers and perform basic arithmetic operations)
+- C) To store a list of integers and perform basic arithmetic operations
+
+Explanation:
+
+- Option A is incorrect because it mentions storing a single integer, while the BiNumber class is specifically designed to store a pair of integers.
+- Option B is correct because the BiNumber class is used to store a pair of integers and provides methods to perform basic arithmetic operations on those numbers.
+- Option C is incorrect because it mentions storing a list of integers, which is not the purpose of the BiNumber class.
+
+Question 2: Which method is used to double the values of both numbers in a BiNumber object?
+
+- A) double()
+- B) doubleNumbers() (Correct: The `doubleNumbers()` method is used to double the values of both numbers in a BiNumber object)
+- C) doubleValue()
+
+Explanation:
+
+- Option A is incorrect because `double()` is not a valid method for doubling the values of both numbers in a BiNumber object.
+- Option B is correct because the `doubleNumbers()` method specifically performs the operation of doubling the values of both numbers in a BiNumber object.
+- Option C is incorrect because `doubleValue()` is not the method responsible for doubling both numbers in a BiNumber object.
+
+Question 3: What will be the output of the following code snippet?
+
+```java
+BiNumber numbers = new BiNumber(4, 5);
+System.out.println(numbers.add());
+numbers.doubleValue();
+System.out.println(numbers.getNumber1());
+System.out.println(numbers.getNumber2());
+```
+
+- A) 9, 8, 10
+- B) 9, 8, 5
+- C) 9, 4, 5 (Correct: The output will be 9, 4, 5 after adding the numbers and doubling the value of the BiNumber object)
+
+Explanation:
+
+- The first line creates a BiNumber object with values 4 and 5.
+- The second line prints the result of adding the two numbers, which is 9.
+- The third line calls the `doubleValue()` method on the BiNumber object, doubling both numbers internally.
+- The fourth line prints the first number of the BiNumber object, which is now 4.
+- The fifth line prints the second number of the BiNumber object, which remains 5.
+- Therefore, the output will be 9, 4, 5.
+
+
+
+Step 05: Floating-Point Types
+
+Question 1: What is the default type for floating-point literals in Java?
+
+- A) float
+- B) double (Correct: The default type for floating-point literals in Java is `double`)
+
+Explanation:
+
+- Option A is incorrect because the default type for floating-point literals in Java is `double`.
+- Option B is correct because `double` is the default type for floating-point literals in Java.
+
+Question 2: How can you create a float literal?
+
+- A) float f = 34.5
+- B) float f = 34.5f; (Correct: To create a float literal, you need to append the suffix `f` to the value)
+- C) float f = (float)34.5
+
+Explanation:
+
+- Option A is incorrect because 34.5 without the `f` suffix is considered a `double` literal, not a `float` literal.
+- Option B is correct because adding the `f` suffix to the value makes it a `float` literal.
+- Option C is incorrect because explicitly casting the value to a `float` is another way to create a `float` literal, but it is not necessary when assigning a literal value directly.
+
+Question 3: Which type of casting is needed to convert a double value to a float value?
+
+- A) Implicit casting
+- B) Explicit casting (Correct: Explicit casting is required to convert a `double` value to a `float` value)
+
+Explanation:
+
+- Option A is incorrect because implicit casting is not sufficient to convert a `double` value to a `float` value. It could result in a loss of precision.
+- Option B is correct because explicit casting, specifically `(float)`, is needed to convert a `double` value to a `float` value. It explicitly tells the compiler to perform the conversion, even though there may be potential loss of precision.
+
+
+
+Step 06: Introducing BigDecimal
+
+Question 1: What is the main reason for using the BigDecimal data type in Java?
+
+- To represent floating-point numbers with higher precision (Correct: The main reason for using the BigDecimal data type is to represent floating-point numbers with higher precision)
+- To perform faster calculations
+- To store large integer values
+
+Explanation:
+
+- Option A is correct because the BigDecimal data type is used to represent floating-point numbers with higher precision, avoiding issues with rounding errors that can occur with other floating-point types.
+- Option B is incorrect because the primary purpose of BigDecimal is precision, not performance.
+- Option C is incorrect because BigDecimal is not specifically designed for storing large integer values; it is more focused on decimal numbers with high precision.
+
+Question 2: What is the best way to construct a BigDecimal object to achieve high precision?
+
+- Using integer literals
+- Using double literals
+- Using string literals (Correct: The best way to construct a BigDecimal object to achieve high precision is by using string literals)
+
+Explanation:
+
+- Option A is incorrect because using integer literals might result in the loss of precision when constructing a BigDecimal object.
+- Option B is incorrect because using double literals may introduce rounding errors when constructing a BigDecimal object.
+- Option C is correct because using string literals, such as "0.12345678901234567890", allows you to specify the exact precision and avoid any potential rounding errors.
+
+Question 3: What is the main characteristic of BigDecimal objects?
+
+- Mutable
+- Immutable (Correct: BigDecimal objects are immutable, meaning their values cannot be changed once created)
+- Synchronized
+
+Explanation:
+
+- Option A is incorrect because BigDecimal objects are immutable, meaning their values cannot be changed once created.
+- Option B is correct because BigDecimal objects have the characteristic of immutability, ensuring that their values remain unchanged.
+- Option C is incorrect because synchronization is not a characteristic specific to BigDecimal objects. It is related to thread safety.
+
+
+
+Step 06: BigDecimal Operations
+
+Question: Which of the following methods can be used for arithmetic operations on BigDecimal objects?
+
+- a. add()
+- b. multiply()
+- c. subtract()
+- d. All of the above (Correct: All of the mentioned methods can be used for arithmetic operations on BigDecimal objects)
+
+Explanation:
+
+- Option a is correct because the `add()` method is used for addition of BigDecimal objects.
+- Option b is correct because the `multiply()` method is used for multiplication of BigDecimal objects.
+- Option c is correct because the `subtract()` method is used for subtraction of BigDecimal objects.
+- Option d is correct because all of the mentioned methods (add(), multiply(), and subtract()) can be used for arithmetic operations on BigDecimal objects.
+
+Question: Can you perform arithmetic operations directly between a BigDecimal object and a primitive data type, like an int or a double?
+
+- a. Yes
+- b. No (Correct: No, arithmetic operations between BigDecimal objects and primitive data types require explicit conversion)
+
+Explanation:
+
+- Option a is incorrect because arithmetic operations between BigDecimal objects and primitive data types cannot be performed directly without explicit conversion.
+- Option b is correct because explicit conversion, using methods like `BigDecimal.valueOf()`, is required to perform arithmetic operations between BigDecimal objects and primitive data types.
+
+Question: How can you perform an arithmetic operation between a BigDecimal object and a primitive int value?
+
+- a. Convert the int to a BigDecimal using BigDecimal.valueOf() (Correct: To perform an arithmetic operation between a BigDecimal object and a primitive int value, you need to convert the int to a BigDecimal using BigDecimal.valueOf())
+
+Explanation:
+
+- Option a is correct because to perform an arithmetic operation between a BigDecimal object and a primitive int value, you need to convert the int to a BigDecimal using the `BigDecimal.valueOf()` method.
+- Using this method, you can create a BigDecimal object representing the int value and then perform arithmetic operations with other BigDecimal objects.
+
+
+
+Step 08: boolean, Relational and Logical Operators
+
+Question: Which of the following operators is a logical operator in Java?
+
+- a) >
+- b) &&
+- c) <= (Correct: The logical operator in Java is represented by the symbol &&)
+
+Explanation:
+
+- Option a is incorrect because the ">" operator is a relational operator used for comparison.
+- Option b is correct because the "&&" operator is the logical AND operator in Java, which combines two boolean expressions.
+- Option c is incorrect because the "<=" operator is a relational operator used for comparison, not a logical operator.
+
+Question: Given the following code snippet, what will be the value of result?
+
+```java
+int a = 10;
+int b = 5;
+boolean result = (a > b) && (a < 2 * b);
+```
+
+- a) true (Correct: The value of result will be true)
+- b) false
+
+Explanation:
+
+- In the given code snippet, the expression `(a > b) && (a < 2 * b)` is evaluated.
+- `(a > b)` evaluates to true because 10 is greater than 5.
+- `(a < 2 * b)` also evaluates to true because 10 is less than 2 times 5, which is 10.
+- The logical AND operator `&&` combines these two boolean expressions and returns true only if both expressions are true.
+- Since both expressions are true, the value of `result` will be true.
+
+Question: What will the following expression evaluate to?
+
+```java
+boolean x = true;
+boolean y = false;
+boolean z = !(x || y);
+```
+
+- a) true
+- b) false (Correct: The expression will evaluate to false)
+
+Explanation:
+
+- The expression `(x || y)` evaluates to true because at least one of the operands (x or y) is true.
+- The `!` operator negates the result, so `!(x || y)` evaluates to false.
+- Therefore, the value of `z` will be false.
+
+
+
+Step 10: Character Types
+
+Question 1: What is the Unicode representation of the double quotation mark?
+
+- \u0021
+- \u0022 (Correct: The Unicode representation of the double quotation mark is \u0022)
+- \u0023
+
+Explanation:
+
+- Option \u0021 represents the Unicode character for exclamation mark (!), not the double quotation mark.
+- Option \u0022 is correct because it represents the Unicode character for double quotation mark (").
+- Option \u0023 represents the Unicode character for hash or number sign (#), not the double quotation mark.
+
+Question 2: What data type in Java is used to store Unicode characters?
+
+- String
+- char (Correct: The `char` data type in Java is used to store Unicode characters)
+- int
+
+Explanation:
+
+- Option String is incorrect because `String` is a data type used to store sequences of characters, not a single Unicode character.
+- Option char is correct because the `char` data type is specifically designed to store a single Unicode character.
+- Option int is incorrect because `int` is used to store integer values, not Unicode characters.
+
+Question 3: What happens when you perform the following operation in Java: `char cn = 65;`?
+
+- A character with a Unicode value of 65 is stored in the variable cn. (Correct: The character with Unicode value 65, which is 'A', is stored in the variable cn)
+- An integer value of 65 is stored in the variable cn.
+- A compilation error occurs.
+
+Explanation:
+
+- Option A is correct because assigning the value 65 to a char variable `cn` will store the character 'A' in `cn`. In Java, characters are internally represented using Unicode values.
+- Option B is incorrect because 65 is the Unicode value of 'A', not an integer value.
+- Option C is incorrect because there is no compilation error in assigning a Unicode value to a char variable.
diff --git a/00-Quiz-Explanation/Archive/Q07-Conditionals.md b/00-Quiz-Explanation/Archive/Q07-Conditionals.md
new file mode 100644
index 00000000..8510fb5f
--- /dev/null
+++ b/00-Quiz-Explanation/Archive/Q07-Conditionals.md
@@ -0,0 +1,381 @@
+### Question 28
+
+What is the if statement used for in Java?
+
+- a) To execute some code when a boolean condition is true. `Correct: An if statement in Java is used to execute a block of code when a specified condition is true`.
+- b) To execute some code when a boolean condition is false. `Incorrect: This is not the primary purpose of the if statement. Though an "else" clause following an if statement can execute code when the condition is false, the primary purpose of the if statement is to execute code when a condition is true`.
+- c) To execute some code regardless of the boolean condition. `Incorrect: An if statement is condition-dependent. Code within its block is executed only when the condition is true`【50†source】.
+
+### Question 29
+
+What is the difference between if and if-else statements in Java?
+
+- a) There is no difference, they do the same thing. `Incorrect: There is a difference between if and if-else statements. The if-else statement includes a default action when the if condition is false`.
+- b) If statement executes code only when the condition is true, whereas if-else statement executes code when the condition is false. `Correct: An if statement executes code only when its condition is true. An if-else statement adds a default action that is executed when the if condition is false`.
+- c) If statement executes code only when the condition is false, whereas if-else statement executes code when the condition is true. `Incorrect: This is the opposite of how if and if-else statements work in Java`【51†source】.
+
+### Question 30
+
+What is the output of the following code snippet in Java?
+
+```java
+int i = 10;
+if(i < 5) {
+ System.out.println("i is less than 5");
+} else if(i > 20) {
+ System.out.println("i is greater than 20");
+} else {
+ System.out.println("i is between 5 and 20");
+}
+```
+
+- a) "i is less than 5" `Incorrect: The value of i is 10, which is not less than 5`.
+- b) "i is greater than 20" `Incorrect: The value of i is 10, which is not greater than 20`.
+- c) "i is between 5 and 20" `Correct: The value of i is 10, which falls between 5 and 20`【52†source】.
+
+### Question 31
+
+What is the purpose of the if-else if-else statement in Java?
+
+- a) To execute some code when a boolean condition is true. `Incorrect: This is a feature of the if statement, not specifically the if-else if-else statement`.
+- b) To execute some code when multiple conditions are true. `Incorrect: An if-else if-else statement is used to check multiple conditions, but it only executes the first block of code whose condition is true`.
+- c) To execute some code when one and only one condition is true. `Correct: In an if-else if-else statement, once a true condition is found and its corresponding code block is executed, the remaining conditions are not checked`【53†source】.
+
+### Question 32
+
+What happens if multiple conditions in the if-else if-else statement evaluate to true in Java?
+
+- a) All corresponding code blocks are executed. `Incorrect: Only the first block of code with a true condition is executed in an if-else if-else statement`.
+- b) Only the first corresponding code block is executed. `Correct: In an if-else if-else statement, once a true condition is found and its corresponding code block is executed, the remaining conditions are not checked`.
+- c) Only the last corresponding code block is executed. `Incorrect: Only the first block of code with a true condition is executed in an if-else if-else statement`【54†source】.
+
+### Question 33
+
+What is the output of the following code snippet in Java?
+
+```java
+int i = 15;
+if(i < 5) {
+ System.out.println("i is less than 5");
+} else if(i > 20) {
+ System.out.println("i is greater than 20");
+} else if(i < 10) {
+ System.out.println("i is less than 10");
+} else {
+ System.out.println("i is between 10 and 20");
+}
+```
+
+- a) "i is less than 5" `Incorrect: The value of i is 15, which is not less than 5`.
+- b) "i is greater than 20" `Incorrect: The value of i is 15, which is not greater than 20`.
+- c) "i is less than 10" `Incorrect: The value of i is 15, which is not less than 10`.
+- d) "i is between 10 and 20" `Correct: The value of i is 15, which falls between 10 and 20`【55†source】.
+
+### Question 34
+
+What is the output of the following code snippet?
+
+```java
+public static void puzzleOne() {
+ int k = 15;
+ if(k > 20) {
+ System.out.println(1);
+ } else if(k > 10) {
+ System.out.println(2);
+ } else if(k < 20) {
+ System.out.println(3);
+ } else {
+ System.out.println(4);
+ }
+}
+```
+
+- a) 1 `Incorrect: The value of k is 15, which is not greater than 20`.
+- b) 2 `Correct: The value of k is 15, which is greater than 10`.
+- c) 3 `Incorrect: The value of k is 15, which is less than 20, but the previous condition (k > 10) was already met and its block was executed`.
+- d) 4 `Incorrect: The else block would only execute if none of the previous conditions were met, but the condition (k > 10) was met`【56†source】.
+
+### Question 35
+
+What is the output of the following code snippet?
+
+```java
+public static void puzzleTwo() {
+ int l = 15;
+ if(l < 20)
+ System.out.println("l < 20");
+ if(l > 20)
+ System.out.println("l > 20");
+ else
+ System.out.println("Who Am I?");
+}
+```
+
+- a) l < 20 `Incorrect: While it's true that l < 20, the subsequent else clause is associated with the second if statement (l > 20), not the first one`.
+- b) l > 20 `Incorrect: The value of l is 15, which is not greater than 20`.
+- c) Who Am I? `Correct: The else clause is associated with the second if statement, and since l is not greater than 20, "Who Am I?" is printed`【57†source】.
+
+### Question 36
+
+What is the output of the following code snippet?
+
+```java
+public static void puzzleThree() {
+ int m = 15;
+ if(m > 20)
+ if(m < 20)
+ System.out.println("m > 20"); else
+ System.out.println("Who Am I?");
+}
+```
+
+- a) m > 20 `Incorrect: The outer condition (m > 20) is not met, so none of the code inside the outer if statement is executed`.
+- b) Who Am I? `Incorrect: The outer condition (m > 20) is not met, so none of the code inside the outer if statement is executed`.
+- c) Nothing is printed. `Correct: The outer condition (m > 20) is not met, so none of the code inside the outer if statement is executed`【58†source】.
+
+
+### Question 37
+
+What is the output of the following code snippet?
+
+```java
+int i = 0;
+if(i) {
+ System.out.println("i");
+}
+```
+
+- a) i `Incorrect: This code will not compile because i is an integer and the if statement requires a boolean`.
+- b) Compiler Error `Correct: This code will not compile because i is an integer and the if statement requires a boolean`.
+- c) Nothing is printed `Incorrect: This code will not compile, so there is no opportunity for anything to be printed`【59†source】.
+
+### Question 38
+
+What is the output of the following code snippet?
+
+```java
+public static void puzzleFive() {
+ int number = 5;
+ if(number < 0)
+ number = number + 10;
+ number++;
+ System.out.println(number);
+}
+```
+
+- a) 4 `Incorrect: The value of number is 5, it is incremented to 6 and then printed`.
+- b) 5 `Incorrect: The value of number is 5, but it is incremented before it is printed`.
+- c) 6 `Correct: The value of number is 5, it is incremented to 6 and then printed`【60†source】.
+
+### Question 39
+
+What is the purpose of using the Scanner class in Java?
+
+- a) To scan user input from the console `Correct: The Scanner class is used to read input from various sources, including the console`.
+- b) To read input from a file `Incorrect: While the Scanner class can be used to read input from a file, the question is about the main purpose of the Scanner class`.
+- c) To generate random numbers `Incorrect: The Scanner class does not generate random numbers`【61†source】.
+
+### Question 40
+
+What do you need to pass as a parameter to the Scanner constructor?
+
+- a) System.in `Correct: To read input from the console, System.in is passed as a parameter to the Scanner constructor`.
+- b) System.out `Incorrect: System.out is not used for input, but rather to output data`.
+- c) System.error `Incorrect: System.error does not exist in Java. You may be thinking of System.err, which is used for error output, not input`【62†source】.
+
+
+### Question 41
+
+How do you read an integer input from the console using the Scanner class?
+
+- a) scanner.nextInt() `Correct: The nextInt() method of the Scanner class is used to read an integer input from the console`.
+- b) scanner.readInt() `Incorrect: The Scanner class does not have a readInt() method`.
+- c) scanner.getInt() `Incorrect: The Scanner class does not have a getInt() method`【63†source】.
+
+### Question 42
+
+What is the purpose of the following code snippet?
+
+```java
+Scanner scanner = new Scanner(System.in);
+```
+
+- a) To initialize the Scanner class `Incorrect: This statement creates an instance of the Scanner class, not initializes it`.
+- b) To import the Scanner class `Incorrect: This statement creates an instance of the Scanner class, not imports it`.
+- c) To create an instance of the Scanner class `Correct: This statement creates an instance of the Scanner class`【64†source】.
+
+### Question 43
+
+What does the following line of code do?
+
+```java
+int number1 = Scanner.nextInt();
+```
+
+- a) Imports the next integer from the keyboard `Incorrect: This statement initializes the value of number1 to the next integer read from the keyboard`.
+- b) Initializes the value of number1 to the next integer from the keyboard `Correct: This statement initializes the value of number1 to the next integer read from the keyboard`.
+- c) Creates an instance of the nextInt method `Incorrect: This statement does not create an instance of a method`【65†source】.
+
+### Question 44
+
+What does the following code snippet do?
+
+```java
+System.out.println("Your Inputs Are:");
+System.out.println("Number1: " + number1);
+System.out.println("Number2: " + number2);
+System.out.println("Choice: " + choice);
+```
+
+- a) Imports the values of number1, number2, and choice from the keyboard `Incorrect: This code snippet does not import any values. It outputs them to the console`.
+- b) Writes the values of number1, number2, and choice to the console `Correct: This code snippet outputs the values of number1, number2, and choice to the console`.
+- c) Initializes the values of number1, number2, and choice `Incorrect: This code snippet does not initialize any values. It outputs them to the console`【66†source】.
+
+
+### Question 45
+
+What is the purpose of the if-else-else if statement in the code?
+
+- a) To check for 4 favorable conditions `Incorrect: While it may look at multiple conditions, it's not specifically for checking 4 conditions`.
+- b) To handle invalid operation choice `Correct: If-else-else if statement is used to handle various possibilities including invalid operation choice`.
+- c) To handle both favorable conditions and invalid operation choice `Correct: This statement is used to handle multiple conditions, both favorable and unfavorable (including invalid operation choice)`.
+- d) None of the above `Incorrect: The if-else-else if statement serves to check conditions and execute code based on those conditions`【67†source】.
+
+### Question 46
+
+What does the statement `"System.out.println("Result = " + (number1 + number2));"` do in the code?
+
+- a) Prints the sum of number1 and number2 `Correct: This statement calculates the sum of number1 and number2 and prints it`.
+- b) Prints the difference of number1 and number2 `Incorrect: This statement is calculating and printing the sum, not the difference`.
+- c) Prints the product of number1 and number2 `Incorrect: This statement is calculating and printing the sum, not the product`.
+- d) Prints the quotient of number1 and number2 `Incorrect: This statement is calculating and printing the sum, not the quotient`【68†source】.
+
+### Question 47
+
+What is the output when choice is 5?
+
+- a) Result = 55 `Incorrect: If choice is not one of the options (1, 2, 3, or 4), the output would be "Invalid Operation"`.
+- b) Invalid Operation `Correct: If choice is not one of the options (1, 2, 3, or 4), the output would be "Invalid Operation"`.
+- c) Number1: 25 `Incorrect: The value of Number1 or Number2 is not outputted based on the value of choice`.
+- d) Number2: 35 `Incorrect: The value of Number1 or Number2 is not outputted based on the value of choice`【69†source】.
+
+
+### Question 48
+
+Which of the following is NOT true about a switch statement in Java?
+
+- A) A switch statement is used to test multiple conditions `Incorrect: The switch statement in Java is used to select one of many code blocks to be executed, essentially testing multiple conditions`.
+- B) The default clause is executed when none of the cases match `Correct: The default clause in a switch statement is indeed executed when none of the case conditions match`.
+- C) The switch statement can handle the default possibility `Correct: The switch statement can include a default clause which is executed when no matching case has been found`.
+- D) The switch statement is used to test only one condition `Correct: This statement is false. The switch statement is used to test multiple conditions (cases) based on a single variable/expression`【70†source】.
+
+### Question 49
+
+What is the purpose of the break statement in a switch statement in Java?
+
+- A) To break out of the switch after a successful match `Correct: The break statement is used to stop the execution of the remaining cases in the switch statement after a case has been executed`.
+- B) To continue to the next case in the switch `Incorrect: Without a break statement, the program will continue executing the next case, even if the case condition does not match. The break statement serves to prevent this`.
+- C) To stop the execution of the program `Incorrect: The break statement only stops the execution of the current switch statement, not the entire program`.
+- D) To continue to the default clause in the switch `Incorrect: The break statement is used to exit the switch statement, not to jump to the default case`【71†source】.
+
+### Question 50
+
+What will the following code snippet output in Java?
+
+```java
+int number = 2;
+switch(number) {
+ case 1:
+ System.out.println(1);
+ case 2:
+ System.out.println(2);
+ case 3:
+ System.out.println(3);
+ default:
+ System.out.println("default");
+}
+```
+
+- A) 1 `Incorrect: Given that "number" is 2, it won't print 1`.
+- B) 2 `Incorrect: Given that "number" is 2, it will start at case 2 but since there are no break statements, it will also execute the remaining cases and the default`.
+- C) 3 `Incorrect: Given that "number" is 2, it will print 3 as well, but it will also print 2 and "default"`.
+- D) 1, 2, 3, default `Correct: Given that "number" is 2 and there are no break statements, it will start at case 2 and also execute the remaining cases (3) and the default`【72†source】.
+
+
+
+### Question 51
+
+What type of conditions can be evaluated using an if-family conditional?
+
+- a. Only boolean conditions `Correct: if, else if, and else in Java evaluate boolean conditions. They run or skip code blocks based on whether a condition is true or false.`
+- b. Only integer values `Incorrect: While integer values can be part of a condition, the condition itself is evaluated as a boolean.`
+- c. Both boolean and integer values `Incorrect: The conditions are always evaluated as booleans, although they can compare integer values.`
+- d. None of the above `Incorrect: Option a is the correct one.`【73†source】
+
+### Question 52
+
+What is the advantage of using a switch conditional over an if-family conditional?
+
+- a. More readable and compact `Correct: Switch cases can be more readable and compact when comparing a variable to several constant values.`
+- b. Can be used to check for only integer values `Incorrect: Switch cases can also handle characters and enumerated types, not only integers.`
+- c. More strict rules `Incorrect: If-else conditionals can be more flexible, since they can evaluate any boolean condition, not just value comparisons.`
+- d. More versatile `Incorrect: If-else conditionals are more versatile since they can evaluate any boolean condition.`【74†source】
+
+### Question 53
+
+What is the disadvantage of using a switch conditional over an if-family conditional?
+
+- a. Can lead to subtle errors in the program `Correct: One such error can occur if the 'break' keyword is forgotten after a case.`
+- b. More versatile `Incorrect: Versatility is not a disadvantage.`
+- c. Can only check for boolean conditions `Incorrect: Switch cases do not evaluate boolean conditions, but rather check the value of a variable against constant values.`
+- d. Not as strict as if-family conditional `Incorrect: Strictness in this context doesn't refer to a disadvantage.`【75†source】
+
+### Question 54
+
+What is the name of the day represented by the number 3 in the determineNameOfDay method?
+
+- A. Monday `Incorrect: Monday is usually represented by 1 in such systems.`
+- B. Tuesday `Incorrect: Tuesday is usually represented by 2.`
+- C. Wednesday `Correct: In this system, Wednesday would be represented by 3.`
+- D. Thursday `Incorrect: Thursday would typically be represented by 4.`【76†source】
+
+### Question 55
+
+What is the name of the month represented by the number 9 in the determinenameofMonth method?
+
+- A. January `Incorrect: January is usually represented by 1 in such systems.`
+- B. February `Incorrect: February is usually represented by 2.`
+- C. March `Incorrect: March is usually represented by 3.`
+- D. September `Correct: In this system, September would be represented by 9.`【77†source】
+
+### Question 56
+
+Is the day represented by the number 1 considered to be a week day in the isWeekDay method?
+
+- A. Yes `Correct: In many systems, the days of the week are numbered from 1 (Monday) to 7 (Sunday), so 1 would be a weekday.`
+- B. No `Incorrect: As stated above, 1 usually represents Monday, which is a weekday.`【78†source】
+
+### Question 57
+
+What is the purpose of the ternary operator ?: in Java?
+
+- A. To perform addition of two operands `Incorrect: The ternary operator is not used for addition. It's used for conditional operations.`
+- B. To perform subtraction of two operands `Incorrect: The ternary operator is not used for subtraction. It's used for conditional operations.`
+- C. To perform conditional operations `Correct: The ternary operator is used to perform a simple if-else check in one line.`【79†source】
+
+### Question 58
+
+What should be the return type of both expressions in the ternary operator ?: in Java?
+
+- A. Both expressions can return any type of value `Incorrect: While the expressions can be of any type, they both need to be of the same type or compatible types.`
+- B. Both expressions should return different types of value `Incorrect: Both expressions should return values of the same type or of compatible types.`
+- C. Both expressions should return values of the same type `Correct: Both expressions in a ternary operation should be of the same type, or of types that can be automatically converted to a common type.`【80†source】
+
+### Question 59
+
+What is the syntax of the ternary operator ?: in Java?
+
+- A. result = (expression-if-condition-true ? condition : expression:if-condition-false); `Incorrect: The syntax for the ternary operator starts with the condition, followed by the '?' operator, the value for if condition is true, the ':' operator, and the value for if condition is false.`
+- B. result = (expression-if-condition-false ? condition : expression-if-condition-true); `Incorrect: Similar to the above explanation, the syntax starts with the condition to be evaluated.`
+- C. result = (condition ? expression-if-condition-true : expression-if-condition-false); `Correct: This is the correct syntax for the ternary operator in Java.`【81†source】
+
diff --git a/00-Quiz-Explanation/Archive/Q09-ReferenceTypes.md b/00-Quiz-Explanation/Archive/Q09-ReferenceTypes.md
new file mode 100644
index 00000000..8aa6bc38
--- /dev/null
+++ b/00-Quiz-Explanation/Archive/Q09-ReferenceTypes.md
@@ -0,0 +1,429 @@
+
+### Step 01: Introducing Reference Types
+
+**Question 60**
+
+What is the purpose of reference variables in Java?
+
+ * A. To store primitive values `Incorrect: Reference variables are used to store references to objects, not primitive values.`
+ * B. To store objects on the Heap `Incorrect: Reference variables store references (addresses), not the actual objects.`
+ * C. To store the memory location of an object `Correct: Reference variables store the memory location (reference) of an object.`【60†source】
+
+**Question 61**
+
+What is the main difference between reference types and primitive types in Java?
+
+ * A. Primitive types are stored on the Stack, reference types on the Heap `Correct: Primitive types are stored on the Stack and reference types are stored on the Heap.`
+ * B. Primitive types are stored on the Heap, reference types on the Stack `Incorrect: This is the opposite of the actual situation.`
+ * C. Both are stored on the Heap `Incorrect: Primitive types are stored on the Stack, not on the Heap.`【61†source】
+
+**Question 62**
+
+In the following code snippet, where are the objects `jupiter` and `dog` stored?
+
+```java
+class Planet { ... }
+Planet jupiter = new Planet();
+
+class Animal { ... }
+Animal dog = new Animal(12);
+```
+
+ * A. Stack `Incorrect: Objects are stored on the Heap in Java.`
+ * B. Heap `Correct: Objects are stored on the Heap in Java.`
+ * C. Both Stack and Heap `Incorrect: In Java, the Stack is used for storing method calls and primitive types, while the Heap is used for storing objects.`【62†source】
+
+### Step 02: References: Usage And Puzzles
+
+**Question 63**
+
+What is the value of a reference variable that is not initialized by the programmer in Java?
+
+ * A. 0 `Incorrect: 0 is a default value for numeric primitive types, not for reference types.`
+ * B. Empty `Incorrect: Empty is not a default value for a reference variable.`
+ * C. Null `Correct: If a reference variable is not initialized, its default value will be null.`【63†source】
+
+**Question 64**
+
+What happens when you compare two reference variables in Java?
+
+ * A. It compares the values stored inside the referenced objects `Incorrect: By default, comparing two reference variables checks if they point to the same object, not the content of the objects.`
+ * B. It compares the memory locations where the objects are stored `Correct: When you compare two reference variables, it checks whether they point to the same object, i.e., they have the same memory location.`
+ * C. It compares the size of the objects `Incorrect: Java does not compare the size of the objects when comparing two reference variables.`【64†source】
+
+**Question 65**
+
+What happens when you assign one reference variable to another in Java?
+
+ * A. It creates a copy of the entire referenced object `Incorrect: Assigning one reference variable to another does not copy the object, only the reference.`
+ * B. It only copies the reference `Correct: When you assign one reference variable to another, it copies the reference, not the object. As a result, both variables point to the same object.`
+ * C. It creates a new object with the same values as the referenced object `Incorrect: Assigning one reference variable to another does not create a new object.`【65†source】
+
+### Step 03: Introducing String Quiz
+
+**Question 66**
+
+What is a string in Java?
+
+ * A. A sequence of numbers `Incorrect: In Java, a string is not a sequence of numbers.`
+ * B. A sequence of characters `Correct: In Java, a string is a sequence of characters.`
+ * C. A sequence of symbols `Incorrect: In Java, a string is not a sequence of symbols, it is a sequence of characters.`【66†source】
+
+**Question 67**
+
+What is the output of the following code:
+
+```java
+String str = "Test";
+System.out.println(str.charAt(2));
+```
+
+ * A. 'e' `Incorrect: The character at index 2 of the string "Test" is 's', not 'e'.`
+ * B. 's' `Correct: The character at index 2 of the string "Test" is 's'.`
+ * C. 'T' `Incorrect: The character at index 2 of the string "Test" is 's', not 'T'.`【67†source】
+
+**Question 68**
+
+What does the substring method of the String class return?
+
+ * A. A sequence of numbers `Incorrect: The substring method returns a sequence of characters, not numbers.`
+ * B. A sequence of characters `Correct: The substring method returns a sequence of characters from the original string.`
+ * C. A sequence of symbols `Incorrect: The substring method returns a sequence of characters, not symbols.`【68†source】
+
+### Step 04: Programming Exercise PE-01, And String Utilities
+
+**Question 102**
+
+What does the indexOf() method in the String class do?
+
+ * A. Returns the position of a character in a string `Correct but not the complete answer: The indexOf() method does return the position of the first occurrence of a specified character in a string.`
+ * B. Returns the starting position of a substring in a string `Correct but not the complete answer: The indexOf() method does return the position of the first occurrence of a specified substring in a string.`
+ * C. Both of the above `Correct: The indexOf() method can return the position of a character or a substring in a string.`
+ * D. None of the above `Incorrect: The indexOf() method does perform the functions stated in option C.`【102†source】
+
+**Question 103**
+
+How does the endsWith() method determine if a string ends with a given suffix?
+
+ * A. It returns the position of the last occurrence of the suffix in the string `Incorrect: The endsWith() method does not return a position.`
+ * B. It returns true if the string ends with the given suffix, false otherwise `Correct: The endsWith() method checks if a string ends with the specified suffix and returns a boolean result.`
+ * C. It returns false if the string ends with the given suffix, true otherwise `Incorrect: The endsWith() method returns true if the string ends with the specified suffix, not false.`
+ * D. None of the above `Incorrect: The endsWith() method does perform the function stated in option B.`【103†source】
+
+**Question 104**
+
+When using the equals() method, what is the result if the string is identical to the argument?
+
+ * A. Returns true `Correct: The equals() method compares the string to the argument and returns true if they are identical.`
+ * B. Returns false `Incorrect: The equals() method returns false if the strings are not identical, not if they are.`
+ * C. Returns the position of the first occurrence of the argument in the string `Incorrect: The equals() method does not return a position.`
+ * D. None of the above `Incorrect: The equals() method does perform the function stated in option A.`【104†source】
+
+### Step 05: String Immutability
+
+**Question 72**
+
+What is the meaning of the word "immutable"?
+
+ * A. Changeable `Incorrect: "Immutable" means unchangeable.`
+ * B. Unchangeable `Correct: "Immutable" means unchangeable.`
+ * C. Mutable `Incorrect: "Mutable" is the opposite of "immutable". It means changeable.`【72†source】
+
+**Question 73**
+
+Can the value of a string object be changed after it is created?
+
+ * A. Yes `Incorrect: String objects are immutable in Java, meaning their value cannot be changed once created.`
+ * B. No `Correct: String objects are immutable in Java, meaning their value cannot be changed once created.`【73†source】
+
+**Question 74**
+
+What does the method concat() do
+
+ in Java?
+
+ * A. Changes the original string by appending another string `Incorrect: The concat() method does not change the original string; instead, it returns a new string.`
+ * B. Returns a new string resulting from appending another string to the original string `Correct: The concat() method returns a new string that is the result of appending the specified string to the end of the original string.`
+ * C. Replaces the original string with a new string `Incorrect: The concat() method does not replace the original string; it returns a new string.`【74†source】
+
+**Question 75**
+
+What is String Pool in Java?
+
+ * A. A pool of methods for the String class `Incorrect: The String Pool is a pool of literal strings, not methods.`
+ * B. A pool of literal strings stored in the heap memory `Correct: The String Pool in Java is a pool of literal strings stored in the heap memory.`
+ * C. A pool of references to the String objects `Incorrect: The String Pool is a pool of literal strings, not references to String objects.`【75†source】
+
+
+### Step 05: String Immutability Continued
+
+**Question 76**
+
+What happens to the original string object when the method toUpperCase() is used on it?
+
+ * A. The original string object is changed to upper case `Incorrect: In Java, strings are immutable. The toUpperCase() method returns a new string.`
+ * B. The original string object remains unchanged, a new string object is returned with the changed value `Correct: The toUpperCase() method does not change the original string; it returns a new string.`【76†source】
+
+**Question 77**
+
+What is the output of the following code:
+
+```java
+String str = "in28Minutes";
+str = str.concat(" is awesome");
+System.out.println(str);
+```
+
+ * A. "in28Minutes is awesome" `Correct: The concat() method appends the given string to the end of the original string and the result is stored in 'str'.`
+ * B. "in28Minutes" `Incorrect: The concat() method appends the given string to the end of the original string.`
+ * C. "in28Minutes is awesome" and "in28Minutes" `Incorrect: The System.out.println() method will print only one string - the value of 'str'.`【77†source】
+
+### Step 06: More String Utilities
+
+**Question 78**
+
+What is the result of the following code:
+
+```java
+int i = 20;
+System.out.println("Value is " + i + 20);
+```
+
+ * A. Value is 40 `Incorrect: In this case, 'i + 20' will not perform integer addition because of string concatenation, and will result in '2020'.`
+ * B. Value is 2020 `Correct: The "+" operator in this context is used for string concatenation, not numerical addition.`
+ * C. Value is 2040 `Incorrect: The "+" operator in this context is used for string concatenation, not numerical addition.`【78†source】
+
+**Question 79**
+
+What is the result of the following code:
+
+```java
+String.join(",", "2", "3", "4");
+```
+
+ * A. "2,3,4" `Correct: The join() method concatenates the given strings with a comma as a delimiter.`
+ * B. "23,4" `Incorrect: The join() method concatenates all the given strings with a comma as a delimiter.`
+ * C. "234" `Incorrect: The join() method concatenates the given strings with a comma as a delimiter.`【79†source】
+
+**Question 80**
+
+What is the result of the following code:
+
+```java
+"abcd".replace("ab", "xyz");
+```
+
+ * A. "xyzcd" `Correct: The replace() method replaces all occurrences of the first argument with the second argument in the string.`
+ * B. "xyzabcd" `Incorrect: The replace() method does not append the replacement at the start of the string.`
+ * C. "abcdxyz" `Incorrect: The replace() method does not append the replacement at the end of the string.`【80†source】
+
+### Step 07: Storing mutable text
+
+**Question 81**
+
+What is the difference between StringBuffer and StringBuilder?
+
+ * A. StringBuffer is mutable while StringBuilder is immutable `Incorrect: Both StringBuffer and StringBuilder are mutable.`
+ * B. StringBuilder is mutable while StringBuffer is immutable `Incorrect: Both StringBuffer and StringBuilder are mutable.`
+ * C. Both StringBuffer and StringBuilder are immutable `Incorrect: Both StringBuffer and StringBuilder are mutable.`【81†source】
+
+**Question 82**
+
+What is the main advantage
+
+ of using StringBuilder over StringBuffer?
+
+ * A. StringBuilder is thread-safe `Incorrect: StringBuffer is thread-safe, not StringBuilder.`
+ * B. StringBuilder offers better performance in both execution-time and memory usage `Correct: Because StringBuilder is not thread-safe, it doesn't have the overhead of synchronization, which makes it faster and more efficient than StringBuffer.`
+ * C. StringBuilder is a built-in class in Java `Incorrect: Both StringBuffer and StringBuilder are built-in classes in Java.`【82†source】
+
+**Question 83**
+
+Can we modify a string literal using StringBuffer?
+
+ * A. Yes, we can modify a string literal using StringBuffer `Incorrect: String literals are immutable in Java, so they cannot be modified by StringBuffer or any other class.`
+ * B. No, we cannot modify a string literal using StringBuffer `Correct: String literals are immutable in Java, so they cannot be modified.`
+ * C. It depends on the situation `Incorrect: String literals are always immutable in Java, regardless of the situation.`【83†source】
+
+### Step 08: Introducing Wrapper Classes
+
+**Question 84**
+
+What is the purpose of using Wrapper Classes in Java?
+
+ * A. To access type information about the corresponding primitive type `Incorrect: Wrapper classes in Java are primarily used to convert primitive data types into objects.`
+ * B. To promote primitive data to an object reference type `Correct: Wrapper classes in Java are used to convert primitive data types into objects. This is often necessary because certain Java collections can only handle objects and not primitive types.`
+ * C. To move primitive type data around data structures `Incorrect: While it's true that wrapper classes can help move primitive data around in object-oriented data structures, their primary purpose is to convert primitive types into objects.`【84†source】
+
+**Question 85**
+
+What is Auto-Boxing in Java?
+
+ * A. The process of promoting primitive data to an object reference type `Incorrect: Auto-boxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes.`
+ * B. The process of converting an object reference type to a primitive data type `Incorrect: This process is known as unboxing, not auto-boxing.`
+ * C. The process of converting a primitive data type to an object reference type `Correct: Auto-boxing is the automatic conversion of primitive types to their corresponding object wrapper classes.`【85†source】
+
+**Question 86**
+
+Can we modify the value of a wrapper class once it is assigned?
+
+ * A. Yes, we can modify the value of a wrapper class `Incorrect: Once a value has been assigned to a wrapper class, it cannot be changed.`
+ * B. No, the value of a wrapper class is immutable `Correct: Once a value has been assigned to a wrapper class, it cannot be changed. This is because all wrapper classes in Java are immutable.`
+ * C. It depends on the type of wrapper class being used. `Incorrect: All wrapper classes in Java are immutable, regardless of the type.`【86†source】
+
+### Step 09: Creating Wrapper Objects
+
+**Question 87**
+
+What are Wrapper Classes in Java?
+
+ * A. Classes that provide a mechanism to convert primitive data types into objects `Correct: This is one of the main functions of wrapper classes in Java.`
+ * B. Classes that provide a mechanism to convert objects into primitive data types `Correct: This is one of the main functions of wrapper classes in Java. They allow us to "unwrap" the value of an object into a primitive type through a process known as unboxing.`
+ * C. Both of the above `Correct: Wrapper classes in Java both convert primitive data types
+
+ into objects (known as boxing), and provide a mechanism to convert objects into primitive data types (known as unboxing).`
+ * D. None of the above `Incorrect: Wrapper classes in Java serve both of the functions listed above.`【87†source】
+
+**Question 88**
+
+What is the difference between creating a Wrapper object using 'new' and 'valueOf()'?
+
+ * A. There is no difference `Incorrect: There is a significant difference between these two methods.`
+ * B. 'new' creates a new object every time, whereas 'valueOf()' reuses existing objects with the same value `Correct: The 'new' keyword always creates a new object, while 'valueOf()' may return a cached object for certain ranges of values (particularly small integers).`
+ * C. 'new' reuses existing objects with the same value, whereas 'valueOf()' creates a new object every time `Incorrect: It is 'valueOf()' that may reuse objects, not 'new'.`
+ * D. None of the above `Incorrect: The correct answer is option B.`【88†source】
+
+**Question 89**
+
+Are Wrapper Classes mutable in Java?
+
+ * A. Yes `Incorrect: Wrapper classes in Java are immutable.`
+ * B. No `Correct: Once a value has been assigned to a wrapper class, it cannot be changed.`
+ * C. Depends on the implementation `Incorrect: All wrapper classes in Java are immutable, regardless of the implementation.`
+ * D. None of the above `Incorrect: The correct answer is option B.`【89†source】
+
+### Step 10: Auto-Boxing, And Some Wrapper Constants
+
+**Question 90**
+
+What is Auto-Boxing in Java?
+
+ * A. A feature that provides new functionality to the Java language `Incorrect: While it is true that auto-boxing was a new feature introduced in Java 5, it is not the definition of auto-boxing.`
+ * B. A mechanism to make code more readable `Incorrect: While auto-boxing can make code more readable, that is not its primary function.`
+ * C. A mechanism to upgrade a primitive data type to its corresponding object type `Correct: Auto-boxing is the automatic conversion of primitive types to their corresponding object wrapper classes.`
+ * D. None of the above `Incorrect: The correct answer is option C.`【90†source】
+
+**Question 91**
+
+What is the mechanism used by Auto-Boxing in Java?
+
+ * A. It uses the 'new' operator to create new objects every time `Incorrect: Auto-boxing uses the valueOf() method, not the new operator.`
+ * B. It uses the 'valueOf()' method to create objects `Correct: Auto-boxing uses the valueOf() method to create an instance of the wrapper class for the corresponding primitive type.`
+ * C. It uses the 'toString()' method to create objects `Incorrect: The toString() method is used to convert an object to a string, not to create new objects.`
+ * D. None of the above `Incorrect: The correct answer is option B.`【91†source】
+
+**Question 92**
+
+Are there any constants available on Wrapper Classes in Java to check the size and range of values they can store?
+
+ * A. No `Incorrect: Each wrapper class does indeed contain constants that represent the minimum and maximum values that can be stored.`
+ * B. Yes `Correct: Each wrapper class contains constants MIN_VALUE and MAX_VALUE that represent the minimum and maximum values that can be stored in an object of that type.`
+ * C. Depends on the implementation `Incorrect: All standard wrapper classes in Java contain these constants.`
+ * D.
+
+ None of the above `Incorrect: The correct answer is option B.`【92†source】
+
+### Step 11: The Java Date API Quiz
+
+**Question 93**
+
+What is the main purpose of the Java Date API?
+
+ * a. To perform arithmetic operations on date and time objects `Incorrect: While the Java Date API does allow arithmetic operations on date and time objects, this is not its main purpose.`
+ * b. To provide an interface for date and time classes `Incorrect: The Java Date API provides more than just an interface; it provides a full implementation for handling date and time.`
+ * c. To provide a framework for date and time classes `Correct: The Java Date API is a framework that provides classes for handling date and time in a way that is both easier to understand and more accurate than using just the Date class.`
+ * d. To provide a library for date and time classes `Incorrect: While the Java Date API can be considered a library, the most accurate description is that it is a framework.`【93†source】
+
+**Question 94**
+
+What is the main difference between LocalDate, LocalTime, and LocalDateTime?
+
+ * a. They are used for different purposes `Incorrect: While these classes are used for different purposes, the key difference is what they represent.`
+ * b. They are different classes in Java `Incorrect: While this is technically true, it doesn't describe the functional differences between these classes.`
+ * c. They are used to represent different values for date and time `Correct: LocalDate represents a date (year, month, day), LocalTime represents a time (hour, minute, second, nanosecond), and LocalDateTime represents both a date and a time.`
+ * d. They are used for different date and time formats `Incorrect: While these classes can be used to format dates and times in different ways, the key difference is what they represent.`【94†source】
+
+**Question 95**
+
+What is the difference between the LocalDate.now() and LocalDate.of() methods in the Java Date API?
+
+ * a. LocalDate.now() returns the current date and time, while LocalDate.of() returns a specific date and time `Incorrect: LocalDate.now() returns the current date, not the current date and time.`
+ * b. LocalDate.now() returns the current date, while LocalDate.of() returns a specific date `Correct: LocalDate.now() returns the current date, and LocalDate.of() can be used to create a LocalDate object for a specific date.`
+ * c. LocalDate.now() returns the current time, while LocalDate.of() returns a specific time `Incorrect: LocalDate objects do not contain time information.`
+ * d. LocalDate.now() returns a date and time object, while LocalDate.of() returns a date object `Incorrect: Both methods return LocalDate objects, which contain only date information.`【95†source】
+
+### Step 12: Playing With java.time.LocalDate Quiz
+
+**Question 96**
+
+What information can you retrieve from a LocalDate object?
+
+ * a. Date information such as Day/Month/Year and related attributes `Correct: LocalDate objects contain date information and related attributes, but do not contain any time information.`
+ * b. Time information such as Hour/Minute/Second and related attributes `Incorrect: LocalDate objects do not contain any time information.`
+ * c. Both date and time information `Incorrect: LocalDate objects contain only date information, not time information.`
+ * d. None of the above `Incorrect: The correct answer is option A.`【96†source】
+
+**Question 97**
+
+Are LocalDate, LocalTime, and LocalDateTime objects mutable?
+
+ * a. Yes `Incorrect: Objects of these classes are immutable.`
+ * b. No `Correct: Objects of LocalDate, LocalTime, and LocalDateTime are immutable. Once created, their
+
+ state cannot be changed.`【97†source】
+
+**Question 98**
+
+What is the result of the following code snippet?
+
+```java
+LocalDate today = LocalDate.now();
+LocalDate tomorrow = today.plusDays(1);
+System.out.println(today.isBefore(tomorrow));
+```
+
+ * a. True `Correct: The method `isBefore()` returns true because the date `tomorrow` is after `today`.`
+ * b. False `Incorrect: The correct answer is true.`
+ * c. Error `Incorrect: The code will not result in an error.`【98†source】
+
+### Step 13: Comparing LocalDate Objects Quiz
+
+**Question 99**
+
+What is the purpose of the isBefore() and isAfter() methods in the Java Date API?
+
+ * a. To compare the order of two LocalDate objects `Correct: The `isBefore()` and `isAfter()` methods are used to determine if one LocalDate is before or after another, respectively.`
+ * b. To determine if a LocalDate object is earlier or later than a specific date `Incorrect: While this can be a result of using these methods, it's not the purpose. Their purpose is to compare two LocalDate objects.`
+ * c. To compare the value of two LocalDate objects `Incorrect: These methods do not compare the value of two LocalDate objects. They check the order of the dates.`
+ * d. To determine if a LocalDate object is equal to a specific date `Incorrect: For equality checks, the `isEqual()` method should be used.`【99†source】
+
+**Question 100**
+
+What is the result of the following code snippet?
+
+```java
+LocalDate today = LocalDate.now();
+LocalDate yesterday = LocalDate.of(2018, 01, 31);
+System.out.println(today.isAfter(yesterday));
+```
+
+ * a. True `Correct: Unless this code is run on January 31, 2018, `today` will be after `yesterday`, and so `isAfter()` will return true.`
+ * b. False `Incorrect: Unless this code is run on January 31, 2018, the method `isAfter()` will return true.`
+ * c. Error `Incorrect: The code will not result in an error.`【100†source】
+
+**Question 101**
+
+Can you compare LocalTime and LocalDateTime objects using the isBefore() and isAfter() methods?
+
+ * a. Yes `Correct: The `isBefore()` and `isAfter()` methods are available in both LocalTime and LocalDateTime classes.`
+ * b. No `Incorrect: The correct answer is yes.`【101†source】
\ No newline at end of file
diff --git a/00-Quiz-Explanation/Archive/Q11-ObjectOrientedProgrammingAgain.md b/00-Quiz-Explanation/Archive/Q11-ObjectOrientedProgrammingAgain.md
new file mode 100644
index 00000000..5aa1562f
--- /dev/null
+++ b/00-Quiz-Explanation/Archive/Q11-ObjectOrientedProgrammingAgain.md
@@ -0,0 +1,285 @@
+### Step 01: Objects Revisited - State And Behavior
+
+**Question 1: What defines an object's state?**
+
+- A. Its methods `Incorrect: Methods define the behavior of an object, not its state.`
+- B. Its behavior `Incorrect: Behavior is how an object acts, but it doesn't define its state.`
+- C. Its attributes `Correct: The state of an object is determined by its attributes or properties.`
+
+**Question 2: What delivers messages to an object?**
+
+- A. Attributes `Incorrect: Attributes don't deliver messages; they store state information.`
+- B. Methods `Correct: Methods are used to send messages to an object to perform certain actions.`
+- C. Constructors `Incorrect: Constructors are used to initialize an object, not to send messages.`
+
+**Question 3: What is the effect of behavior on an object's state?**
+
+- A. No effect `Incorrect: Behavior, defined by methods, can affect an object's state.`
+- B. Positive effect `Incorrect: The term "positive effect" is not precise in this context.`
+- C. Negative effect `Incorrect: The term "negative effect" is not precise in this context.`
+
+### Step 02: Managing class state
+
+**Question 1: What corresponds to the state of a class?**
+
+- A. Member variables `Correct: Member variables hold the state of an object of a class.`
+- B. Methods `Incorrect: Methods define the behavior of the objects, not their state.`
+- C. Constructors `Incorrect: Constructors are used to initialize an object, not to define its state.`
+
+**Question 2: What is the purpose of constructors in a class?**
+
+- A. To define behavior `Incorrect: Constructors are used to initialize an object, not to define its behavior.`
+- B. To create objects `Correct: Constructors are used to create and initialize objects of a class.`
+- C. To set attributes `Incorrect: Although constructors can be used to set attribute values, their primary purpose is to create objects.`
+
+**Question 3: What is the purpose of the toString() method in a class?**
+
+- A. To define behavior `Incorrect: The toString() method does not define behavior.`
+- B. To create objects `Incorrect: The toString() method is used to provide a String representation of an object, not to create objects.`
+- C. To provide a string representation of the object's state `Correct: The toString() method provides a string representation of an object's state.`
+
+### Step 03: Augmenting Fan With Behavior
+
+**Question 1: What is the state attribute that needs to be exposed to change by Fan object users?**
+
+- A. make `Incorrect: "make" is not typically changed by users.`
+- B. color `Incorrect: "color" is not typically changed by users.`
+- C. isOn `Correct: Users need to be able to change whether the fan is on or off.`
+- D. speed `Correct: Users need to be able to change the speed of the fan.`
+
+**Question 2: What is the purpose of the switchOn() and switchOff() methods in the Fan class?**
+
+- A. To toggle the isOn state attribute `Correct: These methods are used to change the "isOn" state attribute of a Fan object.`
+- B. To toggle the speed state attribute `Incorrect: These methods don't directly change the speed state attribute.`
+- C. To create a new Fan object `Incorrect: These methods are used to modify the state of an existing Fan object, not to create a new one.`
+
+**Question 3: What is the
+
+ purpose of the setSpeed() method in the Fan class?**
+
+- A. To toggle the isOn state attribute `Incorrect: This method doesn't change the "isOn" state attribute.`
+- B. To toggle the speed state attribute `Correct: This method is used to set the speed of the Fan.`
+- C. To create a new Fan object `Incorrect: This method is used to modify the state of an existing Fan object, not to create a new one.`
+
+
+**Step 04: Programming Exercise PE-OOP-01**
+
+**Question 1: What are the state attributes of a Rectangle object?**
+- A. Length and width `Correct: A rectangle is defined by its length and width.`
+- B. Height and width `Incorrect: Height is not typically a characteristic used to define a rectangle.`
+- C. Length and breadth `Incorrect: The term "breadth" is less commonly used to describe a rectangle's dimensions.`
+
+**Question 2: What is the purpose of the area() method in the Rectangle class?**
+- A. To calculate the perimeter of the rectangle `Incorrect: The area() method calculates the area, not the perimeter.`
+- B. To calculate the area of the rectangle `Correct: The area() method calculates the area of a rectangle.`
+- C. To set the length of the rectangle `Incorrect: The area() method doesn't set any attribute; it calculates a value.`
+
+**Question 3: What is the purpose of the perimeter() method in the Rectangle class?**
+- A. To calculate the perimeter of the rectangle `Correct: The perimeter() method calculates the perimeter of a rectangle.`
+- B. To calculate the area of the rectangle `Incorrect: The perimeter() method calculates the perimeter, not the area.`
+- C. To set the length of the rectangle `Incorrect: The perimeter() method doesn't set any attribute; it calculates a value.`
+
+**Step 06: Understanding Object Composition**
+
+**Question 1: What are the state attributes of the Fan class?**
+- A) make, radius, color, isOn, speed `Correct: These are the attributes that define the state of a Fan object.`
+- B) brand, diameter, hue, isRunning, velocity `Incorrect: These attributes may define similar features, but the specific names differ from those in the Fan class.`
+- C) manufacturer, size, tone, isActive, rate `Incorrect: These attributes may define similar features, but the specific names differ from those in the Fan class.`
+
+**Question 2: What is object composition?**
+- A) Combining primitive types into a complex object `Incorrect: While this is a form of composition, it's not specific to object composition in OOP.`
+- B) Creating multiple objects of the same type `Incorrect: This doesn't define object composition.`
+- C) Combining different objects to create a more complex object `Correct: Object composition involves using different objects to build more complex ones.`
+
+**Question 3: What is the purpose of constructors in object composition?**
+- A) To create new objects of a class `Correct: Constructors are used to create and initialize new objects.`
+- B) To modify the state of an object `Incorrect: Constructors initialize an object's state, not modify it after creation.`
+- C) To add behaviors to an object `Incorrect: While constructors can assign methods, their main purpose is to create and initialize new objects.`
+
+**Step 07: Programming Exercise PE-OOP-02**
+
+**Question 1: What are the attributes of the Book class?**
+- A) Id, Name, Author `Correct: These are the attributes that define the state of a Book object.`
+- B) Title, Author, Description `Incorrect: While these could be valid attributes for a Book, they do not match the provided Book class structure.`
+- C) Id, Title, Author `Incorrect: While these could be valid attributes for a Book, they do not match the provided Book class structure.`
+
+**Question 2: What is the purpose of the Review class?**
+- A) To manage Books `Incorrect: The Review class is meant to manage reviews, not
+
+ books.`
+- B) To manage Authors `Incorrect: The Review class is meant to manage reviews, not authors.`
+- C) To manage reviews associated with a Book `Correct: The Review class is used to manage and associate reviews with a Book.`
+
+**Question 3: What is the output of the following code?**
+
+```java
+Book book = new Book(123, "Object Oriented Programming With Java", "Ranga");
+book.addReview(new Review(10, "Great Book", 4));
+book.addReview(new Review(101, "Awesome", 5));
+System.out.println(book);
+```
+
+- A) Book-123, Object Oriented Programming With Java, Ranga, [(Review-10, Great Book", 4), (Review-101, Awesome, 5)] `Correct: This is the expected output based on the provided code.`
+- B) Book-123, Object Oriented Programming With Java, Ranga, [(10, Great Book, 4), (101, Awesome, 5)] `Incorrect: The output format includes the word "Review-" before the review IDs.`
+- C) Book-123, Object Oriented Programming With Java, Ranga, [(Review-10, Great Book", 5), (Review-101, Awesome, 4)] `Incorrect: The review ratings do not match those given in the code.`
+
+**Step 07: The Need For Inheritance**
+
+**Question 1: What is Inheritance in Object Oriented Programming?**
+- A) A mechanism of code reuse `Correct: Inheritance allows the reuse of code from one class in another.`
+- B) A mechanism to create new objects `Incorrect: While inheritance can be part of creating new objects, it primarily refers to code reuse between classes.`
+- C) A mechanism to modify existing objects `Incorrect: Inheritance involves classes and their relationships, not modifying existing objects.`
+
+**Question 2: What is a superclass in Inheritance relationship?**
+- A) A class that extends another class `Incorrect: A superclass is the class that gets extended, not the one that does the extending.`
+- B) A class that inherits from another class `Incorrect: A superclass is the class that is inherited from, not the class that does the inheriting.`
+- C) A class that is neither extended nor inherited `Incorrect: In the context of inheritance, a superclass is a class that is inherited from.`
+
+**Question 3: How does a subclass access fields and methods of its superclass?**
+- A) By using the keyword 'super' `Correct: In Java, the 'super' keyword is used to refer to the superclass of the current object.`
+- B) By using the keyword 'this' `Incorrect: The 'this' keyword refers to the current object, not its superclass.`
+- C) By using the keyword 'extends' `Incorrect: The 'extends' keyword is used to establish an inheritance relationship, not to access superclass members.`
+
+**Step 12: Constructors, And Calling super()**
+
+**Question 1: What does the super keyword do in Java?**
+- a. Allows a subclass to access the attributes present in the superclass `Correct: The super keyword in Java is used to refer to the immediate parent class instance variable.`
+- b. Creates a new instance of a superclass `Incorrect: The super keyword does not create new instances; it refers to the superclass.`
+- c. Allows a superclass to access the attributes present in the subclass `Incorrect: The super keyword is used in the context of a subclass referring to its superclass, not the other way around.`
+
+**Step 13: Multiple Inheritance, Reference Variables And instanceof**
+
+**Question 1: Can a Java class directly inherit from two or more classes?**
+- a. Yes `Incorrect: Java doesn't support multiple inheritance directly due to the "Diamond Problem".`
+- b. No `Correct: A class in Java can directly inherit from only one class.`
+
+**Question 2: What is the output of the Dog object's toString() method in Snippet-02?**
+- a. Dog@23a6e47f `Correct: If not overridden, the toString() method returns the class name followed by the "@" sign and the unsigned hexadecimal representation of the hash code of the object.`
+- b. Pet Groom `Incorrect: The output of toString() wouldn't be a string literal unless explicitly defined in the Dog class.`
+- c. null `Incorrect: The toString() method will not return null unless explicitly defined to do so.`
+
+**Question 3: What is the output of the instanceof operator when pet instanceof String is executed in Snippet-02?**
+- a. Pet cannot be converted to java.lang.String `Correct: The 'instanceof' operator in Java is used to test whether an object is an instance of a specific class or not. In this case, 'pet' is not a String.`
+- b. true `Incorrect: The pet is not an instance of String.`
+- c. false `Incorrect: It throws a compile-time error because 'pet' can't be compared with 'String'.`
+
+**Step 14: Introducing Abstract Classes**
+
+**Question 1: What is an abstract method?**
+- A) A method without any parameters `Incorrect: Abstract methods are defined by lack of implementation, not lack of parameters.`
+- B) A method with a method definition `Incorrect: Abstract methods lack a method definition.`
+- C) A method without a method definition `Correct: Abstract methods in Java are declared without a body.`
+
+**Question 2: Can an abstract class be instantiated?**
+- A) Yes `Incorrect: Abstract classes in Java cannot be instantiated.`
+- B) No `Correct: Abstract classes can't be instantiated directly; they can only be subclassed.`
+
+**Question 3: What is a concrete class?**
+- A) A class that can be instantiated `Correct: A concrete class is a class that can be instantiated.`
+- B) A class that cannot be instantiated `Incorrect: A concrete class, unlike an abstract class, can be instantiated.`
+- C) A class with a method definition `Incorrect: While a concrete class does have defined methods, it's primarily characterized by its ability to be instantiated.`
+
+**Step 15: Abstract Classes - Design Aspects**
+
+**Question 1: What is the purpose of an abstract class?**
+- A) To provide implementation for all its methods `Incorrect: Abstract classes don't provide full implementation; they contain one or more abstract methods.`
+- B) To declare methods without providing implementation `Correct: Abstract classes declare methods without providing their implementation.`
+- C) To create a hierarchy of classes `Incorrect: While abstract classes do play a role in class hierarchies, their primary purpose is to declare methods without providing implementation.`
+
+**Question 2: What is the advantage of using an abstract class to create a recipe hierarchy?**
+- A) It allows for the order of steps to be defined `Incorrect: The order of steps is not inherently defined by using an abstract class.`
+- B) It allows for the implementation of each step to be defined by the sub-classes `Correct: Abstract classes allow subclasses to provide specific implementations of abstract methods.`
+- C) It allows for the creation of multiple
+
+ recipe types easily `Incorrect: While it might be true, the main advantage is in the encapsulation of a general process structure while enabling specific step implementations.`
+
+**Question 3: Which design pattern is used in the recipe hierarchy example?**
+- A) Observer pattern `Incorrect: The observer pattern is a design pattern where an object maintains a list of dependents and notifies them of any changes. It's not used here.`
+- B) Decorator pattern `Incorrect: The decorator pattern allows behavior to be added to an individual object, either statically or dynamically, without affecting the behavior of other objects from the same class. It's not used here.`
+- C) Template method pattern `Correct: The template method pattern is a behavioral design pattern that defines the program skeleton in an operation but defers some steps to subclasses.`
+
+**Step 16: Abstract Classes - Puzzles**
+
+**Question 1: Can an abstract class be created without any abstract member methods?**
+- A) Yes `Correct: Abstract classes can exist without abstract methods. They can't be instantiated, but they can include actual method implementations.`
+- B) No `Incorrect: It's not required for an abstract class to have abstract methods, although it's common.`
+
+**Question 2: Can an abstract class have member variables?**
+- A) Yes `Correct: Abstract classes can have member variables like any other classes.`
+- B) No `Incorrect: Abstract classes, like any other class, can have member variables.`
+
+**Question 3: Can an abstract class have non-abstract methods?**
+- A) Yes `Correct: Abstract classes can have both abstract and non-abstract methods.`
+- B) No `Incorrect: Abstract classes can include fully implemented (non-abstract) methods.`
+
+**Step 17: Introducing Interfaces**
+
+**Question 1: What is an interface in Java?**
+- A) A class that provides implementation for all its methods `Incorrect: Interfaces do not provide implementation for any methods, only their signatures.`
+- B) A class that declares methods without providing implementation `Incorrect: While interfaces do declare methods without implementation, they are not classes.`
+- C) A class that cannot be instantiated but can be implemented by other classes `Correct: An interface can't be instantiated, but other classes can implement it to define the methods.`
+
+**Question 2: Who provides the implementation of methods declared in an interface?**
+- A) The interface itself `Incorrect: Interfaces in Java do not provide implementation for methods.`
+- B) The implementing classes `Correct: The classes implementing the interface provide the method implementation.`
+- C) The superclass of the interface `Incorrect: Interfaces do not have superclasses. Method implementation is provided by the classes implementing the interface.`
+
+**Question 3: How can an interface be used to enforce a contract for its implementors?**
+- A) By providing default implementations for its methods `Incorrect: While interfaces can provide default methods, the primary means of enforcing a contract is by declaring methods without providing implementation.`
+- B) By declaring methods without providing implementation `Correct: Interfaces enforce a contract by declaring methods without providing implementation. The implementing classes are obliged to provide the implementation.`
+- C) By creating a hierarchy of interfaces `Incorrect: While interfaces can inherit from other interfaces, the primary way they enforce a contract is by declaring methods without implementation.`
+
+**Step 18: Using Interfaces To Design APIs**
+
+**Question 1: Which of the following is not a way to ensure compatibility between teams working on different parts of an application?**
+- a) Define an interface for the external team to implement `Incorrect: Defining interfaces is indeed a good way to ensure compatibility, as it sets the expectations for method signatures
+
+.`
+- b) Work on the parts of the application simultaneously `Incorrect: Working simultaneously doesn't inherently ensure compatibility; clear contracts and communication do.`
+- c) Define an algorithm for the external team to implement directly into the application `Correct: This approach does not ensure compatibility as it lacks a defined contract for how components should interact.`
+
+**Question 2: What is the purpose of defining an interface between two teams working on different parts of an application?**
+- a) To allow teams to work independently without worrying about compatibility issues `Incorrect: While interfaces allow teams to work independently, they primarily serve to define a contract between the two teams.`
+- b) To define a contract between the two teams `Correct: Interfaces provide a defined contract of methods, which facilitates the independent work of different teams on separate components.`
+- c) To ensure that both teams use the same programming language `Incorrect: An interface doesn't enforce the use of a specific programming language, it's about defining the methods that classes implementing it should have.`
+
+**Question 3: Which of the following is an implementation of the ComplexAlgorithm interface?**
+- a) OneComplexAlgorithm `Incorrect: Without more context, we can't confirm if "OneComplexAlgorithm" is an implementation of the ComplexAlgorithm interface.`
+- b) ActualComplexAlgorithm `Incorrect: Without more context, we can't confirm if "ActualComplexAlgorithm" is an implementation of the ComplexAlgorithm interface.`
+- c) Both a and b `Correct: Assuming that both "OneComplexAlgorithm" and "ActualComplexAlgorithm" implement the ComplexAlgorithm interface.`
+
+**Step 19: Interfaces - Puzzles And Interesting Facts**
+
+**Question 1: Which of the following is true about interfaces in Java?**
+- a) An interface can be extended by another interface `Correct: Interfaces can extend one or more other interfaces.`
+- b) An implementation of an interface needs to implement all methods declared in the interface and its super interfaces `Incorrect: While an implementation class generally needs to implement all methods of an interface, if the class is abstract, it doesn't have to implement all methods.`
+- c) Interfaces can have member variables `Incorrect: Interfaces can have constants (static final variables) but not regular member variables.`
+
+**Question 2: Which of the following is not a way to provide a default implementation for a method in an interface?**
+- a) Include the keyword "default" in the method signature `Incorrect: This is indeed one way to provide a default method in an interface.`
+- b) Provide a body for the method in the interface definition `Incorrect: This is another way to provide a default method in an interface.`
+- c) Override the method in the implementation class `Correct: Overriding the method in the implementation class is not providing a default implementation. It's providing a class-specific implementation.`
+
+**Question 3: Why is providing default method implementations useful in building and extending frameworks?**
+- a) It allows for a new method to be added to an interface without breaking the implementation classes `Correct: Default methods enable new functionality to be added to the interfaces of libraries and ensure binary compatibility with code written for older versions of those interfaces.`
+- b) It ensures that all implementation classes have the same behavior for the default method `Incorrect: While this might happen, the main purpose is to allow extension without breaking existing implementations.`
+- c) It reduces the amount of code needed to implement the interface `Incorrect: The amount of code is not necessarily reduced as the default method can still be overridden.`
+
+**Step 20: abstract class And interface : A Comparison**
+
+**Question 1: Which of the following is a primary use case for an interface?**
+- a) Generalizing behavior by
+
+ defining a set of methods that a class must implement `Correct: This is indeed a primary use case for interfaces.`
+- b) Providing default implementations for methods `Incorrect: While interfaces can provide default method implementations, it's not their primary use case.`
+- c) Defining member variables `Incorrect: Interfaces in Java can't define member variables (only constants).`
+
+**Question 2: Which of the following is a primary use case for an abstract class?**
+- a) Providing partial implementation for a class `Correct: This is a primary use case for abstract classes. They allow for the definition of both abstract and non-abstract methods.`
+- b) Defining a contract for methods that a class must implement `Incorrect: This is a primary use case for interfaces, not abstract classes.`
+- c) Extending multiple classes `Incorrect: In Java, a class (including abstract class) can't extend multiple classes directly.`
+
+**Question 3: Which of the following can be instantiated?**
+- a) An interface `Incorrect: Interfaces cannot be instantiated.`
+- b) An abstract class `Incorrect: Abstract classes cannot be instantiated.`
+- c) A concrete class `Correct: A concrete class, unlike interfaces or abstract classes, can be instantiated.`
\ No newline at end of file
From 93abae014059edfd6062ea817e529ae332919ee4 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sun, 21 May 2023 13:29:39 +0530
Subject: [PATCH 157/178] .
From 6624f604ae4a578a75e62370ab11921aa0a471fa Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sun, 21 May 2023 13:30:18 +0530
Subject: [PATCH 158/178] .
---
...troductionToMethods-MultiplicationTable.md | 0
...-IntroductionToObjectOrientedProgrammin.md | 259 -----------
.../Q06-PrimitiveDataTypesAndAlternatives.md | 331 --------------
.../Archive/Q07-Conditionals.md | 381 ----------------
.../Archive/Q09-ReferenceTypes.md | 429 ------------------
.../Q11-ObjectOrientedProgrammingAgain.md | 285 ------------
6 files changed, 1685 deletions(-)
rename 00-Quiz-Explanation/{ => Archive}/Q02-IntroductionToMethods-MultiplicationTable.md (100%)
delete mode 100644 00-Quiz-Explanation/Archive/Q05-IntroductionToObjectOrientedProgrammin.md
delete mode 100644 00-Quiz-Explanation/Archive/Q06-PrimitiveDataTypesAndAlternatives.md
delete mode 100644 00-Quiz-Explanation/Archive/Q07-Conditionals.md
delete mode 100644 00-Quiz-Explanation/Archive/Q09-ReferenceTypes.md
delete mode 100644 00-Quiz-Explanation/Archive/Q11-ObjectOrientedProgrammingAgain.md
diff --git a/00-Quiz-Explanation/Q02-IntroductionToMethods-MultiplicationTable.md b/00-Quiz-Explanation/Archive/Q02-IntroductionToMethods-MultiplicationTable.md
similarity index 100%
rename from 00-Quiz-Explanation/Q02-IntroductionToMethods-MultiplicationTable.md
rename to 00-Quiz-Explanation/Archive/Q02-IntroductionToMethods-MultiplicationTable.md
diff --git a/00-Quiz-Explanation/Archive/Q05-IntroductionToObjectOrientedProgrammin.md b/00-Quiz-Explanation/Archive/Q05-IntroductionToObjectOrientedProgrammin.md
deleted file mode 100644
index 9ffbdae8..00000000
--- a/00-Quiz-Explanation/Archive/Q05-IntroductionToObjectOrientedProgrammin.md
+++ /dev/null
@@ -1,259 +0,0 @@
-### Question 1
-
-What is a class in Object Oriented Programming?
-
- * A) An instance of an object. `Incorrect: An instance of a class is an object, not the class itself`.
- * B) A template for creating objects. `Correct: A class in Object Oriented Programming is a blueprint or template for creating objects`.
- * C) A function to perform actions. `Incorrect: Functions (methods in Java) can be part of a class, but they are not the definition of a class`【23†source】.
-
-### Question 2
-
-What are the two main components of an object in Object Oriented Programming?
-
- * A) State and Behavior. `Correct: An object in Object Oriented Programming consists of state (represented by attributes or properties) and behavior (represented by methods)`.
- * B) Template and Instance. `Incorrect: These terms relate to the concept of classes and objects, but they are not the components of an object`.
- * C) Functions and Variables. `Incorrect: While objects can contain variables (fields) and functions (methods), in the context of Object-Oriented Programming they are usually referred to as state (fields) and behavior (methods)`【24†source】.
-
-### Question 3
-
-Which of the following methods in a class sets the title attribute?
-
- * A) setTitle(String bookTitle). `Correct: This method follows the common naming convention for a setter method, which is used to set the value of a field`.
- * B) getTitle(). `Incorrect: This method is typically a getter method, used to retrieve the value of a field, not to set it`.
- * C) setBook(String title). `Incorrect: While the method name implies it could set some information related to a book, it's not clear that it sets the title`【25†source】.
-
-### Question 4
-
-In a class representing a vehicle, what is the purpose of the this keyword when used within a method?
-
- * A) To access a static variable. `Incorrect: The this keyword is used to refer to the current instance of a class, not to access static variables`.
- * B) To differentiate between a member variable and a method argument with the same name. `Correct: The this keyword is often used in this context to avoid confusion or name clashes between a field (member variable) and a parameter`.
- * C) To call a method within the same class. `Incorrect: While this can be used to call a method within the same class, its primary function is to reference the current object instance`【26†source】.
-
-### Question 5
-
-What is the primary purpose of using access modifiers such as public and private in Object-Oriented Programming?
-
- * A) To make code more readable. `Incorrect: While good use of access modifiers can make code more readable by clearly indicating which parts of the code are intended for external access, this is not their primary purpose`.
- * B) To control what external objects can access within a given object. `Correct: Access modifiers are primarily used to control the level of access other objects have to an object's fields and methods`.
- * C) To define the scope of a variable. `Incorrect: Access modifiers do influence scope, but their primary function is to control access, not to define scope`【27†source】.
-
-### Question 6
-
-What is the purpose of private keyword in Java?
-
- * A) To make a variable or method accessible only within the class. `Correct: The private access modifier restricts access to the field or method to the class in which it is declared`.
- * B) To make a variable or method accessible outside the class. `Incorrect: The private keyword makes a variable or method less accessible, not more. A public keyword would make a variable or method accessible outside the class`.
- * C) To make a variable or method static. `Incorrect: The keyword for making a variable or method static is static, not private`【28†source】.
-
-### Question 7
-
-What are the methods used to access and modify private member variables in a class?
-
- * A) Public methods. `Incorrect: While technically correct, since getter and setter methods are usually public, this is too broad of a term`.
- * B) Getter and Setter methods. `Correct: Getter and Setter methods are specifically used to access and modify private member variables in a class`.
- * C) Static methods. `Incorrect: While static methods can access and modify static variables, they are not typically used to access and modify instance variables`【29†source】.
-
-### Question 8
-
-What is the main principle that is violated when an object directly accesses the state of another object without using any methods?
-
- * A) Inheritance. `Incorrect: Inheritance is a principle that allows a class to inherit fields and methods from another class. It is not related to the direct access of another object's state`.
- * B) Encapsulation. `Correct: Encapsulation is the principle that an object's state should be accessed and modified through its methods, not directly`.
- * C) Polymorphism. `Incorrect: Polymorphism is a principle that allows a method to behave differently depending on the object that it is acting upon. It is not related to the direct access of another object's state`【30†source】.
-
-### Question 9
-
-In a Java class, what is the purpose of a getter method?
-
- * A) To modify the value of a private member variable. `Incorrect: A getter method is used to access or retrieve the value of a private member variable, not to modify it`.
- * B) To access the value of a private member variable. `Correct: A getter method's purpose is to access or retrieve the value of a private member variable`.
- * C) To perform a calculation with a private member variable. `Incorrect: While a getter method might be used as part of a calculation, its primary purpose is to retrieve the value of a variable, not to perform calculations`【31†source】.
-
-### Question 10
-
-Which of the following best describes the concept of state in Object-Oriented Programming?
-
- * A) The condition of an object at a given time, represented by member variables. `Correct: In Object-Oriented Programming, the state of an object is the data it contains at any given moment, represented by its member variables`.
- * B) The actions an object can perform, represented by methods. `Incorrect: This describes behavior, not state`.
- * C) The relationship between two objects. `Incorrect: While relationships between objects are a significant aspect of OOP, they don't define the state of an individual object`【32†source】.
-
-### Question 11
-
-What is the primary reason for using a getter method in a Java class?
-
- * A) To ensure that an object's member variables are accessed according to the encapsulation principle. `Correct: Getter methods are used to provide access to an object's data while still maintaining the principles of encapsulation`.
- * B) To define a new method that performs a calculation with an object's member variables. `Incorrect: While a getter method can be used as part of a calculation, that's not the primary reason to use one`.
- * C) To initialize an object's member variables with default values. `Incorrect: Initialization of member variables is usually done in constructors or with direct assignment, not with getter methods`【33†source】.
-
-### Question 12
-
-Which of the following correctly defines a getter method for a private member variable name in a Java class?
-
- * A) `Correct: This is the conventional way to define a getter method in Java. It's public, has a return type matching the variable type, and returns the private variable`.
-
-```java
-public String getName() {
- return name;
-}
-```
-- B) `Incorrect: This seems to be a setter method rather than a getter method, as it takes a parameter and assigns it to the variable`.
-
-```java
-public void getName(String newName) {
- name = newName;
-}
-```
-
-- C) `Incorrect: This method signature includes a parameter, which is unusual for a getter method. Additionally, it might create confusion between the method parameter and the class field`.
-
-```java
-public String getName(String name) {
- return this.name;
-}
-```
-
-【34†source】.
-
-### Question 13
-
-What is the primary purpose of a getter method?
-
-- A) To modify the value of an object's private member variable. `Incorrect: Getter methods are used to access or return the value of a private member variable, not to modify it`.
-- B) To allow controlled access to an object's private member variable. `Correct: The primary purpose of a getter method is to provide controlled access to an object's private member variable`.
-- C) To set a default value for an object's private member variable. `Incorrect: Default values for an object's private member variables are usually set in a constructor or at the time of variable declaration, not in a getter method`【35†source】.
-
-### Question 14
-
-Consider the following code snippet. What will be the output?
-
-```java
-public class MotorBike {
- private int speed;
-
- public int getSpeed() {
- return speed;
- }
-}
-
-public class MotorBikeRunner {
- public static void main(String[] args) {
- MotorBike bike = new MotorBike();
- System.out.println("Current Bike Speed is : " + bike.getSpeed());
- }
-}
-```
-
-- A) The code will not compile because the speed variable is not initialized. `Incorrect: In Java, instance variables are automatically initialized to a default value if not explicitly initialized. For integer variables, this default value is 0`.
-- B) The output will be: Current Bike Speed is : 0. `Correct: Since the speed variable is not explicitly initialized, its value is set to the default value of 0`.
-- C) The output will be: Current Bike Speed is : null. `Incorrect: Null is the default value for object references and not for primitive types like int`【36†source】.
-
-### Question 15
-
-What are the default values for object member variables when they are not explicitly initialized?
-
-- A) null for reference types, and the type's minimum value for primitive types. `Incorrect: While reference types are initialized to null, primitive types are not initialized to their minimum value`.
-- B) null for reference types, and 0 for primitive types. `Correct: Reference types are initialized to null and primitive types like int, char, float, boolean etc., are initialized to 0, '\u0000', 0.0f, and false respectively`.
-- C) The type's maximum value for primitive types, and null for reference types. `Incorrect: Primitive types are not initialized to their maximum value`【37†source】.
-
-### Question 16
-
-What is one of the advantages of encapsulation in Object-Oriented Programming?
-
-- A) Code Reuse. `Incorrect: Code reuse is associated more with inheritance and polymorphism than with encapsulation`.
-- B) Code Compression. `Incorrect: Encapsulation does not inherently lead to code compression`.
-- C) Code Simplification. `Correct: Encapsulation simplifies code by hiding its complexity. It allows the encapsulating object to change its internal implementation without affecting the code that uses the object`【38†source】.
-### Question 17
-
-In the given example, which method is responsible for setting the speed of a MotorBike object while ensuring it is not negative?
-
-- A) setSpeed(). `Correct: The setSpeed() method is typically responsible for setting the speed of a MotorBike object. It can include validation to ensure the speed is not negative`.
-- B) increaseSpeed(). `Incorrect: The increaseSpeed() method might increase the speed of the MotorBike object, but it is not responsible for directly setting the speed`.
-- C) decreaseSpeed(). `Incorrect: The decreaseSpeed() method might decrease the speed of the MotorBike object, but it is not responsible for directly setting the speed`【39†source】.
-
-### Question 18
-
-How can code duplication be reduced when implementing validation checks for the increaseSpeed() and decreaseSpeed() methods?
-
-- A) By using separate validation checks for each method. `Incorrect: Using separate validation checks for each method would actually lead to code duplication`.
-- B) By calling the setSpeed() method with appropriate parameters inside both methods. `Correct: By calling the setSpeed() method (which could contain the necessary validation checks) from within the increaseSpeed() and decreaseSpeed() methods, we can reuse the validation logic and thus reduce code duplication`.
-- C) By using a global validation check. `Incorrect: Using a global validation check can be problematic as it may not apply universally to all situations and can lead to code coupling`【40†source】.
-
-### Question 19
-
-What is the purpose of encapsulation in the context of protecting an object's state?
-
-- A) To prevent other objects from directly accessing the object's state. `Correct: Encapsulation is a principle of Object-Oriented Programming that helps protect an object's state by hiding its data (fields) and providing methods for data access and manipulation`.
-- B) To allow other objects to directly access the object's state. `Incorrect: Encapsulation does not allow other objects to directly access the object's state, instead, it provides controlled access via methods`.
-- C) To create a new object with the same state as the original object. `Incorrect: Encapsulation does not deal with creating new objects with the same state as existing ones`【41†source】.
-
-### Question 20
-
-In the given example, which method is used to start the MotorBike?
-
-- A) begin(). `Incorrect: The method name to start the MotorBike is not given in the question. However, in conventional programming practice, methods such as "start" or "run" are often used`.
-- B) start(). `Correct: In common practice, the method to start a MotorBike or similar objects could be named "start"`.
-- C) initiate(). `Incorrect: Although "initiate" could be a valid method name, it's not as commonly used as "start"`【42†source】.
-
-### Question 22
-
-What is the purpose of a constructor in a Java class?
-
-- a) To create an instance of the class with the specified initial state. `Correct: A constructor in Java is used to create an instance of a class and can initialize the state of the object`.
-- b) To perform calculations on the class variables. `Incorrect: While constructors can contain code that performs calculations, this is not their primary purpose`.
-- c) To modify the state of an object after it has been created. `Incorrect: Constructors are used to initialize an object when it is created, not to modify its state after creation`.
-- d) To destroy an object when it is no longer needed. `Incorrect: In Java, destruction of objects is managed by the Garbage Collector, not by constructors`【43†source】.
-
-### Question 6
-
-What is a default constructor in Java?
-
-- a) A constructor that is automatically provided by the compiler if no other constructors are defined. `Correct: If no constructors are defined in a Java class, the compiler automatically provides a default constructor with no arguments`.
-- b) A constructor with a single argument. `Incorrect: The number of arguments has no bearing on whether a constructor is considered default`.
-- c) A constructor that takes an unlimited number of arguments. `Incorrect: A default constructor does not take an unlimited number of arguments, it takes no arguments`.
-- d) A constructor that initializes all instance variables to their default values. `Incorrect: While a default constructor can be used to initialize variables, its defining feature is that it is provided by the compiler when no other constructors are defined`【44†source】.
-
-### Question 23
-
-What is a constructor in Java?
-
-- a) A special method with the same name as the class. `Correct: A constructor is a special method in a class, with the same name as the class`.
-- b) A method that returns a value. `Incorrect: Constructors do not return a value`.
-- c) A method that can be called directly. `Incorrect: Constructors are not called directly; they are called when an instance of the class is created using the new keyword`.
-- d) A method that can only accept zero arguments. `Incorrect: Constructors can take any number of arguments, including zero`【45†source】.
-
-### Question 24
-
-How is a constructor invoked in Java?
-
-- a) By calling the method directly. `Incorrect: Constructors are not called directly, they are invoked when an instance of the class is created`.
-- b) By using the new keyword while creating an object of the class. `Correct: Constructors are invoked using the new keyword when an object of the class is created`.
-- c) By declaring the constructor as static. `Incorrect: Static methods belong to the class, not the instance of the class. Constructors are not static and cannot be declared as such`.
-- d) By using the this keyword while creating an object of the class. `Incorrect: The this keyword refers to the current instance of the class and is not used to invoke a constructor`【46†source】.
-
-### Question 25
-
-Can a constructor accept multiple arguments in Java?
-
-- a) No, a constructor can only accept zero or one argument. `Incorrect: A constructor in Java can accept any number of arguments`.
-- b) Yes, a constructor can accept multiple arguments. `Correct: A constructor in Java can accept multiple arguments`.
-- c) Only the default constructor can accept multiple arguments. `Incorrect: The default constructor does not take any arguments`.
-- d) It depends on the access modifiers of the constructor. `Incorrect: The number of arguments a constructor can take does not depend on its access modifiers`【47†source】.
-
-### Question 26
-
-What is a default constructor in Java?
-
-- a) A constructor that accepts no arguments. `Correct: A default constructor is a no-argument constructor`.
-- b) A constructor that is defined by the programmer. `Incorrect: A default constructor is provided by the compiler if no constructor is defined by the programmer`.
-- c) A constructor that is generated by the compiler when no constructor is defined. `Correct: If no constructor is defined in the class, the Java compiler automatically provides a default constructor`.
-- d) A constructor that is called automatically when an object is created. `Incorrect: While all constructors are invoked when an object is created, not all are default constructors`【48†source】.
-
-### Question 27
-
-What happens when a class has no constructor defined in Java?
-
-- a) The code fails to compile. `Incorrect: If a class in Java does not have a constructor defined, the code will still compile`.
-- b) A default constructor is generated by the compiler. `Correct: If no constructor is explicitly defined in a Java class, the compiler automatically generates a default constructor`.
-- c) The code compiles and runs without any issues. `Incorrect: While the code would still compile and could run without issues, this answer is misleading because it does not mention the automatic generation of a default constructor`.
-- d) The class cannot be instantiated. `Incorrect: Even if a constructor is not defined, a class can still be instantiated using the default constructor`【49†source】.
\ No newline at end of file
diff --git a/00-Quiz-Explanation/Archive/Q06-PrimitiveDataTypesAndAlternatives.md b/00-Quiz-Explanation/Archive/Q06-PrimitiveDataTypesAndAlternatives.md
deleted file mode 100644
index 879dd81e..00000000
--- a/00-Quiz-Explanation/Archive/Q06-PrimitiveDataTypesAndAlternatives.md
+++ /dev/null
@@ -1,331 +0,0 @@
-Step 01: The Integer Types
-
-Question 1: Which of the following wrapper classes corresponds to the int primitive type in Java?
-
-- A) Byte (Incorrect: The `Byte` class corresponds to the byte primitive type, not int.)
-- B) Integer (Correct: The `Integer` class is the wrapper class for the `int` primitive type. It provides methods to work with int values.)
-- C) Short (Incorrect: The `Short` class corresponds to the short primitive type, not int.)
-
-Explanation:
-
-- Option A is incorrect because the `Byte` class corresponds to the byte primitive type, not int.
-- Option B is correct because the `Integer` class is the wrapper class specifically designed to work with int values.
-- Option C is incorrect because the `Short` class corresponds to the short primitive type, not int.
-
-Question 2: What is the maximum value of a short data type in Java?
-
-- A) 127
-- B) 32767 (Correct: The maximum value of a `short` is 32767)
-- C) 2147483647 (Incorrect: The value 2147483647 is the maximum value for the `int` data type, not short.)
-
-Explanation:
-
-- Option A is incorrect because 127 is the maximum value for the `byte` data type, not short.
-- Option B is correct because 32767 is the maximum value for the `short` data type in Java.
-- Option C is incorrect because 2147483647 is the maximum value for the `int` data type, not short.
-
-Question 3: What type of cast is used to store a smaller data value in a larger data type variable?
-
-- A) Implicit cast (Correct: Implicit casting is used to automatically convert a smaller data type to a larger data type)
-- B) Explicit cast
-
-Explanation:
-
-- Option A is correct because implicit casting is used to automatically convert a smaller data type to a larger data type without any loss of data.
-- Option B is incorrect because explicit casting is used when converting a larger data type to a smaller data type and requires explicit specification.
-
-
-
-Step 02: Integer Representations, And Other Puzzles
-
-Question 1: What are the three number systems supported by Java for integers?
-
-- A) Decimal, Octal, and Binary
-- B) Decimal, Octal, and Hexadecimal (Correct: The three number systems supported by Java for integers are decimal, octal, and hexadecimal)
-- C) Decimal, Binary, and Hexadecimal (Incorrect: Binary is also a number system supported by Java for integers)
-
-Explanation:
-
-- Option A is incorrect because it doesn't include hexadecimal, which is one of the number systems supported by Java for integers.
-- Option B is correct because decimal, octal, and hexadecimal are the three number systems supported by Java for integers.
-- Option C is incorrect because it includes binary, but it doesn't include octal.
-
-Question 2: Which of the following is the correct representation for the value 16 in a hexadecimal system?
-
-- A) 0x10 (Correct: In a hexadecimal system, 16 is represented as 0x10)
-- B) 010 (Incorrect: This represents the value 10 in an octal system)
-- C) 0x16 (Incorrect: This represents the value 22 in a hexadecimal system)
-
-Explanation:
-
-- Option A is correct because in a hexadecimal system, the prefix "0x" is used, followed by the digits representing the value. Therefore, 16 is represented as 0x10.
-- Option B is incorrect because "010" represents the value 10 in an octal system, not hexadecimal.
-- Option C is incorrect because "0x16" represents the value 22 in a hexadecimal system, not 16.
-
-Question 3: What is the difference between prefix and post-fix increment operators in Java?
-
-- A) Prefix increment takes place before the assignment, and post-fix increment takes place after the assignment. (Correct: Prefix increment happens before the assignment, while postfix increment happens after the assignment.)
-- B) Prefix increment takes place after the assignment, and post-fix increment takes place before the assignment. (Incorrect: The order of increment is reversed in the explanation)
-- C) There is no difference between prefix and post-fix increment operators in Java. (Incorrect: There is a difference in the order of increment)
-
-Explanation:
-
-- Option A is correct because prefix increment (++variable) happens before the assignment, meaning the variable is incremented and then used in the expression.
-- Option B is incorrect because the explanation states that postfix increment happens before the assignment, which is incorrect.
-- Option C is incorrect because there is indeed a difference between prefix and postfix increment operators in Java.
-
-
-
-Step 03: Classroom Exercise CE-01 (With Solutions)
-
-Question 1: What is the purpose of the BiNumber class?
-
-- A) To store a single integer and perform basic arithmetic operations
-- B) To store a pair of integers and perform basic arithmetic operations (Correct: The purpose of the BiNumber class is to store a pair of integers and perform basic arithmetic operations)
-- C) To store a list of integers and perform basic arithmetic operations
-
-Explanation:
-
-- Option A is incorrect because it mentions storing a single integer, while the BiNumber class is specifically designed to store a pair of integers.
-- Option B is correct because the BiNumber class is used to store a pair of integers and provides methods to perform basic arithmetic operations on those numbers.
-- Option C is incorrect because it mentions storing a list of integers, which is not the purpose of the BiNumber class.
-
-Question 2: Which method is used to double the values of both numbers in a BiNumber object?
-
-- A) double()
-- B) doubleNumbers() (Correct: The `doubleNumbers()` method is used to double the values of both numbers in a BiNumber object)
-- C) doubleValue()
-
-Explanation:
-
-- Option A is incorrect because `double()` is not a valid method for doubling the values of both numbers in a BiNumber object.
-- Option B is correct because the `doubleNumbers()` method specifically performs the operation of doubling the values of both numbers in a BiNumber object.
-- Option C is incorrect because `doubleValue()` is not the method responsible for doubling both numbers in a BiNumber object.
-
-Question 3: What will be the output of the following code snippet?
-
-```java
-BiNumber numbers = new BiNumber(4, 5);
-System.out.println(numbers.add());
-numbers.doubleValue();
-System.out.println(numbers.getNumber1());
-System.out.println(numbers.getNumber2());
-```
-
-- A) 9, 8, 10
-- B) 9, 8, 5
-- C) 9, 4, 5 (Correct: The output will be 9, 4, 5 after adding the numbers and doubling the value of the BiNumber object)
-
-Explanation:
-
-- The first line creates a BiNumber object with values 4 and 5.
-- The second line prints the result of adding the two numbers, which is 9.
-- The third line calls the `doubleValue()` method on the BiNumber object, doubling both numbers internally.
-- The fourth line prints the first number of the BiNumber object, which is now 4.
-- The fifth line prints the second number of the BiNumber object, which remains 5.
-- Therefore, the output will be 9, 4, 5.
-
-
-
-Step 05: Floating-Point Types
-
-Question 1: What is the default type for floating-point literals in Java?
-
-- A) float
-- B) double (Correct: The default type for floating-point literals in Java is `double`)
-
-Explanation:
-
-- Option A is incorrect because the default type for floating-point literals in Java is `double`.
-- Option B is correct because `double` is the default type for floating-point literals in Java.
-
-Question 2: How can you create a float literal?
-
-- A) float f = 34.5
-- B) float f = 34.5f; (Correct: To create a float literal, you need to append the suffix `f` to the value)
-- C) float f = (float)34.5
-
-Explanation:
-
-- Option A is incorrect because 34.5 without the `f` suffix is considered a `double` literal, not a `float` literal.
-- Option B is correct because adding the `f` suffix to the value makes it a `float` literal.
-- Option C is incorrect because explicitly casting the value to a `float` is another way to create a `float` literal, but it is not necessary when assigning a literal value directly.
-
-Question 3: Which type of casting is needed to convert a double value to a float value?
-
-- A) Implicit casting
-- B) Explicit casting (Correct: Explicit casting is required to convert a `double` value to a `float` value)
-
-Explanation:
-
-- Option A is incorrect because implicit casting is not sufficient to convert a `double` value to a `float` value. It could result in a loss of precision.
-- Option B is correct because explicit casting, specifically `(float)`, is needed to convert a `double` value to a `float` value. It explicitly tells the compiler to perform the conversion, even though there may be potential loss of precision.
-
-
-
-Step 06: Introducing BigDecimal
-
-Question 1: What is the main reason for using the BigDecimal data type in Java?
-
-- To represent floating-point numbers with higher precision (Correct: The main reason for using the BigDecimal data type is to represent floating-point numbers with higher precision)
-- To perform faster calculations
-- To store large integer values
-
-Explanation:
-
-- Option A is correct because the BigDecimal data type is used to represent floating-point numbers with higher precision, avoiding issues with rounding errors that can occur with other floating-point types.
-- Option B is incorrect because the primary purpose of BigDecimal is precision, not performance.
-- Option C is incorrect because BigDecimal is not specifically designed for storing large integer values; it is more focused on decimal numbers with high precision.
-
-Question 2: What is the best way to construct a BigDecimal object to achieve high precision?
-
-- Using integer literals
-- Using double literals
-- Using string literals (Correct: The best way to construct a BigDecimal object to achieve high precision is by using string literals)
-
-Explanation:
-
-- Option A is incorrect because using integer literals might result in the loss of precision when constructing a BigDecimal object.
-- Option B is incorrect because using double literals may introduce rounding errors when constructing a BigDecimal object.
-- Option C is correct because using string literals, such as "0.12345678901234567890", allows you to specify the exact precision and avoid any potential rounding errors.
-
-Question 3: What is the main characteristic of BigDecimal objects?
-
-- Mutable
-- Immutable (Correct: BigDecimal objects are immutable, meaning their values cannot be changed once created)
-- Synchronized
-
-Explanation:
-
-- Option A is incorrect because BigDecimal objects are immutable, meaning their values cannot be changed once created.
-- Option B is correct because BigDecimal objects have the characteristic of immutability, ensuring that their values remain unchanged.
-- Option C is incorrect because synchronization is not a characteristic specific to BigDecimal objects. It is related to thread safety.
-
-
-
-Step 06: BigDecimal Operations
-
-Question: Which of the following methods can be used for arithmetic operations on BigDecimal objects?
-
-- a. add()
-- b. multiply()
-- c. subtract()
-- d. All of the above (Correct: All of the mentioned methods can be used for arithmetic operations on BigDecimal objects)
-
-Explanation:
-
-- Option a is correct because the `add()` method is used for addition of BigDecimal objects.
-- Option b is correct because the `multiply()` method is used for multiplication of BigDecimal objects.
-- Option c is correct because the `subtract()` method is used for subtraction of BigDecimal objects.
-- Option d is correct because all of the mentioned methods (add(), multiply(), and subtract()) can be used for arithmetic operations on BigDecimal objects.
-
-Question: Can you perform arithmetic operations directly between a BigDecimal object and a primitive data type, like an int or a double?
-
-- a. Yes
-- b. No (Correct: No, arithmetic operations between BigDecimal objects and primitive data types require explicit conversion)
-
-Explanation:
-
-- Option a is incorrect because arithmetic operations between BigDecimal objects and primitive data types cannot be performed directly without explicit conversion.
-- Option b is correct because explicit conversion, using methods like `BigDecimal.valueOf()`, is required to perform arithmetic operations between BigDecimal objects and primitive data types.
-
-Question: How can you perform an arithmetic operation between a BigDecimal object and a primitive int value?
-
-- a. Convert the int to a BigDecimal using BigDecimal.valueOf() (Correct: To perform an arithmetic operation between a BigDecimal object and a primitive int value, you need to convert the int to a BigDecimal using BigDecimal.valueOf())
-
-Explanation:
-
-- Option a is correct because to perform an arithmetic operation between a BigDecimal object and a primitive int value, you need to convert the int to a BigDecimal using the `BigDecimal.valueOf()` method.
-- Using this method, you can create a BigDecimal object representing the int value and then perform arithmetic operations with other BigDecimal objects.
-
-
-
-Step 08: boolean, Relational and Logical Operators
-
-Question: Which of the following operators is a logical operator in Java?
-
-- a) >
-- b) &&
-- c) <= (Correct: The logical operator in Java is represented by the symbol &&)
-
-Explanation:
-
-- Option a is incorrect because the ">" operator is a relational operator used for comparison.
-- Option b is correct because the "&&" operator is the logical AND operator in Java, which combines two boolean expressions.
-- Option c is incorrect because the "<=" operator is a relational operator used for comparison, not a logical operator.
-
-Question: Given the following code snippet, what will be the value of result?
-
-```java
-int a = 10;
-int b = 5;
-boolean result = (a > b) && (a < 2 * b);
-```
-
-- a) true (Correct: The value of result will be true)
-- b) false
-
-Explanation:
-
-- In the given code snippet, the expression `(a > b) && (a < 2 * b)` is evaluated.
-- `(a > b)` evaluates to true because 10 is greater than 5.
-- `(a < 2 * b)` also evaluates to true because 10 is less than 2 times 5, which is 10.
-- The logical AND operator `&&` combines these two boolean expressions and returns true only if both expressions are true.
-- Since both expressions are true, the value of `result` will be true.
-
-Question: What will the following expression evaluate to?
-
-```java
-boolean x = true;
-boolean y = false;
-boolean z = !(x || y);
-```
-
-- a) true
-- b) false (Correct: The expression will evaluate to false)
-
-Explanation:
-
-- The expression `(x || y)` evaluates to true because at least one of the operands (x or y) is true.
-- The `!` operator negates the result, so `!(x || y)` evaluates to false.
-- Therefore, the value of `z` will be false.
-
-
-
-Step 10: Character Types
-
-Question 1: What is the Unicode representation of the double quotation mark?
-
-- \u0021
-- \u0022 (Correct: The Unicode representation of the double quotation mark is \u0022)
-- \u0023
-
-Explanation:
-
-- Option \u0021 represents the Unicode character for exclamation mark (!), not the double quotation mark.
-- Option \u0022 is correct because it represents the Unicode character for double quotation mark (").
-- Option \u0023 represents the Unicode character for hash or number sign (#), not the double quotation mark.
-
-Question 2: What data type in Java is used to store Unicode characters?
-
-- String
-- char (Correct: The `char` data type in Java is used to store Unicode characters)
-- int
-
-Explanation:
-
-- Option String is incorrect because `String` is a data type used to store sequences of characters, not a single Unicode character.
-- Option char is correct because the `char` data type is specifically designed to store a single Unicode character.
-- Option int is incorrect because `int` is used to store integer values, not Unicode characters.
-
-Question 3: What happens when you perform the following operation in Java: `char cn = 65;`?
-
-- A character with a Unicode value of 65 is stored in the variable cn. (Correct: The character with Unicode value 65, which is 'A', is stored in the variable cn)
-- An integer value of 65 is stored in the variable cn.
-- A compilation error occurs.
-
-Explanation:
-
-- Option A is correct because assigning the value 65 to a char variable `cn` will store the character 'A' in `cn`. In Java, characters are internally represented using Unicode values.
-- Option B is incorrect because 65 is the Unicode value of 'A', not an integer value.
-- Option C is incorrect because there is no compilation error in assigning a Unicode value to a char variable.
diff --git a/00-Quiz-Explanation/Archive/Q07-Conditionals.md b/00-Quiz-Explanation/Archive/Q07-Conditionals.md
deleted file mode 100644
index 8510fb5f..00000000
--- a/00-Quiz-Explanation/Archive/Q07-Conditionals.md
+++ /dev/null
@@ -1,381 +0,0 @@
-### Question 28
-
-What is the if statement used for in Java?
-
-- a) To execute some code when a boolean condition is true. `Correct: An if statement in Java is used to execute a block of code when a specified condition is true`.
-- b) To execute some code when a boolean condition is false. `Incorrect: This is not the primary purpose of the if statement. Though an "else" clause following an if statement can execute code when the condition is false, the primary purpose of the if statement is to execute code when a condition is true`.
-- c) To execute some code regardless of the boolean condition. `Incorrect: An if statement is condition-dependent. Code within its block is executed only when the condition is true`【50†source】.
-
-### Question 29
-
-What is the difference between if and if-else statements in Java?
-
-- a) There is no difference, they do the same thing. `Incorrect: There is a difference between if and if-else statements. The if-else statement includes a default action when the if condition is false`.
-- b) If statement executes code only when the condition is true, whereas if-else statement executes code when the condition is false. `Correct: An if statement executes code only when its condition is true. An if-else statement adds a default action that is executed when the if condition is false`.
-- c) If statement executes code only when the condition is false, whereas if-else statement executes code when the condition is true. `Incorrect: This is the opposite of how if and if-else statements work in Java`【51†source】.
-
-### Question 30
-
-What is the output of the following code snippet in Java?
-
-```java
-int i = 10;
-if(i < 5) {
- System.out.println("i is less than 5");
-} else if(i > 20) {
- System.out.println("i is greater than 20");
-} else {
- System.out.println("i is between 5 and 20");
-}
-```
-
-- a) "i is less than 5" `Incorrect: The value of i is 10, which is not less than 5`.
-- b) "i is greater than 20" `Incorrect: The value of i is 10, which is not greater than 20`.
-- c) "i is between 5 and 20" `Correct: The value of i is 10, which falls between 5 and 20`【52†source】.
-
-### Question 31
-
-What is the purpose of the if-else if-else statement in Java?
-
-- a) To execute some code when a boolean condition is true. `Incorrect: This is a feature of the if statement, not specifically the if-else if-else statement`.
-- b) To execute some code when multiple conditions are true. `Incorrect: An if-else if-else statement is used to check multiple conditions, but it only executes the first block of code whose condition is true`.
-- c) To execute some code when one and only one condition is true. `Correct: In an if-else if-else statement, once a true condition is found and its corresponding code block is executed, the remaining conditions are not checked`【53†source】.
-
-### Question 32
-
-What happens if multiple conditions in the if-else if-else statement evaluate to true in Java?
-
-- a) All corresponding code blocks are executed. `Incorrect: Only the first block of code with a true condition is executed in an if-else if-else statement`.
-- b) Only the first corresponding code block is executed. `Correct: In an if-else if-else statement, once a true condition is found and its corresponding code block is executed, the remaining conditions are not checked`.
-- c) Only the last corresponding code block is executed. `Incorrect: Only the first block of code with a true condition is executed in an if-else if-else statement`【54†source】.
-
-### Question 33
-
-What is the output of the following code snippet in Java?
-
-```java
-int i = 15;
-if(i < 5) {
- System.out.println("i is less than 5");
-} else if(i > 20) {
- System.out.println("i is greater than 20");
-} else if(i < 10) {
- System.out.println("i is less than 10");
-} else {
- System.out.println("i is between 10 and 20");
-}
-```
-
-- a) "i is less than 5" `Incorrect: The value of i is 15, which is not less than 5`.
-- b) "i is greater than 20" `Incorrect: The value of i is 15, which is not greater than 20`.
-- c) "i is less than 10" `Incorrect: The value of i is 15, which is not less than 10`.
-- d) "i is between 10 and 20" `Correct: The value of i is 15, which falls between 10 and 20`【55†source】.
-
-### Question 34
-
-What is the output of the following code snippet?
-
-```java
-public static void puzzleOne() {
- int k = 15;
- if(k > 20) {
- System.out.println(1);
- } else if(k > 10) {
- System.out.println(2);
- } else if(k < 20) {
- System.out.println(3);
- } else {
- System.out.println(4);
- }
-}
-```
-
-- a) 1 `Incorrect: The value of k is 15, which is not greater than 20`.
-- b) 2 `Correct: The value of k is 15, which is greater than 10`.
-- c) 3 `Incorrect: The value of k is 15, which is less than 20, but the previous condition (k > 10) was already met and its block was executed`.
-- d) 4 `Incorrect: The else block would only execute if none of the previous conditions were met, but the condition (k > 10) was met`【56†source】.
-
-### Question 35
-
-What is the output of the following code snippet?
-
-```java
-public static void puzzleTwo() {
- int l = 15;
- if(l < 20)
- System.out.println("l < 20");
- if(l > 20)
- System.out.println("l > 20");
- else
- System.out.println("Who Am I?");
-}
-```
-
-- a) l < 20 `Incorrect: While it's true that l < 20, the subsequent else clause is associated with the second if statement (l > 20), not the first one`.
-- b) l > 20 `Incorrect: The value of l is 15, which is not greater than 20`.
-- c) Who Am I? `Correct: The else clause is associated with the second if statement, and since l is not greater than 20, "Who Am I?" is printed`【57†source】.
-
-### Question 36
-
-What is the output of the following code snippet?
-
-```java
-public static void puzzleThree() {
- int m = 15;
- if(m > 20)
- if(m < 20)
- System.out.println("m > 20"); else
- System.out.println("Who Am I?");
-}
-```
-
-- a) m > 20 `Incorrect: The outer condition (m > 20) is not met, so none of the code inside the outer if statement is executed`.
-- b) Who Am I? `Incorrect: The outer condition (m > 20) is not met, so none of the code inside the outer if statement is executed`.
-- c) Nothing is printed. `Correct: The outer condition (m > 20) is not met, so none of the code inside the outer if statement is executed`【58†source】.
-
-
-### Question 37
-
-What is the output of the following code snippet?
-
-```java
-int i = 0;
-if(i) {
- System.out.println("i");
-}
-```
-
-- a) i `Incorrect: This code will not compile because i is an integer and the if statement requires a boolean`.
-- b) Compiler Error `Correct: This code will not compile because i is an integer and the if statement requires a boolean`.
-- c) Nothing is printed `Incorrect: This code will not compile, so there is no opportunity for anything to be printed`【59†source】.
-
-### Question 38
-
-What is the output of the following code snippet?
-
-```java
-public static void puzzleFive() {
- int number = 5;
- if(number < 0)
- number = number + 10;
- number++;
- System.out.println(number);
-}
-```
-
-- a) 4 `Incorrect: The value of number is 5, it is incremented to 6 and then printed`.
-- b) 5 `Incorrect: The value of number is 5, but it is incremented before it is printed`.
-- c) 6 `Correct: The value of number is 5, it is incremented to 6 and then printed`【60†source】.
-
-### Question 39
-
-What is the purpose of using the Scanner class in Java?
-
-- a) To scan user input from the console `Correct: The Scanner class is used to read input from various sources, including the console`.
-- b) To read input from a file `Incorrect: While the Scanner class can be used to read input from a file, the question is about the main purpose of the Scanner class`.
-- c) To generate random numbers `Incorrect: The Scanner class does not generate random numbers`【61†source】.
-
-### Question 40
-
-What do you need to pass as a parameter to the Scanner constructor?
-
-- a) System.in `Correct: To read input from the console, System.in is passed as a parameter to the Scanner constructor`.
-- b) System.out `Incorrect: System.out is not used for input, but rather to output data`.
-- c) System.error `Incorrect: System.error does not exist in Java. You may be thinking of System.err, which is used for error output, not input`【62†source】.
-
-
-### Question 41
-
-How do you read an integer input from the console using the Scanner class?
-
-- a) scanner.nextInt() `Correct: The nextInt() method of the Scanner class is used to read an integer input from the console`.
-- b) scanner.readInt() `Incorrect: The Scanner class does not have a readInt() method`.
-- c) scanner.getInt() `Incorrect: The Scanner class does not have a getInt() method`【63†source】.
-
-### Question 42
-
-What is the purpose of the following code snippet?
-
-```java
-Scanner scanner = new Scanner(System.in);
-```
-
-- a) To initialize the Scanner class `Incorrect: This statement creates an instance of the Scanner class, not initializes it`.
-- b) To import the Scanner class `Incorrect: This statement creates an instance of the Scanner class, not imports it`.
-- c) To create an instance of the Scanner class `Correct: This statement creates an instance of the Scanner class`【64†source】.
-
-### Question 43
-
-What does the following line of code do?
-
-```java
-int number1 = Scanner.nextInt();
-```
-
-- a) Imports the next integer from the keyboard `Incorrect: This statement initializes the value of number1 to the next integer read from the keyboard`.
-- b) Initializes the value of number1 to the next integer from the keyboard `Correct: This statement initializes the value of number1 to the next integer read from the keyboard`.
-- c) Creates an instance of the nextInt method `Incorrect: This statement does not create an instance of a method`【65†source】.
-
-### Question 44
-
-What does the following code snippet do?
-
-```java
-System.out.println("Your Inputs Are:");
-System.out.println("Number1: " + number1);
-System.out.println("Number2: " + number2);
-System.out.println("Choice: " + choice);
-```
-
-- a) Imports the values of number1, number2, and choice from the keyboard `Incorrect: This code snippet does not import any values. It outputs them to the console`.
-- b) Writes the values of number1, number2, and choice to the console `Correct: This code snippet outputs the values of number1, number2, and choice to the console`.
-- c) Initializes the values of number1, number2, and choice `Incorrect: This code snippet does not initialize any values. It outputs them to the console`【66†source】.
-
-
-### Question 45
-
-What is the purpose of the if-else-else if statement in the code?
-
-- a) To check for 4 favorable conditions `Incorrect: While it may look at multiple conditions, it's not specifically for checking 4 conditions`.
-- b) To handle invalid operation choice `Correct: If-else-else if statement is used to handle various possibilities including invalid operation choice`.
-- c) To handle both favorable conditions and invalid operation choice `Correct: This statement is used to handle multiple conditions, both favorable and unfavorable (including invalid operation choice)`.
-- d) None of the above `Incorrect: The if-else-else if statement serves to check conditions and execute code based on those conditions`【67†source】.
-
-### Question 46
-
-What does the statement `"System.out.println("Result = " + (number1 + number2));"` do in the code?
-
-- a) Prints the sum of number1 and number2 `Correct: This statement calculates the sum of number1 and number2 and prints it`.
-- b) Prints the difference of number1 and number2 `Incorrect: This statement is calculating and printing the sum, not the difference`.
-- c) Prints the product of number1 and number2 `Incorrect: This statement is calculating and printing the sum, not the product`.
-- d) Prints the quotient of number1 and number2 `Incorrect: This statement is calculating and printing the sum, not the quotient`【68†source】.
-
-### Question 47
-
-What is the output when choice is 5?
-
-- a) Result = 55 `Incorrect: If choice is not one of the options (1, 2, 3, or 4), the output would be "Invalid Operation"`.
-- b) Invalid Operation `Correct: If choice is not one of the options (1, 2, 3, or 4), the output would be "Invalid Operation"`.
-- c) Number1: 25 `Incorrect: The value of Number1 or Number2 is not outputted based on the value of choice`.
-- d) Number2: 35 `Incorrect: The value of Number1 or Number2 is not outputted based on the value of choice`【69†source】.
-
-
-### Question 48
-
-Which of the following is NOT true about a switch statement in Java?
-
-- A) A switch statement is used to test multiple conditions `Incorrect: The switch statement in Java is used to select one of many code blocks to be executed, essentially testing multiple conditions`.
-- B) The default clause is executed when none of the cases match `Correct: The default clause in a switch statement is indeed executed when none of the case conditions match`.
-- C) The switch statement can handle the default possibility `Correct: The switch statement can include a default clause which is executed when no matching case has been found`.
-- D) The switch statement is used to test only one condition `Correct: This statement is false. The switch statement is used to test multiple conditions (cases) based on a single variable/expression`【70†source】.
-
-### Question 49
-
-What is the purpose of the break statement in a switch statement in Java?
-
-- A) To break out of the switch after a successful match `Correct: The break statement is used to stop the execution of the remaining cases in the switch statement after a case has been executed`.
-- B) To continue to the next case in the switch `Incorrect: Without a break statement, the program will continue executing the next case, even if the case condition does not match. The break statement serves to prevent this`.
-- C) To stop the execution of the program `Incorrect: The break statement only stops the execution of the current switch statement, not the entire program`.
-- D) To continue to the default clause in the switch `Incorrect: The break statement is used to exit the switch statement, not to jump to the default case`【71†source】.
-
-### Question 50
-
-What will the following code snippet output in Java?
-
-```java
-int number = 2;
-switch(number) {
- case 1:
- System.out.println(1);
- case 2:
- System.out.println(2);
- case 3:
- System.out.println(3);
- default:
- System.out.println("default");
-}
-```
-
-- A) 1 `Incorrect: Given that "number" is 2, it won't print 1`.
-- B) 2 `Incorrect: Given that "number" is 2, it will start at case 2 but since there are no break statements, it will also execute the remaining cases and the default`.
-- C) 3 `Incorrect: Given that "number" is 2, it will print 3 as well, but it will also print 2 and "default"`.
-- D) 1, 2, 3, default `Correct: Given that "number" is 2 and there are no break statements, it will start at case 2 and also execute the remaining cases (3) and the default`【72†source】.
-
-
-
-### Question 51
-
-What type of conditions can be evaluated using an if-family conditional?
-
-- a. Only boolean conditions `Correct: if, else if, and else in Java evaluate boolean conditions. They run or skip code blocks based on whether a condition is true or false.`
-- b. Only integer values `Incorrect: While integer values can be part of a condition, the condition itself is evaluated as a boolean.`
-- c. Both boolean and integer values `Incorrect: The conditions are always evaluated as booleans, although they can compare integer values.`
-- d. None of the above `Incorrect: Option a is the correct one.`【73†source】
-
-### Question 52
-
-What is the advantage of using a switch conditional over an if-family conditional?
-
-- a. More readable and compact `Correct: Switch cases can be more readable and compact when comparing a variable to several constant values.`
-- b. Can be used to check for only integer values `Incorrect: Switch cases can also handle characters and enumerated types, not only integers.`
-- c. More strict rules `Incorrect: If-else conditionals can be more flexible, since they can evaluate any boolean condition, not just value comparisons.`
-- d. More versatile `Incorrect: If-else conditionals are more versatile since they can evaluate any boolean condition.`【74†source】
-
-### Question 53
-
-What is the disadvantage of using a switch conditional over an if-family conditional?
-
-- a. Can lead to subtle errors in the program `Correct: One such error can occur if the 'break' keyword is forgotten after a case.`
-- b. More versatile `Incorrect: Versatility is not a disadvantage.`
-- c. Can only check for boolean conditions `Incorrect: Switch cases do not evaluate boolean conditions, but rather check the value of a variable against constant values.`
-- d. Not as strict as if-family conditional `Incorrect: Strictness in this context doesn't refer to a disadvantage.`【75†source】
-
-### Question 54
-
-What is the name of the day represented by the number 3 in the determineNameOfDay method?
-
-- A. Monday `Incorrect: Monday is usually represented by 1 in such systems.`
-- B. Tuesday `Incorrect: Tuesday is usually represented by 2.`
-- C. Wednesday `Correct: In this system, Wednesday would be represented by 3.`
-- D. Thursday `Incorrect: Thursday would typically be represented by 4.`【76†source】
-
-### Question 55
-
-What is the name of the month represented by the number 9 in the determinenameofMonth method?
-
-- A. January `Incorrect: January is usually represented by 1 in such systems.`
-- B. February `Incorrect: February is usually represented by 2.`
-- C. March `Incorrect: March is usually represented by 3.`
-- D. September `Correct: In this system, September would be represented by 9.`【77†source】
-
-### Question 56
-
-Is the day represented by the number 1 considered to be a week day in the isWeekDay method?
-
-- A. Yes `Correct: In many systems, the days of the week are numbered from 1 (Monday) to 7 (Sunday), so 1 would be a weekday.`
-- B. No `Incorrect: As stated above, 1 usually represents Monday, which is a weekday.`【78†source】
-
-### Question 57
-
-What is the purpose of the ternary operator ?: in Java?
-
-- A. To perform addition of two operands `Incorrect: The ternary operator is not used for addition. It's used for conditional operations.`
-- B. To perform subtraction of two operands `Incorrect: The ternary operator is not used for subtraction. It's used for conditional operations.`
-- C. To perform conditional operations `Correct: The ternary operator is used to perform a simple if-else check in one line.`【79†source】
-
-### Question 58
-
-What should be the return type of both expressions in the ternary operator ?: in Java?
-
-- A. Both expressions can return any type of value `Incorrect: While the expressions can be of any type, they both need to be of the same type or compatible types.`
-- B. Both expressions should return different types of value `Incorrect: Both expressions should return values of the same type or of compatible types.`
-- C. Both expressions should return values of the same type `Correct: Both expressions in a ternary operation should be of the same type, or of types that can be automatically converted to a common type.`【80†source】
-
-### Question 59
-
-What is the syntax of the ternary operator ?: in Java?
-
-- A. result = (expression-if-condition-true ? condition : expression:if-condition-false); `Incorrect: The syntax for the ternary operator starts with the condition, followed by the '?' operator, the value for if condition is true, the ':' operator, and the value for if condition is false.`
-- B. result = (expression-if-condition-false ? condition : expression-if-condition-true); `Incorrect: Similar to the above explanation, the syntax starts with the condition to be evaluated.`
-- C. result = (condition ? expression-if-condition-true : expression-if-condition-false); `Correct: This is the correct syntax for the ternary operator in Java.`【81†source】
-
diff --git a/00-Quiz-Explanation/Archive/Q09-ReferenceTypes.md b/00-Quiz-Explanation/Archive/Q09-ReferenceTypes.md
deleted file mode 100644
index 8aa6bc38..00000000
--- a/00-Quiz-Explanation/Archive/Q09-ReferenceTypes.md
+++ /dev/null
@@ -1,429 +0,0 @@
-
-### Step 01: Introducing Reference Types
-
-**Question 60**
-
-What is the purpose of reference variables in Java?
-
- * A. To store primitive values `Incorrect: Reference variables are used to store references to objects, not primitive values.`
- * B. To store objects on the Heap `Incorrect: Reference variables store references (addresses), not the actual objects.`
- * C. To store the memory location of an object `Correct: Reference variables store the memory location (reference) of an object.`【60†source】
-
-**Question 61**
-
-What is the main difference between reference types and primitive types in Java?
-
- * A. Primitive types are stored on the Stack, reference types on the Heap `Correct: Primitive types are stored on the Stack and reference types are stored on the Heap.`
- * B. Primitive types are stored on the Heap, reference types on the Stack `Incorrect: This is the opposite of the actual situation.`
- * C. Both are stored on the Heap `Incorrect: Primitive types are stored on the Stack, not on the Heap.`【61†source】
-
-**Question 62**
-
-In the following code snippet, where are the objects `jupiter` and `dog` stored?
-
-```java
-class Planet { ... }
-Planet jupiter = new Planet();
-
-class Animal { ... }
-Animal dog = new Animal(12);
-```
-
- * A. Stack `Incorrect: Objects are stored on the Heap in Java.`
- * B. Heap `Correct: Objects are stored on the Heap in Java.`
- * C. Both Stack and Heap `Incorrect: In Java, the Stack is used for storing method calls and primitive types, while the Heap is used for storing objects.`【62†source】
-
-### Step 02: References: Usage And Puzzles
-
-**Question 63**
-
-What is the value of a reference variable that is not initialized by the programmer in Java?
-
- * A. 0 `Incorrect: 0 is a default value for numeric primitive types, not for reference types.`
- * B. Empty `Incorrect: Empty is not a default value for a reference variable.`
- * C. Null `Correct: If a reference variable is not initialized, its default value will be null.`【63†source】
-
-**Question 64**
-
-What happens when you compare two reference variables in Java?
-
- * A. It compares the values stored inside the referenced objects `Incorrect: By default, comparing two reference variables checks if they point to the same object, not the content of the objects.`
- * B. It compares the memory locations where the objects are stored `Correct: When you compare two reference variables, it checks whether they point to the same object, i.e., they have the same memory location.`
- * C. It compares the size of the objects `Incorrect: Java does not compare the size of the objects when comparing two reference variables.`【64†source】
-
-**Question 65**
-
-What happens when you assign one reference variable to another in Java?
-
- * A. It creates a copy of the entire referenced object `Incorrect: Assigning one reference variable to another does not copy the object, only the reference.`
- * B. It only copies the reference `Correct: When you assign one reference variable to another, it copies the reference, not the object. As a result, both variables point to the same object.`
- * C. It creates a new object with the same values as the referenced object `Incorrect: Assigning one reference variable to another does not create a new object.`【65†source】
-
-### Step 03: Introducing String Quiz
-
-**Question 66**
-
-What is a string in Java?
-
- * A. A sequence of numbers `Incorrect: In Java, a string is not a sequence of numbers.`
- * B. A sequence of characters `Correct: In Java, a string is a sequence of characters.`
- * C. A sequence of symbols `Incorrect: In Java, a string is not a sequence of symbols, it is a sequence of characters.`【66†source】
-
-**Question 67**
-
-What is the output of the following code:
-
-```java
-String str = "Test";
-System.out.println(str.charAt(2));
-```
-
- * A. 'e' `Incorrect: The character at index 2 of the string "Test" is 's', not 'e'.`
- * B. 's' `Correct: The character at index 2 of the string "Test" is 's'.`
- * C. 'T' `Incorrect: The character at index 2 of the string "Test" is 's', not 'T'.`【67†source】
-
-**Question 68**
-
-What does the substring method of the String class return?
-
- * A. A sequence of numbers `Incorrect: The substring method returns a sequence of characters, not numbers.`
- * B. A sequence of characters `Correct: The substring method returns a sequence of characters from the original string.`
- * C. A sequence of symbols `Incorrect: The substring method returns a sequence of characters, not symbols.`【68†source】
-
-### Step 04: Programming Exercise PE-01, And String Utilities
-
-**Question 102**
-
-What does the indexOf() method in the String class do?
-
- * A. Returns the position of a character in a string `Correct but not the complete answer: The indexOf() method does return the position of the first occurrence of a specified character in a string.`
- * B. Returns the starting position of a substring in a string `Correct but not the complete answer: The indexOf() method does return the position of the first occurrence of a specified substring in a string.`
- * C. Both of the above `Correct: The indexOf() method can return the position of a character or a substring in a string.`
- * D. None of the above `Incorrect: The indexOf() method does perform the functions stated in option C.`【102†source】
-
-**Question 103**
-
-How does the endsWith() method determine if a string ends with a given suffix?
-
- * A. It returns the position of the last occurrence of the suffix in the string `Incorrect: The endsWith() method does not return a position.`
- * B. It returns true if the string ends with the given suffix, false otherwise `Correct: The endsWith() method checks if a string ends with the specified suffix and returns a boolean result.`
- * C. It returns false if the string ends with the given suffix, true otherwise `Incorrect: The endsWith() method returns true if the string ends with the specified suffix, not false.`
- * D. None of the above `Incorrect: The endsWith() method does perform the function stated in option B.`【103†source】
-
-**Question 104**
-
-When using the equals() method, what is the result if the string is identical to the argument?
-
- * A. Returns true `Correct: The equals() method compares the string to the argument and returns true if they are identical.`
- * B. Returns false `Incorrect: The equals() method returns false if the strings are not identical, not if they are.`
- * C. Returns the position of the first occurrence of the argument in the string `Incorrect: The equals() method does not return a position.`
- * D. None of the above `Incorrect: The equals() method does perform the function stated in option A.`【104†source】
-
-### Step 05: String Immutability
-
-**Question 72**
-
-What is the meaning of the word "immutable"?
-
- * A. Changeable `Incorrect: "Immutable" means unchangeable.`
- * B. Unchangeable `Correct: "Immutable" means unchangeable.`
- * C. Mutable `Incorrect: "Mutable" is the opposite of "immutable". It means changeable.`【72†source】
-
-**Question 73**
-
-Can the value of a string object be changed after it is created?
-
- * A. Yes `Incorrect: String objects are immutable in Java, meaning their value cannot be changed once created.`
- * B. No `Correct: String objects are immutable in Java, meaning their value cannot be changed once created.`【73†source】
-
-**Question 74**
-
-What does the method concat() do
-
- in Java?
-
- * A. Changes the original string by appending another string `Incorrect: The concat() method does not change the original string; instead, it returns a new string.`
- * B. Returns a new string resulting from appending another string to the original string `Correct: The concat() method returns a new string that is the result of appending the specified string to the end of the original string.`
- * C. Replaces the original string with a new string `Incorrect: The concat() method does not replace the original string; it returns a new string.`【74†source】
-
-**Question 75**
-
-What is String Pool in Java?
-
- * A. A pool of methods for the String class `Incorrect: The String Pool is a pool of literal strings, not methods.`
- * B. A pool of literal strings stored in the heap memory `Correct: The String Pool in Java is a pool of literal strings stored in the heap memory.`
- * C. A pool of references to the String objects `Incorrect: The String Pool is a pool of literal strings, not references to String objects.`【75†source】
-
-
-### Step 05: String Immutability Continued
-
-**Question 76**
-
-What happens to the original string object when the method toUpperCase() is used on it?
-
- * A. The original string object is changed to upper case `Incorrect: In Java, strings are immutable. The toUpperCase() method returns a new string.`
- * B. The original string object remains unchanged, a new string object is returned with the changed value `Correct: The toUpperCase() method does not change the original string; it returns a new string.`【76†source】
-
-**Question 77**
-
-What is the output of the following code:
-
-```java
-String str = "in28Minutes";
-str = str.concat(" is awesome");
-System.out.println(str);
-```
-
- * A. "in28Minutes is awesome" `Correct: The concat() method appends the given string to the end of the original string and the result is stored in 'str'.`
- * B. "in28Minutes" `Incorrect: The concat() method appends the given string to the end of the original string.`
- * C. "in28Minutes is awesome" and "in28Minutes" `Incorrect: The System.out.println() method will print only one string - the value of 'str'.`【77†source】
-
-### Step 06: More String Utilities
-
-**Question 78**
-
-What is the result of the following code:
-
-```java
-int i = 20;
-System.out.println("Value is " + i + 20);
-```
-
- * A. Value is 40 `Incorrect: In this case, 'i + 20' will not perform integer addition because of string concatenation, and will result in '2020'.`
- * B. Value is 2020 `Correct: The "+" operator in this context is used for string concatenation, not numerical addition.`
- * C. Value is 2040 `Incorrect: The "+" operator in this context is used for string concatenation, not numerical addition.`【78†source】
-
-**Question 79**
-
-What is the result of the following code:
-
-```java
-String.join(",", "2", "3", "4");
-```
-
- * A. "2,3,4" `Correct: The join() method concatenates the given strings with a comma as a delimiter.`
- * B. "23,4" `Incorrect: The join() method concatenates all the given strings with a comma as a delimiter.`
- * C. "234" `Incorrect: The join() method concatenates the given strings with a comma as a delimiter.`【79†source】
-
-**Question 80**
-
-What is the result of the following code:
-
-```java
-"abcd".replace("ab", "xyz");
-```
-
- * A. "xyzcd" `Correct: The replace() method replaces all occurrences of the first argument with the second argument in the string.`
- * B. "xyzabcd" `Incorrect: The replace() method does not append the replacement at the start of the string.`
- * C. "abcdxyz" `Incorrect: The replace() method does not append the replacement at the end of the string.`【80†source】
-
-### Step 07: Storing mutable text
-
-**Question 81**
-
-What is the difference between StringBuffer and StringBuilder?
-
- * A. StringBuffer is mutable while StringBuilder is immutable `Incorrect: Both StringBuffer and StringBuilder are mutable.`
- * B. StringBuilder is mutable while StringBuffer is immutable `Incorrect: Both StringBuffer and StringBuilder are mutable.`
- * C. Both StringBuffer and StringBuilder are immutable `Incorrect: Both StringBuffer and StringBuilder are mutable.`【81†source】
-
-**Question 82**
-
-What is the main advantage
-
- of using StringBuilder over StringBuffer?
-
- * A. StringBuilder is thread-safe `Incorrect: StringBuffer is thread-safe, not StringBuilder.`
- * B. StringBuilder offers better performance in both execution-time and memory usage `Correct: Because StringBuilder is not thread-safe, it doesn't have the overhead of synchronization, which makes it faster and more efficient than StringBuffer.`
- * C. StringBuilder is a built-in class in Java `Incorrect: Both StringBuffer and StringBuilder are built-in classes in Java.`【82†source】
-
-**Question 83**
-
-Can we modify a string literal using StringBuffer?
-
- * A. Yes, we can modify a string literal using StringBuffer `Incorrect: String literals are immutable in Java, so they cannot be modified by StringBuffer or any other class.`
- * B. No, we cannot modify a string literal using StringBuffer `Correct: String literals are immutable in Java, so they cannot be modified.`
- * C. It depends on the situation `Incorrect: String literals are always immutable in Java, regardless of the situation.`【83†source】
-
-### Step 08: Introducing Wrapper Classes
-
-**Question 84**
-
-What is the purpose of using Wrapper Classes in Java?
-
- * A. To access type information about the corresponding primitive type `Incorrect: Wrapper classes in Java are primarily used to convert primitive data types into objects.`
- * B. To promote primitive data to an object reference type `Correct: Wrapper classes in Java are used to convert primitive data types into objects. This is often necessary because certain Java collections can only handle objects and not primitive types.`
- * C. To move primitive type data around data structures `Incorrect: While it's true that wrapper classes can help move primitive data around in object-oriented data structures, their primary purpose is to convert primitive types into objects.`【84†source】
-
-**Question 85**
-
-What is Auto-Boxing in Java?
-
- * A. The process of promoting primitive data to an object reference type `Incorrect: Auto-boxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes.`
- * B. The process of converting an object reference type to a primitive data type `Incorrect: This process is known as unboxing, not auto-boxing.`
- * C. The process of converting a primitive data type to an object reference type `Correct: Auto-boxing is the automatic conversion of primitive types to their corresponding object wrapper classes.`【85†source】
-
-**Question 86**
-
-Can we modify the value of a wrapper class once it is assigned?
-
- * A. Yes, we can modify the value of a wrapper class `Incorrect: Once a value has been assigned to a wrapper class, it cannot be changed.`
- * B. No, the value of a wrapper class is immutable `Correct: Once a value has been assigned to a wrapper class, it cannot be changed. This is because all wrapper classes in Java are immutable.`
- * C. It depends on the type of wrapper class being used. `Incorrect: All wrapper classes in Java are immutable, regardless of the type.`【86†source】
-
-### Step 09: Creating Wrapper Objects
-
-**Question 87**
-
-What are Wrapper Classes in Java?
-
- * A. Classes that provide a mechanism to convert primitive data types into objects `Correct: This is one of the main functions of wrapper classes in Java.`
- * B. Classes that provide a mechanism to convert objects into primitive data types `Correct: This is one of the main functions of wrapper classes in Java. They allow us to "unwrap" the value of an object into a primitive type through a process known as unboxing.`
- * C. Both of the above `Correct: Wrapper classes in Java both convert primitive data types
-
- into objects (known as boxing), and provide a mechanism to convert objects into primitive data types (known as unboxing).`
- * D. None of the above `Incorrect: Wrapper classes in Java serve both of the functions listed above.`【87†source】
-
-**Question 88**
-
-What is the difference between creating a Wrapper object using 'new' and 'valueOf()'?
-
- * A. There is no difference `Incorrect: There is a significant difference between these two methods.`
- * B. 'new' creates a new object every time, whereas 'valueOf()' reuses existing objects with the same value `Correct: The 'new' keyword always creates a new object, while 'valueOf()' may return a cached object for certain ranges of values (particularly small integers).`
- * C. 'new' reuses existing objects with the same value, whereas 'valueOf()' creates a new object every time `Incorrect: It is 'valueOf()' that may reuse objects, not 'new'.`
- * D. None of the above `Incorrect: The correct answer is option B.`【88†source】
-
-**Question 89**
-
-Are Wrapper Classes mutable in Java?
-
- * A. Yes `Incorrect: Wrapper classes in Java are immutable.`
- * B. No `Correct: Once a value has been assigned to a wrapper class, it cannot be changed.`
- * C. Depends on the implementation `Incorrect: All wrapper classes in Java are immutable, regardless of the implementation.`
- * D. None of the above `Incorrect: The correct answer is option B.`【89†source】
-
-### Step 10: Auto-Boxing, And Some Wrapper Constants
-
-**Question 90**
-
-What is Auto-Boxing in Java?
-
- * A. A feature that provides new functionality to the Java language `Incorrect: While it is true that auto-boxing was a new feature introduced in Java 5, it is not the definition of auto-boxing.`
- * B. A mechanism to make code more readable `Incorrect: While auto-boxing can make code more readable, that is not its primary function.`
- * C. A mechanism to upgrade a primitive data type to its corresponding object type `Correct: Auto-boxing is the automatic conversion of primitive types to their corresponding object wrapper classes.`
- * D. None of the above `Incorrect: The correct answer is option C.`【90†source】
-
-**Question 91**
-
-What is the mechanism used by Auto-Boxing in Java?
-
- * A. It uses the 'new' operator to create new objects every time `Incorrect: Auto-boxing uses the valueOf() method, not the new operator.`
- * B. It uses the 'valueOf()' method to create objects `Correct: Auto-boxing uses the valueOf() method to create an instance of the wrapper class for the corresponding primitive type.`
- * C. It uses the 'toString()' method to create objects `Incorrect: The toString() method is used to convert an object to a string, not to create new objects.`
- * D. None of the above `Incorrect: The correct answer is option B.`【91†source】
-
-**Question 92**
-
-Are there any constants available on Wrapper Classes in Java to check the size and range of values they can store?
-
- * A. No `Incorrect: Each wrapper class does indeed contain constants that represent the minimum and maximum values that can be stored.`
- * B. Yes `Correct: Each wrapper class contains constants MIN_VALUE and MAX_VALUE that represent the minimum and maximum values that can be stored in an object of that type.`
- * C. Depends on the implementation `Incorrect: All standard wrapper classes in Java contain these constants.`
- * D.
-
- None of the above `Incorrect: The correct answer is option B.`【92†source】
-
-### Step 11: The Java Date API Quiz
-
-**Question 93**
-
-What is the main purpose of the Java Date API?
-
- * a. To perform arithmetic operations on date and time objects `Incorrect: While the Java Date API does allow arithmetic operations on date and time objects, this is not its main purpose.`
- * b. To provide an interface for date and time classes `Incorrect: The Java Date API provides more than just an interface; it provides a full implementation for handling date and time.`
- * c. To provide a framework for date and time classes `Correct: The Java Date API is a framework that provides classes for handling date and time in a way that is both easier to understand and more accurate than using just the Date class.`
- * d. To provide a library for date and time classes `Incorrect: While the Java Date API can be considered a library, the most accurate description is that it is a framework.`【93†source】
-
-**Question 94**
-
-What is the main difference between LocalDate, LocalTime, and LocalDateTime?
-
- * a. They are used for different purposes `Incorrect: While these classes are used for different purposes, the key difference is what they represent.`
- * b. They are different classes in Java `Incorrect: While this is technically true, it doesn't describe the functional differences between these classes.`
- * c. They are used to represent different values for date and time `Correct: LocalDate represents a date (year, month, day), LocalTime represents a time (hour, minute, second, nanosecond), and LocalDateTime represents both a date and a time.`
- * d. They are used for different date and time formats `Incorrect: While these classes can be used to format dates and times in different ways, the key difference is what they represent.`【94†source】
-
-**Question 95**
-
-What is the difference between the LocalDate.now() and LocalDate.of() methods in the Java Date API?
-
- * a. LocalDate.now() returns the current date and time, while LocalDate.of() returns a specific date and time `Incorrect: LocalDate.now() returns the current date, not the current date and time.`
- * b. LocalDate.now() returns the current date, while LocalDate.of() returns a specific date `Correct: LocalDate.now() returns the current date, and LocalDate.of() can be used to create a LocalDate object for a specific date.`
- * c. LocalDate.now() returns the current time, while LocalDate.of() returns a specific time `Incorrect: LocalDate objects do not contain time information.`
- * d. LocalDate.now() returns a date and time object, while LocalDate.of() returns a date object `Incorrect: Both methods return LocalDate objects, which contain only date information.`【95†source】
-
-### Step 12: Playing With java.time.LocalDate Quiz
-
-**Question 96**
-
-What information can you retrieve from a LocalDate object?
-
- * a. Date information such as Day/Month/Year and related attributes `Correct: LocalDate objects contain date information and related attributes, but do not contain any time information.`
- * b. Time information such as Hour/Minute/Second and related attributes `Incorrect: LocalDate objects do not contain any time information.`
- * c. Both date and time information `Incorrect: LocalDate objects contain only date information, not time information.`
- * d. None of the above `Incorrect: The correct answer is option A.`【96†source】
-
-**Question 97**
-
-Are LocalDate, LocalTime, and LocalDateTime objects mutable?
-
- * a. Yes `Incorrect: Objects of these classes are immutable.`
- * b. No `Correct: Objects of LocalDate, LocalTime, and LocalDateTime are immutable. Once created, their
-
- state cannot be changed.`【97†source】
-
-**Question 98**
-
-What is the result of the following code snippet?
-
-```java
-LocalDate today = LocalDate.now();
-LocalDate tomorrow = today.plusDays(1);
-System.out.println(today.isBefore(tomorrow));
-```
-
- * a. True `Correct: The method `isBefore()` returns true because the date `tomorrow` is after `today`.`
- * b. False `Incorrect: The correct answer is true.`
- * c. Error `Incorrect: The code will not result in an error.`【98†source】
-
-### Step 13: Comparing LocalDate Objects Quiz
-
-**Question 99**
-
-What is the purpose of the isBefore() and isAfter() methods in the Java Date API?
-
- * a. To compare the order of two LocalDate objects `Correct: The `isBefore()` and `isAfter()` methods are used to determine if one LocalDate is before or after another, respectively.`
- * b. To determine if a LocalDate object is earlier or later than a specific date `Incorrect: While this can be a result of using these methods, it's not the purpose. Their purpose is to compare two LocalDate objects.`
- * c. To compare the value of two LocalDate objects `Incorrect: These methods do not compare the value of two LocalDate objects. They check the order of the dates.`
- * d. To determine if a LocalDate object is equal to a specific date `Incorrect: For equality checks, the `isEqual()` method should be used.`【99†source】
-
-**Question 100**
-
-What is the result of the following code snippet?
-
-```java
-LocalDate today = LocalDate.now();
-LocalDate yesterday = LocalDate.of(2018, 01, 31);
-System.out.println(today.isAfter(yesterday));
-```
-
- * a. True `Correct: Unless this code is run on January 31, 2018, `today` will be after `yesterday`, and so `isAfter()` will return true.`
- * b. False `Incorrect: Unless this code is run on January 31, 2018, the method `isAfter()` will return true.`
- * c. Error `Incorrect: The code will not result in an error.`【100†source】
-
-**Question 101**
-
-Can you compare LocalTime and LocalDateTime objects using the isBefore() and isAfter() methods?
-
- * a. Yes `Correct: The `isBefore()` and `isAfter()` methods are available in both LocalTime and LocalDateTime classes.`
- * b. No `Incorrect: The correct answer is yes.`【101†source】
\ No newline at end of file
diff --git a/00-Quiz-Explanation/Archive/Q11-ObjectOrientedProgrammingAgain.md b/00-Quiz-Explanation/Archive/Q11-ObjectOrientedProgrammingAgain.md
deleted file mode 100644
index 5aa1562f..00000000
--- a/00-Quiz-Explanation/Archive/Q11-ObjectOrientedProgrammingAgain.md
+++ /dev/null
@@ -1,285 +0,0 @@
-### Step 01: Objects Revisited - State And Behavior
-
-**Question 1: What defines an object's state?**
-
-- A. Its methods `Incorrect: Methods define the behavior of an object, not its state.`
-- B. Its behavior `Incorrect: Behavior is how an object acts, but it doesn't define its state.`
-- C. Its attributes `Correct: The state of an object is determined by its attributes or properties.`
-
-**Question 2: What delivers messages to an object?**
-
-- A. Attributes `Incorrect: Attributes don't deliver messages; they store state information.`
-- B. Methods `Correct: Methods are used to send messages to an object to perform certain actions.`
-- C. Constructors `Incorrect: Constructors are used to initialize an object, not to send messages.`
-
-**Question 3: What is the effect of behavior on an object's state?**
-
-- A. No effect `Incorrect: Behavior, defined by methods, can affect an object's state.`
-- B. Positive effect `Incorrect: The term "positive effect" is not precise in this context.`
-- C. Negative effect `Incorrect: The term "negative effect" is not precise in this context.`
-
-### Step 02: Managing class state
-
-**Question 1: What corresponds to the state of a class?**
-
-- A. Member variables `Correct: Member variables hold the state of an object of a class.`
-- B. Methods `Incorrect: Methods define the behavior of the objects, not their state.`
-- C. Constructors `Incorrect: Constructors are used to initialize an object, not to define its state.`
-
-**Question 2: What is the purpose of constructors in a class?**
-
-- A. To define behavior `Incorrect: Constructors are used to initialize an object, not to define its behavior.`
-- B. To create objects `Correct: Constructors are used to create and initialize objects of a class.`
-- C. To set attributes `Incorrect: Although constructors can be used to set attribute values, their primary purpose is to create objects.`
-
-**Question 3: What is the purpose of the toString() method in a class?**
-
-- A. To define behavior `Incorrect: The toString() method does not define behavior.`
-- B. To create objects `Incorrect: The toString() method is used to provide a String representation of an object, not to create objects.`
-- C. To provide a string representation of the object's state `Correct: The toString() method provides a string representation of an object's state.`
-
-### Step 03: Augmenting Fan With Behavior
-
-**Question 1: What is the state attribute that needs to be exposed to change by Fan object users?**
-
-- A. make `Incorrect: "make" is not typically changed by users.`
-- B. color `Incorrect: "color" is not typically changed by users.`
-- C. isOn `Correct: Users need to be able to change whether the fan is on or off.`
-- D. speed `Correct: Users need to be able to change the speed of the fan.`
-
-**Question 2: What is the purpose of the switchOn() and switchOff() methods in the Fan class?**
-
-- A. To toggle the isOn state attribute `Correct: These methods are used to change the "isOn" state attribute of a Fan object.`
-- B. To toggle the speed state attribute `Incorrect: These methods don't directly change the speed state attribute.`
-- C. To create a new Fan object `Incorrect: These methods are used to modify the state of an existing Fan object, not to create a new one.`
-
-**Question 3: What is the
-
- purpose of the setSpeed() method in the Fan class?**
-
-- A. To toggle the isOn state attribute `Incorrect: This method doesn't change the "isOn" state attribute.`
-- B. To toggle the speed state attribute `Correct: This method is used to set the speed of the Fan.`
-- C. To create a new Fan object `Incorrect: This method is used to modify the state of an existing Fan object, not to create a new one.`
-
-
-**Step 04: Programming Exercise PE-OOP-01**
-
-**Question 1: What are the state attributes of a Rectangle object?**
-- A. Length and width `Correct: A rectangle is defined by its length and width.`
-- B. Height and width `Incorrect: Height is not typically a characteristic used to define a rectangle.`
-- C. Length and breadth `Incorrect: The term "breadth" is less commonly used to describe a rectangle's dimensions.`
-
-**Question 2: What is the purpose of the area() method in the Rectangle class?**
-- A. To calculate the perimeter of the rectangle `Incorrect: The area() method calculates the area, not the perimeter.`
-- B. To calculate the area of the rectangle `Correct: The area() method calculates the area of a rectangle.`
-- C. To set the length of the rectangle `Incorrect: The area() method doesn't set any attribute; it calculates a value.`
-
-**Question 3: What is the purpose of the perimeter() method in the Rectangle class?**
-- A. To calculate the perimeter of the rectangle `Correct: The perimeter() method calculates the perimeter of a rectangle.`
-- B. To calculate the area of the rectangle `Incorrect: The perimeter() method calculates the perimeter, not the area.`
-- C. To set the length of the rectangle `Incorrect: The perimeter() method doesn't set any attribute; it calculates a value.`
-
-**Step 06: Understanding Object Composition**
-
-**Question 1: What are the state attributes of the Fan class?**
-- A) make, radius, color, isOn, speed `Correct: These are the attributes that define the state of a Fan object.`
-- B) brand, diameter, hue, isRunning, velocity `Incorrect: These attributes may define similar features, but the specific names differ from those in the Fan class.`
-- C) manufacturer, size, tone, isActive, rate `Incorrect: These attributes may define similar features, but the specific names differ from those in the Fan class.`
-
-**Question 2: What is object composition?**
-- A) Combining primitive types into a complex object `Incorrect: While this is a form of composition, it's not specific to object composition in OOP.`
-- B) Creating multiple objects of the same type `Incorrect: This doesn't define object composition.`
-- C) Combining different objects to create a more complex object `Correct: Object composition involves using different objects to build more complex ones.`
-
-**Question 3: What is the purpose of constructors in object composition?**
-- A) To create new objects of a class `Correct: Constructors are used to create and initialize new objects.`
-- B) To modify the state of an object `Incorrect: Constructors initialize an object's state, not modify it after creation.`
-- C) To add behaviors to an object `Incorrect: While constructors can assign methods, their main purpose is to create and initialize new objects.`
-
-**Step 07: Programming Exercise PE-OOP-02**
-
-**Question 1: What are the attributes of the Book class?**
-- A) Id, Name, Author `Correct: These are the attributes that define the state of a Book object.`
-- B) Title, Author, Description `Incorrect: While these could be valid attributes for a Book, they do not match the provided Book class structure.`
-- C) Id, Title, Author `Incorrect: While these could be valid attributes for a Book, they do not match the provided Book class structure.`
-
-**Question 2: What is the purpose of the Review class?**
-- A) To manage Books `Incorrect: The Review class is meant to manage reviews, not
-
- books.`
-- B) To manage Authors `Incorrect: The Review class is meant to manage reviews, not authors.`
-- C) To manage reviews associated with a Book `Correct: The Review class is used to manage and associate reviews with a Book.`
-
-**Question 3: What is the output of the following code?**
-
-```java
-Book book = new Book(123, "Object Oriented Programming With Java", "Ranga");
-book.addReview(new Review(10, "Great Book", 4));
-book.addReview(new Review(101, "Awesome", 5));
-System.out.println(book);
-```
-
-- A) Book-123, Object Oriented Programming With Java, Ranga, [(Review-10, Great Book", 4), (Review-101, Awesome, 5)] `Correct: This is the expected output based on the provided code.`
-- B) Book-123, Object Oriented Programming With Java, Ranga, [(10, Great Book, 4), (101, Awesome, 5)] `Incorrect: The output format includes the word "Review-" before the review IDs.`
-- C) Book-123, Object Oriented Programming With Java, Ranga, [(Review-10, Great Book", 5), (Review-101, Awesome, 4)] `Incorrect: The review ratings do not match those given in the code.`
-
-**Step 07: The Need For Inheritance**
-
-**Question 1: What is Inheritance in Object Oriented Programming?**
-- A) A mechanism of code reuse `Correct: Inheritance allows the reuse of code from one class in another.`
-- B) A mechanism to create new objects `Incorrect: While inheritance can be part of creating new objects, it primarily refers to code reuse between classes.`
-- C) A mechanism to modify existing objects `Incorrect: Inheritance involves classes and their relationships, not modifying existing objects.`
-
-**Question 2: What is a superclass in Inheritance relationship?**
-- A) A class that extends another class `Incorrect: A superclass is the class that gets extended, not the one that does the extending.`
-- B) A class that inherits from another class `Incorrect: A superclass is the class that is inherited from, not the class that does the inheriting.`
-- C) A class that is neither extended nor inherited `Incorrect: In the context of inheritance, a superclass is a class that is inherited from.`
-
-**Question 3: How does a subclass access fields and methods of its superclass?**
-- A) By using the keyword 'super' `Correct: In Java, the 'super' keyword is used to refer to the superclass of the current object.`
-- B) By using the keyword 'this' `Incorrect: The 'this' keyword refers to the current object, not its superclass.`
-- C) By using the keyword 'extends' `Incorrect: The 'extends' keyword is used to establish an inheritance relationship, not to access superclass members.`
-
-**Step 12: Constructors, And Calling super()**
-
-**Question 1: What does the super keyword do in Java?**
-- a. Allows a subclass to access the attributes present in the superclass `Correct: The super keyword in Java is used to refer to the immediate parent class instance variable.`
-- b. Creates a new instance of a superclass `Incorrect: The super keyword does not create new instances; it refers to the superclass.`
-- c. Allows a superclass to access the attributes present in the subclass `Incorrect: The super keyword is used in the context of a subclass referring to its superclass, not the other way around.`
-
-**Step 13: Multiple Inheritance, Reference Variables And instanceof**
-
-**Question 1: Can a Java class directly inherit from two or more classes?**
-- a. Yes `Incorrect: Java doesn't support multiple inheritance directly due to the "Diamond Problem".`
-- b. No `Correct: A class in Java can directly inherit from only one class.`
-
-**Question 2: What is the output of the Dog object's toString() method in Snippet-02?**
-- a. Dog@23a6e47f `Correct: If not overridden, the toString() method returns the class name followed by the "@" sign and the unsigned hexadecimal representation of the hash code of the object.`
-- b. Pet Groom `Incorrect: The output of toString() wouldn't be a string literal unless explicitly defined in the Dog class.`
-- c. null `Incorrect: The toString() method will not return null unless explicitly defined to do so.`
-
-**Question 3: What is the output of the instanceof operator when pet instanceof String is executed in Snippet-02?**
-- a. Pet cannot be converted to java.lang.String `Correct: The 'instanceof' operator in Java is used to test whether an object is an instance of a specific class or not. In this case, 'pet' is not a String.`
-- b. true `Incorrect: The pet is not an instance of String.`
-- c. false `Incorrect: It throws a compile-time error because 'pet' can't be compared with 'String'.`
-
-**Step 14: Introducing Abstract Classes**
-
-**Question 1: What is an abstract method?**
-- A) A method without any parameters `Incorrect: Abstract methods are defined by lack of implementation, not lack of parameters.`
-- B) A method with a method definition `Incorrect: Abstract methods lack a method definition.`
-- C) A method without a method definition `Correct: Abstract methods in Java are declared without a body.`
-
-**Question 2: Can an abstract class be instantiated?**
-- A) Yes `Incorrect: Abstract classes in Java cannot be instantiated.`
-- B) No `Correct: Abstract classes can't be instantiated directly; they can only be subclassed.`
-
-**Question 3: What is a concrete class?**
-- A) A class that can be instantiated `Correct: A concrete class is a class that can be instantiated.`
-- B) A class that cannot be instantiated `Incorrect: A concrete class, unlike an abstract class, can be instantiated.`
-- C) A class with a method definition `Incorrect: While a concrete class does have defined methods, it's primarily characterized by its ability to be instantiated.`
-
-**Step 15: Abstract Classes - Design Aspects**
-
-**Question 1: What is the purpose of an abstract class?**
-- A) To provide implementation for all its methods `Incorrect: Abstract classes don't provide full implementation; they contain one or more abstract methods.`
-- B) To declare methods without providing implementation `Correct: Abstract classes declare methods without providing their implementation.`
-- C) To create a hierarchy of classes `Incorrect: While abstract classes do play a role in class hierarchies, their primary purpose is to declare methods without providing implementation.`
-
-**Question 2: What is the advantage of using an abstract class to create a recipe hierarchy?**
-- A) It allows for the order of steps to be defined `Incorrect: The order of steps is not inherently defined by using an abstract class.`
-- B) It allows for the implementation of each step to be defined by the sub-classes `Correct: Abstract classes allow subclasses to provide specific implementations of abstract methods.`
-- C) It allows for the creation of multiple
-
- recipe types easily `Incorrect: While it might be true, the main advantage is in the encapsulation of a general process structure while enabling specific step implementations.`
-
-**Question 3: Which design pattern is used in the recipe hierarchy example?**
-- A) Observer pattern `Incorrect: The observer pattern is a design pattern where an object maintains a list of dependents and notifies them of any changes. It's not used here.`
-- B) Decorator pattern `Incorrect: The decorator pattern allows behavior to be added to an individual object, either statically or dynamically, without affecting the behavior of other objects from the same class. It's not used here.`
-- C) Template method pattern `Correct: The template method pattern is a behavioral design pattern that defines the program skeleton in an operation but defers some steps to subclasses.`
-
-**Step 16: Abstract Classes - Puzzles**
-
-**Question 1: Can an abstract class be created without any abstract member methods?**
-- A) Yes `Correct: Abstract classes can exist without abstract methods. They can't be instantiated, but they can include actual method implementations.`
-- B) No `Incorrect: It's not required for an abstract class to have abstract methods, although it's common.`
-
-**Question 2: Can an abstract class have member variables?**
-- A) Yes `Correct: Abstract classes can have member variables like any other classes.`
-- B) No `Incorrect: Abstract classes, like any other class, can have member variables.`
-
-**Question 3: Can an abstract class have non-abstract methods?**
-- A) Yes `Correct: Abstract classes can have both abstract and non-abstract methods.`
-- B) No `Incorrect: Abstract classes can include fully implemented (non-abstract) methods.`
-
-**Step 17: Introducing Interfaces**
-
-**Question 1: What is an interface in Java?**
-- A) A class that provides implementation for all its methods `Incorrect: Interfaces do not provide implementation for any methods, only their signatures.`
-- B) A class that declares methods without providing implementation `Incorrect: While interfaces do declare methods without implementation, they are not classes.`
-- C) A class that cannot be instantiated but can be implemented by other classes `Correct: An interface can't be instantiated, but other classes can implement it to define the methods.`
-
-**Question 2: Who provides the implementation of methods declared in an interface?**
-- A) The interface itself `Incorrect: Interfaces in Java do not provide implementation for methods.`
-- B) The implementing classes `Correct: The classes implementing the interface provide the method implementation.`
-- C) The superclass of the interface `Incorrect: Interfaces do not have superclasses. Method implementation is provided by the classes implementing the interface.`
-
-**Question 3: How can an interface be used to enforce a contract for its implementors?**
-- A) By providing default implementations for its methods `Incorrect: While interfaces can provide default methods, the primary means of enforcing a contract is by declaring methods without providing implementation.`
-- B) By declaring methods without providing implementation `Correct: Interfaces enforce a contract by declaring methods without providing implementation. The implementing classes are obliged to provide the implementation.`
-- C) By creating a hierarchy of interfaces `Incorrect: While interfaces can inherit from other interfaces, the primary way they enforce a contract is by declaring methods without implementation.`
-
-**Step 18: Using Interfaces To Design APIs**
-
-**Question 1: Which of the following is not a way to ensure compatibility between teams working on different parts of an application?**
-- a) Define an interface for the external team to implement `Incorrect: Defining interfaces is indeed a good way to ensure compatibility, as it sets the expectations for method signatures
-
-.`
-- b) Work on the parts of the application simultaneously `Incorrect: Working simultaneously doesn't inherently ensure compatibility; clear contracts and communication do.`
-- c) Define an algorithm for the external team to implement directly into the application `Correct: This approach does not ensure compatibility as it lacks a defined contract for how components should interact.`
-
-**Question 2: What is the purpose of defining an interface between two teams working on different parts of an application?**
-- a) To allow teams to work independently without worrying about compatibility issues `Incorrect: While interfaces allow teams to work independently, they primarily serve to define a contract between the two teams.`
-- b) To define a contract between the two teams `Correct: Interfaces provide a defined contract of methods, which facilitates the independent work of different teams on separate components.`
-- c) To ensure that both teams use the same programming language `Incorrect: An interface doesn't enforce the use of a specific programming language, it's about defining the methods that classes implementing it should have.`
-
-**Question 3: Which of the following is an implementation of the ComplexAlgorithm interface?**
-- a) OneComplexAlgorithm `Incorrect: Without more context, we can't confirm if "OneComplexAlgorithm" is an implementation of the ComplexAlgorithm interface.`
-- b) ActualComplexAlgorithm `Incorrect: Without more context, we can't confirm if "ActualComplexAlgorithm" is an implementation of the ComplexAlgorithm interface.`
-- c) Both a and b `Correct: Assuming that both "OneComplexAlgorithm" and "ActualComplexAlgorithm" implement the ComplexAlgorithm interface.`
-
-**Step 19: Interfaces - Puzzles And Interesting Facts**
-
-**Question 1: Which of the following is true about interfaces in Java?**
-- a) An interface can be extended by another interface `Correct: Interfaces can extend one or more other interfaces.`
-- b) An implementation of an interface needs to implement all methods declared in the interface and its super interfaces `Incorrect: While an implementation class generally needs to implement all methods of an interface, if the class is abstract, it doesn't have to implement all methods.`
-- c) Interfaces can have member variables `Incorrect: Interfaces can have constants (static final variables) but not regular member variables.`
-
-**Question 2: Which of the following is not a way to provide a default implementation for a method in an interface?**
-- a) Include the keyword "default" in the method signature `Incorrect: This is indeed one way to provide a default method in an interface.`
-- b) Provide a body for the method in the interface definition `Incorrect: This is another way to provide a default method in an interface.`
-- c) Override the method in the implementation class `Correct: Overriding the method in the implementation class is not providing a default implementation. It's providing a class-specific implementation.`
-
-**Question 3: Why is providing default method implementations useful in building and extending frameworks?**
-- a) It allows for a new method to be added to an interface without breaking the implementation classes `Correct: Default methods enable new functionality to be added to the interfaces of libraries and ensure binary compatibility with code written for older versions of those interfaces.`
-- b) It ensures that all implementation classes have the same behavior for the default method `Incorrect: While this might happen, the main purpose is to allow extension without breaking existing implementations.`
-- c) It reduces the amount of code needed to implement the interface `Incorrect: The amount of code is not necessarily reduced as the default method can still be overridden.`
-
-**Step 20: abstract class And interface : A Comparison**
-
-**Question 1: Which of the following is a primary use case for an interface?**
-- a) Generalizing behavior by
-
- defining a set of methods that a class must implement `Correct: This is indeed a primary use case for interfaces.`
-- b) Providing default implementations for methods `Incorrect: While interfaces can provide default method implementations, it's not their primary use case.`
-- c) Defining member variables `Incorrect: Interfaces in Java can't define member variables (only constants).`
-
-**Question 2: Which of the following is a primary use case for an abstract class?**
-- a) Providing partial implementation for a class `Correct: This is a primary use case for abstract classes. They allow for the definition of both abstract and non-abstract methods.`
-- b) Defining a contract for methods that a class must implement `Incorrect: This is a primary use case for interfaces, not abstract classes.`
-- c) Extending multiple classes `Incorrect: In Java, a class (including abstract class) can't extend multiple classes directly.`
-
-**Question 3: Which of the following can be instantiated?**
-- a) An interface `Incorrect: Interfaces cannot be instantiated.`
-- b) An abstract class `Incorrect: Abstract classes cannot be instantiated.`
-- c) A concrete class `Correct: A concrete class, unlike interfaces or abstract classes, can be instantiated.`
\ No newline at end of file
From a65c107b4e11aaa854a9b556afe0a394b2fe6edd Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sun, 21 May 2023 13:31:33 +0530
Subject: [PATCH 159/178] .
---
...troductionToMethods-MultiplicationTable.md | 251 ++++++++++
...-IntroductionToObjectOrientedProgrammin.md | 259 +++++++++++
.../Q06-PrimitiveDataTypesAndAlternatives.md | 331 ++++++++++++++
00-Quiz-Explanation/Q07-Conditionals.md | 381 ++++++++++++++++
00-Quiz-Explanation/Q09-ReferenceTypes.md | 429 ++++++++++++++++++
.../Q11-ObjectOrientedProgrammingAgain.md | 285 ++++++++++++
6 files changed, 1936 insertions(+)
create mode 100644 00-Quiz-Explanation/Q02-IntroductionToMethods-MultiplicationTable.md
create mode 100644 00-Quiz-Explanation/Q05-IntroductionToObjectOrientedProgrammin.md
create mode 100644 00-Quiz-Explanation/Q06-PrimitiveDataTypesAndAlternatives.md
create mode 100644 00-Quiz-Explanation/Q07-Conditionals.md
create mode 100644 00-Quiz-Explanation/Q09-ReferenceTypes.md
create mode 100644 00-Quiz-Explanation/Q11-ObjectOrientedProgrammingAgain.md
diff --git a/00-Quiz-Explanation/Q02-IntroductionToMethods-MultiplicationTable.md b/00-Quiz-Explanation/Q02-IntroductionToMethods-MultiplicationTable.md
new file mode 100644
index 00000000..fc25ab5c
--- /dev/null
+++ b/00-Quiz-Explanation/Q02-IntroductionToMethods-MultiplicationTable.md
@@ -0,0 +1,251 @@
+### Question 1
+
+
+
+What does the `void` keyword indicate in a method definition?
+
+
+
+* A) The method returns an integer value. `Incorrect: void` means no return type, not integer.
+
+* B) The method does not return any value. `Correct: void` means the method does not return any value.
+
+* C) The method returns a boolean value. `Incorrect: void` means no return type, not boolean【5†source】.
+
+
+
+### Question 2
+
+
+
+What is the correct way to call a method named `sayHelloWorldTwice`?
+
+
+
+* A) sayHelloWorldTwice. `Incorrect: Method calls in Java require parentheses, even if no arguments are being passed`.
+
+* B) sayHelloWorldTwice(). `Correct: This is the correct syntax to call a method in Java`.
+
+* C) sayHelloWorldTwice(); `Incorrect: While this is valid in a statement context, it's not the correct way to just refer to a method call`【6†source】.
+
+
+
+### Question 3
+
+
+
+Which of the following statements is true about method definitions and method calls?
+
+
+
+* A) Defining a method automatically executes its statement body. `Incorrect: Defining a method does not execute its body`.
+
+* B) Defining a method and invoking it are the same thing. `Incorrect: Defining a method is different from invoking it`.
+
+* C) Defining and invoking methods are two different steps. `Correct: In Java, a method must first be defined and then invoked for the code in the method to execute`【7†source】.
+
+
+
+### Question 4
+
+
+
+What is the correct syntax for defining a method that prints "Hello World"?
+
+
+
+* A) void printHelloWorld() { System.out.println("Hello World"); }. `Correct: This is the correct syntax for defining a method in Java`.
+
+* B) printHelloWorld() { System.out.println("Hello World"); }. `Incorrect: Java methods require a return type, in this case, 'void' is missing`.
+
+* C) void printHelloWorld { System.out.println("Hello World"); }. `Incorrect: Parentheses are required after the method name to indicate it's a method`【8†source】.
+
+
+
+### Question 5
+
+
+
+Which of these method names follows the same naming rules as variable names?
+
+
+
+* A) 1stMethod. `Incorrect: Variable names cannot start with a number`.
+
+* B) method_one. `Correct: This follows the Java naming rules, can contain alphanumeric characters and underscores, and cannot start with a number`.
+
+* C) first-Method. `Incorrect: Hyphens are not allowed in Java method names`【9†source】.
+
+
+
+### Question 6
+
+
+
+Which command lists the methods defined in the current JShell session?
+
+
+
+* A) /methods. `Correct: This command lists the methods defined in the current JShell session`.
+
+* B) /list. `Incorrect: This command lists the statements entered during the current JShell session`.
+
+* C) /edit. `Incorrect: This command opens a method definition in a separate editor window`【10†source】.
+
+
+
+### Question 7
+
+
+
+What does the /edit command do in JShell?
+
+
+
+* A) Lists the code of the specified method. `Incorrect: This is not the function of the /edit command`.
+
+* B) Allows you to modify the method definition in a separate editor window. `Correct: The /edit command opens the definition of a method in a separate editor window for modification`.
+
+* C) Saves the session method definitions to a file. ``Incorrect: This is the functionality of the /save command, not /edit`【11†source】.
+
+
+
+### Question 8
+
+
+
+What is the correct syntax for defining a method with an argument?
+
+
+
+* A) void methodName(ArgType argName) { method-body }. `Correct: This is the correct syntax to define a method with arguments in Java`.
+
+* B) methodName(ArgType argName) { method-body }. `Incorrect: Java methods require a return type`.
+
+* C) methodName(ArgType argName) { method-body; }. `Incorrect: The semicolon at the end is not necessary and the return type is missing`【12†source】.
+
+
+
+### Question 9
+
+
+
+Which method definition correctly prints all integers from 1 to n (inclusive), where n is an argument?
+
+
+
+* A)
+
+
+
+void printNumbers(int n) {
+
+for (int i = 1; i <= n; i++) {
+
+System.out.println(i);
+
+}
+
+}
+
+`Correct: This method correctly prints all integers from 1 to n`【13†source】.
+
+
+
+### Question 10
+
+
+
+What would happen if you try to call the method `sayHelloWorld` with a string argument, when the method is defined to accept an integer argument?
+
+
+
+* A) The program will compile and run without any errors. `Incorrect: The method call will fail to compile due to incompatible types`.
+
+* B) The program will throw a runtime error. `Incorrect: The error will occur at compile time, not runtime`.
+
+* C) The program will fail to compile due to incompatible types. `Correct: Java is statically-typed, meaning the type of each variable and expression is checked at compile time`【14†source】.
+
+
+
+
+``### Question 11
+
+What is method overloading in Java?
+
+ * A) The ability to have multiple methods with the same name in a class, but with different types of arguments. `Correct: Method overloading allows multiple methods with the same name but different parameter lists in a class`.
+ * B) The ability to have multiple methods with the same name and the same types of arguments in a class. `Incorrect: Methods with the same name and argument types are considered duplicates and will result in a compilation error`.
+ * C) The ability to have a single method with an arbitrary number of arguments. `Incorrect: This describes varargs, not method overloading`【16†source】.
+
+### Question 12
+
+Consider the following two method definitions:
+
+```java
+void printName(String firstName, String lastName) {
+ System.out.println(firstName + " " + lastName);
+}
+
+void printName(String firstName, String middleName, String lastName) {
+ System.out.println(firstName + " " + middleName + " " + lastName);
+}
+```
+
+Which of the following statements are true?
+
+- A) The two methods are overloaded methods. `Correct: These methods have the same name but different parameters, which is a feature of method overloading`.
+- B) The two methods have the same name and different number of arguments. `Correct: These methods indeed have the same name but different number of arguments`.
+- C) The two methods have the same name and the same types of arguments. `Incorrect: While they have the same types of arguments, the number of arguments is different, so this statement is false`【17†source】.
+
+### Question 13
+
+What will the following code snippet output?
+
+```
+void sum(int a, int b) {
+ System.out.println(a + b);
+}
+
+void sum(int a, int b, int c) {
+ System.out.println(a + b + c);
+}
+
+sum(1, 2);
+sum(1, 2, 3);
+```
+
+- A) The output will be 3 6. `Correct: The first call to sum uses the two-parameter version, while the second call uses the three-parameter version`.
+- B) The output will be 3 5. `Incorrect: The second call to sum(1,2,3) would yield 6, not 5`.
+- C) The code will not compile due to method overloading. `Incorrect: Method overloading is a valid concept in Java, and this code would compile and run correctly`【18†source】.
+
+### Question 14
+
+Which of the following statements is true about methods with multiple arguments in Java?
+
+- A) A method can only accept up to 2 arguments. `Incorrect: A method in Java can accept any number of arguments`.
+- B) A method can accept any number of arguments, but they must be of the same type. `Incorrect: A method can accept arguments of different types`.
+- C) A method can accept any number of arguments, and they can be of different types. `Correct: In Java, a method can accept any number of arguments, and these arguments can be of different types`【19†source】.
+
+### Question 15
+
+What is the main purpose of method overloading in Java?
+
+- A) To reduce code duplication by allowing methods with the same name but different arguments. `Correct: One of the benefits of method overloading is that it allows the same method name to be used with different parameters`.
+- B) To allow a method to return different types of values based on the input arguments. `Incorrect: Method overloading does not affect the return type of a method`.
+- C) To create multiple methods with the same name and the same number of arguments, but with different implementation. `Incorrect: The methods would need to have different parameter lists to be considered overloaded`【20†source】.
+
+### Question 16
+
+What is the purpose of a return statement in a method?
+
+- A) To end the execution of the method. `Incorrect: While a return statement does end the execution of a method, its main purpose is to return the result of a computation to the calling code`.
+- B) To return the result of a computation to the calling code. `Correct: The primary purpose of the return statement in a method is to return the result of a computation to the calling code`.
+- C) To print the output of the method. `Incorrect: Printing the output is the job of the System.out.println() method, not the return statement`【21†source】.
+
+### Question 17
+
+What is the benefit of using a return mechanism in a method?
+
+- A) It allows the method to print the result of the computation. `Incorrect: Printing is not the job of the return statement, rather it returns the result to the calling code`.
+- B) It enables sharing computed results with other code and methods, and improves breaking down a problem into sub-problems. `Correct: The return mechanism enables the reuse of computed results in other parts of the code`.
+- C) It simplifies the syntax of the method. `Incorrect: While the use of return can make a method more readable, it does not necessarily simplify the syntax`【22†source】.
\ No newline at end of file
diff --git a/00-Quiz-Explanation/Q05-IntroductionToObjectOrientedProgrammin.md b/00-Quiz-Explanation/Q05-IntroductionToObjectOrientedProgrammin.md
new file mode 100644
index 00000000..9ffbdae8
--- /dev/null
+++ b/00-Quiz-Explanation/Q05-IntroductionToObjectOrientedProgrammin.md
@@ -0,0 +1,259 @@
+### Question 1
+
+What is a class in Object Oriented Programming?
+
+ * A) An instance of an object. `Incorrect: An instance of a class is an object, not the class itself`.
+ * B) A template for creating objects. `Correct: A class in Object Oriented Programming is a blueprint or template for creating objects`.
+ * C) A function to perform actions. `Incorrect: Functions (methods in Java) can be part of a class, but they are not the definition of a class`【23†source】.
+
+### Question 2
+
+What are the two main components of an object in Object Oriented Programming?
+
+ * A) State and Behavior. `Correct: An object in Object Oriented Programming consists of state (represented by attributes or properties) and behavior (represented by methods)`.
+ * B) Template and Instance. `Incorrect: These terms relate to the concept of classes and objects, but they are not the components of an object`.
+ * C) Functions and Variables. `Incorrect: While objects can contain variables (fields) and functions (methods), in the context of Object-Oriented Programming they are usually referred to as state (fields) and behavior (methods)`【24†source】.
+
+### Question 3
+
+Which of the following methods in a class sets the title attribute?
+
+ * A) setTitle(String bookTitle). `Correct: This method follows the common naming convention for a setter method, which is used to set the value of a field`.
+ * B) getTitle(). `Incorrect: This method is typically a getter method, used to retrieve the value of a field, not to set it`.
+ * C) setBook(String title). `Incorrect: While the method name implies it could set some information related to a book, it's not clear that it sets the title`【25†source】.
+
+### Question 4
+
+In a class representing a vehicle, what is the purpose of the this keyword when used within a method?
+
+ * A) To access a static variable. `Incorrect: The this keyword is used to refer to the current instance of a class, not to access static variables`.
+ * B) To differentiate between a member variable and a method argument with the same name. `Correct: The this keyword is often used in this context to avoid confusion or name clashes between a field (member variable) and a parameter`.
+ * C) To call a method within the same class. `Incorrect: While this can be used to call a method within the same class, its primary function is to reference the current object instance`【26†source】.
+
+### Question 5
+
+What is the primary purpose of using access modifiers such as public and private in Object-Oriented Programming?
+
+ * A) To make code more readable. `Incorrect: While good use of access modifiers can make code more readable by clearly indicating which parts of the code are intended for external access, this is not their primary purpose`.
+ * B) To control what external objects can access within a given object. `Correct: Access modifiers are primarily used to control the level of access other objects have to an object's fields and methods`.
+ * C) To define the scope of a variable. `Incorrect: Access modifiers do influence scope, but their primary function is to control access, not to define scope`【27†source】.
+
+### Question 6
+
+What is the purpose of private keyword in Java?
+
+ * A) To make a variable or method accessible only within the class. `Correct: The private access modifier restricts access to the field or method to the class in which it is declared`.
+ * B) To make a variable or method accessible outside the class. `Incorrect: The private keyword makes a variable or method less accessible, not more. A public keyword would make a variable or method accessible outside the class`.
+ * C) To make a variable or method static. `Incorrect: The keyword for making a variable or method static is static, not private`【28†source】.
+
+### Question 7
+
+What are the methods used to access and modify private member variables in a class?
+
+ * A) Public methods. `Incorrect: While technically correct, since getter and setter methods are usually public, this is too broad of a term`.
+ * B) Getter and Setter methods. `Correct: Getter and Setter methods are specifically used to access and modify private member variables in a class`.
+ * C) Static methods. `Incorrect: While static methods can access and modify static variables, they are not typically used to access and modify instance variables`【29†source】.
+
+### Question 8
+
+What is the main principle that is violated when an object directly accesses the state of another object without using any methods?
+
+ * A) Inheritance. `Incorrect: Inheritance is a principle that allows a class to inherit fields and methods from another class. It is not related to the direct access of another object's state`.
+ * B) Encapsulation. `Correct: Encapsulation is the principle that an object's state should be accessed and modified through its methods, not directly`.
+ * C) Polymorphism. `Incorrect: Polymorphism is a principle that allows a method to behave differently depending on the object that it is acting upon. It is not related to the direct access of another object's state`【30†source】.
+
+### Question 9
+
+In a Java class, what is the purpose of a getter method?
+
+ * A) To modify the value of a private member variable. `Incorrect: A getter method is used to access or retrieve the value of a private member variable, not to modify it`.
+ * B) To access the value of a private member variable. `Correct: A getter method's purpose is to access or retrieve the value of a private member variable`.
+ * C) To perform a calculation with a private member variable. `Incorrect: While a getter method might be used as part of a calculation, its primary purpose is to retrieve the value of a variable, not to perform calculations`【31†source】.
+
+### Question 10
+
+Which of the following best describes the concept of state in Object-Oriented Programming?
+
+ * A) The condition of an object at a given time, represented by member variables. `Correct: In Object-Oriented Programming, the state of an object is the data it contains at any given moment, represented by its member variables`.
+ * B) The actions an object can perform, represented by methods. `Incorrect: This describes behavior, not state`.
+ * C) The relationship between two objects. `Incorrect: While relationships between objects are a significant aspect of OOP, they don't define the state of an individual object`【32†source】.
+
+### Question 11
+
+What is the primary reason for using a getter method in a Java class?
+
+ * A) To ensure that an object's member variables are accessed according to the encapsulation principle. `Correct: Getter methods are used to provide access to an object's data while still maintaining the principles of encapsulation`.
+ * B) To define a new method that performs a calculation with an object's member variables. `Incorrect: While a getter method can be used as part of a calculation, that's not the primary reason to use one`.
+ * C) To initialize an object's member variables with default values. `Incorrect: Initialization of member variables is usually done in constructors or with direct assignment, not with getter methods`【33†source】.
+
+### Question 12
+
+Which of the following correctly defines a getter method for a private member variable name in a Java class?
+
+ * A) `Correct: This is the conventional way to define a getter method in Java. It's public, has a return type matching the variable type, and returns the private variable`.
+
+```java
+public String getName() {
+ return name;
+}
+```
+- B) `Incorrect: This seems to be a setter method rather than a getter method, as it takes a parameter and assigns it to the variable`.
+
+```java
+public void getName(String newName) {
+ name = newName;
+}
+```
+
+- C) `Incorrect: This method signature includes a parameter, which is unusual for a getter method. Additionally, it might create confusion between the method parameter and the class field`.
+
+```java
+public String getName(String name) {
+ return this.name;
+}
+```
+
+【34†source】.
+
+### Question 13
+
+What is the primary purpose of a getter method?
+
+- A) To modify the value of an object's private member variable. `Incorrect: Getter methods are used to access or return the value of a private member variable, not to modify it`.
+- B) To allow controlled access to an object's private member variable. `Correct: The primary purpose of a getter method is to provide controlled access to an object's private member variable`.
+- C) To set a default value for an object's private member variable. `Incorrect: Default values for an object's private member variables are usually set in a constructor or at the time of variable declaration, not in a getter method`【35†source】.
+
+### Question 14
+
+Consider the following code snippet. What will be the output?
+
+```java
+public class MotorBike {
+ private int speed;
+
+ public int getSpeed() {
+ return speed;
+ }
+}
+
+public class MotorBikeRunner {
+ public static void main(String[] args) {
+ MotorBike bike = new MotorBike();
+ System.out.println("Current Bike Speed is : " + bike.getSpeed());
+ }
+}
+```
+
+- A) The code will not compile because the speed variable is not initialized. `Incorrect: In Java, instance variables are automatically initialized to a default value if not explicitly initialized. For integer variables, this default value is 0`.
+- B) The output will be: Current Bike Speed is : 0. `Correct: Since the speed variable is not explicitly initialized, its value is set to the default value of 0`.
+- C) The output will be: Current Bike Speed is : null. `Incorrect: Null is the default value for object references and not for primitive types like int`【36†source】.
+
+### Question 15
+
+What are the default values for object member variables when they are not explicitly initialized?
+
+- A) null for reference types, and the type's minimum value for primitive types. `Incorrect: While reference types are initialized to null, primitive types are not initialized to their minimum value`.
+- B) null for reference types, and 0 for primitive types. `Correct: Reference types are initialized to null and primitive types like int, char, float, boolean etc., are initialized to 0, '\u0000', 0.0f, and false respectively`.
+- C) The type's maximum value for primitive types, and null for reference types. `Incorrect: Primitive types are not initialized to their maximum value`【37†source】.
+
+### Question 16
+
+What is one of the advantages of encapsulation in Object-Oriented Programming?
+
+- A) Code Reuse. `Incorrect: Code reuse is associated more with inheritance and polymorphism than with encapsulation`.
+- B) Code Compression. `Incorrect: Encapsulation does not inherently lead to code compression`.
+- C) Code Simplification. `Correct: Encapsulation simplifies code by hiding its complexity. It allows the encapsulating object to change its internal implementation without affecting the code that uses the object`【38†source】.
+### Question 17
+
+In the given example, which method is responsible for setting the speed of a MotorBike object while ensuring it is not negative?
+
+- A) setSpeed(). `Correct: The setSpeed() method is typically responsible for setting the speed of a MotorBike object. It can include validation to ensure the speed is not negative`.
+- B) increaseSpeed(). `Incorrect: The increaseSpeed() method might increase the speed of the MotorBike object, but it is not responsible for directly setting the speed`.
+- C) decreaseSpeed(). `Incorrect: The decreaseSpeed() method might decrease the speed of the MotorBike object, but it is not responsible for directly setting the speed`【39†source】.
+
+### Question 18
+
+How can code duplication be reduced when implementing validation checks for the increaseSpeed() and decreaseSpeed() methods?
+
+- A) By using separate validation checks for each method. `Incorrect: Using separate validation checks for each method would actually lead to code duplication`.
+- B) By calling the setSpeed() method with appropriate parameters inside both methods. `Correct: By calling the setSpeed() method (which could contain the necessary validation checks) from within the increaseSpeed() and decreaseSpeed() methods, we can reuse the validation logic and thus reduce code duplication`.
+- C) By using a global validation check. `Incorrect: Using a global validation check can be problematic as it may not apply universally to all situations and can lead to code coupling`【40†source】.
+
+### Question 19
+
+What is the purpose of encapsulation in the context of protecting an object's state?
+
+- A) To prevent other objects from directly accessing the object's state. `Correct: Encapsulation is a principle of Object-Oriented Programming that helps protect an object's state by hiding its data (fields) and providing methods for data access and manipulation`.
+- B) To allow other objects to directly access the object's state. `Incorrect: Encapsulation does not allow other objects to directly access the object's state, instead, it provides controlled access via methods`.
+- C) To create a new object with the same state as the original object. `Incorrect: Encapsulation does not deal with creating new objects with the same state as existing ones`【41†source】.
+
+### Question 20
+
+In the given example, which method is used to start the MotorBike?
+
+- A) begin(). `Incorrect: The method name to start the MotorBike is not given in the question. However, in conventional programming practice, methods such as "start" or "run" are often used`.
+- B) start(). `Correct: In common practice, the method to start a MotorBike or similar objects could be named "start"`.
+- C) initiate(). `Incorrect: Although "initiate" could be a valid method name, it's not as commonly used as "start"`【42†source】.
+
+### Question 22
+
+What is the purpose of a constructor in a Java class?
+
+- a) To create an instance of the class with the specified initial state. `Correct: A constructor in Java is used to create an instance of a class and can initialize the state of the object`.
+- b) To perform calculations on the class variables. `Incorrect: While constructors can contain code that performs calculations, this is not their primary purpose`.
+- c) To modify the state of an object after it has been created. `Incorrect: Constructors are used to initialize an object when it is created, not to modify its state after creation`.
+- d) To destroy an object when it is no longer needed. `Incorrect: In Java, destruction of objects is managed by the Garbage Collector, not by constructors`【43†source】.
+
+### Question 6
+
+What is a default constructor in Java?
+
+- a) A constructor that is automatically provided by the compiler if no other constructors are defined. `Correct: If no constructors are defined in a Java class, the compiler automatically provides a default constructor with no arguments`.
+- b) A constructor with a single argument. `Incorrect: The number of arguments has no bearing on whether a constructor is considered default`.
+- c) A constructor that takes an unlimited number of arguments. `Incorrect: A default constructor does not take an unlimited number of arguments, it takes no arguments`.
+- d) A constructor that initializes all instance variables to their default values. `Incorrect: While a default constructor can be used to initialize variables, its defining feature is that it is provided by the compiler when no other constructors are defined`【44†source】.
+
+### Question 23
+
+What is a constructor in Java?
+
+- a) A special method with the same name as the class. `Correct: A constructor is a special method in a class, with the same name as the class`.
+- b) A method that returns a value. `Incorrect: Constructors do not return a value`.
+- c) A method that can be called directly. `Incorrect: Constructors are not called directly; they are called when an instance of the class is created using the new keyword`.
+- d) A method that can only accept zero arguments. `Incorrect: Constructors can take any number of arguments, including zero`【45†source】.
+
+### Question 24
+
+How is a constructor invoked in Java?
+
+- a) By calling the method directly. `Incorrect: Constructors are not called directly, they are invoked when an instance of the class is created`.
+- b) By using the new keyword while creating an object of the class. `Correct: Constructors are invoked using the new keyword when an object of the class is created`.
+- c) By declaring the constructor as static. `Incorrect: Static methods belong to the class, not the instance of the class. Constructors are not static and cannot be declared as such`.
+- d) By using the this keyword while creating an object of the class. `Incorrect: The this keyword refers to the current instance of the class and is not used to invoke a constructor`【46†source】.
+
+### Question 25
+
+Can a constructor accept multiple arguments in Java?
+
+- a) No, a constructor can only accept zero or one argument. `Incorrect: A constructor in Java can accept any number of arguments`.
+- b) Yes, a constructor can accept multiple arguments. `Correct: A constructor in Java can accept multiple arguments`.
+- c) Only the default constructor can accept multiple arguments. `Incorrect: The default constructor does not take any arguments`.
+- d) It depends on the access modifiers of the constructor. `Incorrect: The number of arguments a constructor can take does not depend on its access modifiers`【47†source】.
+
+### Question 26
+
+What is a default constructor in Java?
+
+- a) A constructor that accepts no arguments. `Correct: A default constructor is a no-argument constructor`.
+- b) A constructor that is defined by the programmer. `Incorrect: A default constructor is provided by the compiler if no constructor is defined by the programmer`.
+- c) A constructor that is generated by the compiler when no constructor is defined. `Correct: If no constructor is defined in the class, the Java compiler automatically provides a default constructor`.
+- d) A constructor that is called automatically when an object is created. `Incorrect: While all constructors are invoked when an object is created, not all are default constructors`【48†source】.
+
+### Question 27
+
+What happens when a class has no constructor defined in Java?
+
+- a) The code fails to compile. `Incorrect: If a class in Java does not have a constructor defined, the code will still compile`.
+- b) A default constructor is generated by the compiler. `Correct: If no constructor is explicitly defined in a Java class, the compiler automatically generates a default constructor`.
+- c) The code compiles and runs without any issues. `Incorrect: While the code would still compile and could run without issues, this answer is misleading because it does not mention the automatic generation of a default constructor`.
+- d) The class cannot be instantiated. `Incorrect: Even if a constructor is not defined, a class can still be instantiated using the default constructor`【49†source】.
\ No newline at end of file
diff --git a/00-Quiz-Explanation/Q06-PrimitiveDataTypesAndAlternatives.md b/00-Quiz-Explanation/Q06-PrimitiveDataTypesAndAlternatives.md
new file mode 100644
index 00000000..879dd81e
--- /dev/null
+++ b/00-Quiz-Explanation/Q06-PrimitiveDataTypesAndAlternatives.md
@@ -0,0 +1,331 @@
+Step 01: The Integer Types
+
+Question 1: Which of the following wrapper classes corresponds to the int primitive type in Java?
+
+- A) Byte (Incorrect: The `Byte` class corresponds to the byte primitive type, not int.)
+- B) Integer (Correct: The `Integer` class is the wrapper class for the `int` primitive type. It provides methods to work with int values.)
+- C) Short (Incorrect: The `Short` class corresponds to the short primitive type, not int.)
+
+Explanation:
+
+- Option A is incorrect because the `Byte` class corresponds to the byte primitive type, not int.
+- Option B is correct because the `Integer` class is the wrapper class specifically designed to work with int values.
+- Option C is incorrect because the `Short` class corresponds to the short primitive type, not int.
+
+Question 2: What is the maximum value of a short data type in Java?
+
+- A) 127
+- B) 32767 (Correct: The maximum value of a `short` is 32767)
+- C) 2147483647 (Incorrect: The value 2147483647 is the maximum value for the `int` data type, not short.)
+
+Explanation:
+
+- Option A is incorrect because 127 is the maximum value for the `byte` data type, not short.
+- Option B is correct because 32767 is the maximum value for the `short` data type in Java.
+- Option C is incorrect because 2147483647 is the maximum value for the `int` data type, not short.
+
+Question 3: What type of cast is used to store a smaller data value in a larger data type variable?
+
+- A) Implicit cast (Correct: Implicit casting is used to automatically convert a smaller data type to a larger data type)
+- B) Explicit cast
+
+Explanation:
+
+- Option A is correct because implicit casting is used to automatically convert a smaller data type to a larger data type without any loss of data.
+- Option B is incorrect because explicit casting is used when converting a larger data type to a smaller data type and requires explicit specification.
+
+
+
+Step 02: Integer Representations, And Other Puzzles
+
+Question 1: What are the three number systems supported by Java for integers?
+
+- A) Decimal, Octal, and Binary
+- B) Decimal, Octal, and Hexadecimal (Correct: The three number systems supported by Java for integers are decimal, octal, and hexadecimal)
+- C) Decimal, Binary, and Hexadecimal (Incorrect: Binary is also a number system supported by Java for integers)
+
+Explanation:
+
+- Option A is incorrect because it doesn't include hexadecimal, which is one of the number systems supported by Java for integers.
+- Option B is correct because decimal, octal, and hexadecimal are the three number systems supported by Java for integers.
+- Option C is incorrect because it includes binary, but it doesn't include octal.
+
+Question 2: Which of the following is the correct representation for the value 16 in a hexadecimal system?
+
+- A) 0x10 (Correct: In a hexadecimal system, 16 is represented as 0x10)
+- B) 010 (Incorrect: This represents the value 10 in an octal system)
+- C) 0x16 (Incorrect: This represents the value 22 in a hexadecimal system)
+
+Explanation:
+
+- Option A is correct because in a hexadecimal system, the prefix "0x" is used, followed by the digits representing the value. Therefore, 16 is represented as 0x10.
+- Option B is incorrect because "010" represents the value 10 in an octal system, not hexadecimal.
+- Option C is incorrect because "0x16" represents the value 22 in a hexadecimal system, not 16.
+
+Question 3: What is the difference between prefix and post-fix increment operators in Java?
+
+- A) Prefix increment takes place before the assignment, and post-fix increment takes place after the assignment. (Correct: Prefix increment happens before the assignment, while postfix increment happens after the assignment.)
+- B) Prefix increment takes place after the assignment, and post-fix increment takes place before the assignment. (Incorrect: The order of increment is reversed in the explanation)
+- C) There is no difference between prefix and post-fix increment operators in Java. (Incorrect: There is a difference in the order of increment)
+
+Explanation:
+
+- Option A is correct because prefix increment (++variable) happens before the assignment, meaning the variable is incremented and then used in the expression.
+- Option B is incorrect because the explanation states that postfix increment happens before the assignment, which is incorrect.
+- Option C is incorrect because there is indeed a difference between prefix and postfix increment operators in Java.
+
+
+
+Step 03: Classroom Exercise CE-01 (With Solutions)
+
+Question 1: What is the purpose of the BiNumber class?
+
+- A) To store a single integer and perform basic arithmetic operations
+- B) To store a pair of integers and perform basic arithmetic operations (Correct: The purpose of the BiNumber class is to store a pair of integers and perform basic arithmetic operations)
+- C) To store a list of integers and perform basic arithmetic operations
+
+Explanation:
+
+- Option A is incorrect because it mentions storing a single integer, while the BiNumber class is specifically designed to store a pair of integers.
+- Option B is correct because the BiNumber class is used to store a pair of integers and provides methods to perform basic arithmetic operations on those numbers.
+- Option C is incorrect because it mentions storing a list of integers, which is not the purpose of the BiNumber class.
+
+Question 2: Which method is used to double the values of both numbers in a BiNumber object?
+
+- A) double()
+- B) doubleNumbers() (Correct: The `doubleNumbers()` method is used to double the values of both numbers in a BiNumber object)
+- C) doubleValue()
+
+Explanation:
+
+- Option A is incorrect because `double()` is not a valid method for doubling the values of both numbers in a BiNumber object.
+- Option B is correct because the `doubleNumbers()` method specifically performs the operation of doubling the values of both numbers in a BiNumber object.
+- Option C is incorrect because `doubleValue()` is not the method responsible for doubling both numbers in a BiNumber object.
+
+Question 3: What will be the output of the following code snippet?
+
+```java
+BiNumber numbers = new BiNumber(4, 5);
+System.out.println(numbers.add());
+numbers.doubleValue();
+System.out.println(numbers.getNumber1());
+System.out.println(numbers.getNumber2());
+```
+
+- A) 9, 8, 10
+- B) 9, 8, 5
+- C) 9, 4, 5 (Correct: The output will be 9, 4, 5 after adding the numbers and doubling the value of the BiNumber object)
+
+Explanation:
+
+- The first line creates a BiNumber object with values 4 and 5.
+- The second line prints the result of adding the two numbers, which is 9.
+- The third line calls the `doubleValue()` method on the BiNumber object, doubling both numbers internally.
+- The fourth line prints the first number of the BiNumber object, which is now 4.
+- The fifth line prints the second number of the BiNumber object, which remains 5.
+- Therefore, the output will be 9, 4, 5.
+
+
+
+Step 05: Floating-Point Types
+
+Question 1: What is the default type for floating-point literals in Java?
+
+- A) float
+- B) double (Correct: The default type for floating-point literals in Java is `double`)
+
+Explanation:
+
+- Option A is incorrect because the default type for floating-point literals in Java is `double`.
+- Option B is correct because `double` is the default type for floating-point literals in Java.
+
+Question 2: How can you create a float literal?
+
+- A) float f = 34.5
+- B) float f = 34.5f; (Correct: To create a float literal, you need to append the suffix `f` to the value)
+- C) float f = (float)34.5
+
+Explanation:
+
+- Option A is incorrect because 34.5 without the `f` suffix is considered a `double` literal, not a `float` literal.
+- Option B is correct because adding the `f` suffix to the value makes it a `float` literal.
+- Option C is incorrect because explicitly casting the value to a `float` is another way to create a `float` literal, but it is not necessary when assigning a literal value directly.
+
+Question 3: Which type of casting is needed to convert a double value to a float value?
+
+- A) Implicit casting
+- B) Explicit casting (Correct: Explicit casting is required to convert a `double` value to a `float` value)
+
+Explanation:
+
+- Option A is incorrect because implicit casting is not sufficient to convert a `double` value to a `float` value. It could result in a loss of precision.
+- Option B is correct because explicit casting, specifically `(float)`, is needed to convert a `double` value to a `float` value. It explicitly tells the compiler to perform the conversion, even though there may be potential loss of precision.
+
+
+
+Step 06: Introducing BigDecimal
+
+Question 1: What is the main reason for using the BigDecimal data type in Java?
+
+- To represent floating-point numbers with higher precision (Correct: The main reason for using the BigDecimal data type is to represent floating-point numbers with higher precision)
+- To perform faster calculations
+- To store large integer values
+
+Explanation:
+
+- Option A is correct because the BigDecimal data type is used to represent floating-point numbers with higher precision, avoiding issues with rounding errors that can occur with other floating-point types.
+- Option B is incorrect because the primary purpose of BigDecimal is precision, not performance.
+- Option C is incorrect because BigDecimal is not specifically designed for storing large integer values; it is more focused on decimal numbers with high precision.
+
+Question 2: What is the best way to construct a BigDecimal object to achieve high precision?
+
+- Using integer literals
+- Using double literals
+- Using string literals (Correct: The best way to construct a BigDecimal object to achieve high precision is by using string literals)
+
+Explanation:
+
+- Option A is incorrect because using integer literals might result in the loss of precision when constructing a BigDecimal object.
+- Option B is incorrect because using double literals may introduce rounding errors when constructing a BigDecimal object.
+- Option C is correct because using string literals, such as "0.12345678901234567890", allows you to specify the exact precision and avoid any potential rounding errors.
+
+Question 3: What is the main characteristic of BigDecimal objects?
+
+- Mutable
+- Immutable (Correct: BigDecimal objects are immutable, meaning their values cannot be changed once created)
+- Synchronized
+
+Explanation:
+
+- Option A is incorrect because BigDecimal objects are immutable, meaning their values cannot be changed once created.
+- Option B is correct because BigDecimal objects have the characteristic of immutability, ensuring that their values remain unchanged.
+- Option C is incorrect because synchronization is not a characteristic specific to BigDecimal objects. It is related to thread safety.
+
+
+
+Step 06: BigDecimal Operations
+
+Question: Which of the following methods can be used for arithmetic operations on BigDecimal objects?
+
+- a. add()
+- b. multiply()
+- c. subtract()
+- d. All of the above (Correct: All of the mentioned methods can be used for arithmetic operations on BigDecimal objects)
+
+Explanation:
+
+- Option a is correct because the `add()` method is used for addition of BigDecimal objects.
+- Option b is correct because the `multiply()` method is used for multiplication of BigDecimal objects.
+- Option c is correct because the `subtract()` method is used for subtraction of BigDecimal objects.
+- Option d is correct because all of the mentioned methods (add(), multiply(), and subtract()) can be used for arithmetic operations on BigDecimal objects.
+
+Question: Can you perform arithmetic operations directly between a BigDecimal object and a primitive data type, like an int or a double?
+
+- a. Yes
+- b. No (Correct: No, arithmetic operations between BigDecimal objects and primitive data types require explicit conversion)
+
+Explanation:
+
+- Option a is incorrect because arithmetic operations between BigDecimal objects and primitive data types cannot be performed directly without explicit conversion.
+- Option b is correct because explicit conversion, using methods like `BigDecimal.valueOf()`, is required to perform arithmetic operations between BigDecimal objects and primitive data types.
+
+Question: How can you perform an arithmetic operation between a BigDecimal object and a primitive int value?
+
+- a. Convert the int to a BigDecimal using BigDecimal.valueOf() (Correct: To perform an arithmetic operation between a BigDecimal object and a primitive int value, you need to convert the int to a BigDecimal using BigDecimal.valueOf())
+
+Explanation:
+
+- Option a is correct because to perform an arithmetic operation between a BigDecimal object and a primitive int value, you need to convert the int to a BigDecimal using the `BigDecimal.valueOf()` method.
+- Using this method, you can create a BigDecimal object representing the int value and then perform arithmetic operations with other BigDecimal objects.
+
+
+
+Step 08: boolean, Relational and Logical Operators
+
+Question: Which of the following operators is a logical operator in Java?
+
+- a) >
+- b) &&
+- c) <= (Correct: The logical operator in Java is represented by the symbol &&)
+
+Explanation:
+
+- Option a is incorrect because the ">" operator is a relational operator used for comparison.
+- Option b is correct because the "&&" operator is the logical AND operator in Java, which combines two boolean expressions.
+- Option c is incorrect because the "<=" operator is a relational operator used for comparison, not a logical operator.
+
+Question: Given the following code snippet, what will be the value of result?
+
+```java
+int a = 10;
+int b = 5;
+boolean result = (a > b) && (a < 2 * b);
+```
+
+- a) true (Correct: The value of result will be true)
+- b) false
+
+Explanation:
+
+- In the given code snippet, the expression `(a > b) && (a < 2 * b)` is evaluated.
+- `(a > b)` evaluates to true because 10 is greater than 5.
+- `(a < 2 * b)` also evaluates to true because 10 is less than 2 times 5, which is 10.
+- The logical AND operator `&&` combines these two boolean expressions and returns true only if both expressions are true.
+- Since both expressions are true, the value of `result` will be true.
+
+Question: What will the following expression evaluate to?
+
+```java
+boolean x = true;
+boolean y = false;
+boolean z = !(x || y);
+```
+
+- a) true
+- b) false (Correct: The expression will evaluate to false)
+
+Explanation:
+
+- The expression `(x || y)` evaluates to true because at least one of the operands (x or y) is true.
+- The `!` operator negates the result, so `!(x || y)` evaluates to false.
+- Therefore, the value of `z` will be false.
+
+
+
+Step 10: Character Types
+
+Question 1: What is the Unicode representation of the double quotation mark?
+
+- \u0021
+- \u0022 (Correct: The Unicode representation of the double quotation mark is \u0022)
+- \u0023
+
+Explanation:
+
+- Option \u0021 represents the Unicode character for exclamation mark (!), not the double quotation mark.
+- Option \u0022 is correct because it represents the Unicode character for double quotation mark (").
+- Option \u0023 represents the Unicode character for hash or number sign (#), not the double quotation mark.
+
+Question 2: What data type in Java is used to store Unicode characters?
+
+- String
+- char (Correct: The `char` data type in Java is used to store Unicode characters)
+- int
+
+Explanation:
+
+- Option String is incorrect because `String` is a data type used to store sequences of characters, not a single Unicode character.
+- Option char is correct because the `char` data type is specifically designed to store a single Unicode character.
+- Option int is incorrect because `int` is used to store integer values, not Unicode characters.
+
+Question 3: What happens when you perform the following operation in Java: `char cn = 65;`?
+
+- A character with a Unicode value of 65 is stored in the variable cn. (Correct: The character with Unicode value 65, which is 'A', is stored in the variable cn)
+- An integer value of 65 is stored in the variable cn.
+- A compilation error occurs.
+
+Explanation:
+
+- Option A is correct because assigning the value 65 to a char variable `cn` will store the character 'A' in `cn`. In Java, characters are internally represented using Unicode values.
+- Option B is incorrect because 65 is the Unicode value of 'A', not an integer value.
+- Option C is incorrect because there is no compilation error in assigning a Unicode value to a char variable.
diff --git a/00-Quiz-Explanation/Q07-Conditionals.md b/00-Quiz-Explanation/Q07-Conditionals.md
new file mode 100644
index 00000000..8510fb5f
--- /dev/null
+++ b/00-Quiz-Explanation/Q07-Conditionals.md
@@ -0,0 +1,381 @@
+### Question 28
+
+What is the if statement used for in Java?
+
+- a) To execute some code when a boolean condition is true. `Correct: An if statement in Java is used to execute a block of code when a specified condition is true`.
+- b) To execute some code when a boolean condition is false. `Incorrect: This is not the primary purpose of the if statement. Though an "else" clause following an if statement can execute code when the condition is false, the primary purpose of the if statement is to execute code when a condition is true`.
+- c) To execute some code regardless of the boolean condition. `Incorrect: An if statement is condition-dependent. Code within its block is executed only when the condition is true`【50†source】.
+
+### Question 29
+
+What is the difference between if and if-else statements in Java?
+
+- a) There is no difference, they do the same thing. `Incorrect: There is a difference between if and if-else statements. The if-else statement includes a default action when the if condition is false`.
+- b) If statement executes code only when the condition is true, whereas if-else statement executes code when the condition is false. `Correct: An if statement executes code only when its condition is true. An if-else statement adds a default action that is executed when the if condition is false`.
+- c) If statement executes code only when the condition is false, whereas if-else statement executes code when the condition is true. `Incorrect: This is the opposite of how if and if-else statements work in Java`【51†source】.
+
+### Question 30
+
+What is the output of the following code snippet in Java?
+
+```java
+int i = 10;
+if(i < 5) {
+ System.out.println("i is less than 5");
+} else if(i > 20) {
+ System.out.println("i is greater than 20");
+} else {
+ System.out.println("i is between 5 and 20");
+}
+```
+
+- a) "i is less than 5" `Incorrect: The value of i is 10, which is not less than 5`.
+- b) "i is greater than 20" `Incorrect: The value of i is 10, which is not greater than 20`.
+- c) "i is between 5 and 20" `Correct: The value of i is 10, which falls between 5 and 20`【52†source】.
+
+### Question 31
+
+What is the purpose of the if-else if-else statement in Java?
+
+- a) To execute some code when a boolean condition is true. `Incorrect: This is a feature of the if statement, not specifically the if-else if-else statement`.
+- b) To execute some code when multiple conditions are true. `Incorrect: An if-else if-else statement is used to check multiple conditions, but it only executes the first block of code whose condition is true`.
+- c) To execute some code when one and only one condition is true. `Correct: In an if-else if-else statement, once a true condition is found and its corresponding code block is executed, the remaining conditions are not checked`【53†source】.
+
+### Question 32
+
+What happens if multiple conditions in the if-else if-else statement evaluate to true in Java?
+
+- a) All corresponding code blocks are executed. `Incorrect: Only the first block of code with a true condition is executed in an if-else if-else statement`.
+- b) Only the first corresponding code block is executed. `Correct: In an if-else if-else statement, once a true condition is found and its corresponding code block is executed, the remaining conditions are not checked`.
+- c) Only the last corresponding code block is executed. `Incorrect: Only the first block of code with a true condition is executed in an if-else if-else statement`【54†source】.
+
+### Question 33
+
+What is the output of the following code snippet in Java?
+
+```java
+int i = 15;
+if(i < 5) {
+ System.out.println("i is less than 5");
+} else if(i > 20) {
+ System.out.println("i is greater than 20");
+} else if(i < 10) {
+ System.out.println("i is less than 10");
+} else {
+ System.out.println("i is between 10 and 20");
+}
+```
+
+- a) "i is less than 5" `Incorrect: The value of i is 15, which is not less than 5`.
+- b) "i is greater than 20" `Incorrect: The value of i is 15, which is not greater than 20`.
+- c) "i is less than 10" `Incorrect: The value of i is 15, which is not less than 10`.
+- d) "i is between 10 and 20" `Correct: The value of i is 15, which falls between 10 and 20`【55†source】.
+
+### Question 34
+
+What is the output of the following code snippet?
+
+```java
+public static void puzzleOne() {
+ int k = 15;
+ if(k > 20) {
+ System.out.println(1);
+ } else if(k > 10) {
+ System.out.println(2);
+ } else if(k < 20) {
+ System.out.println(3);
+ } else {
+ System.out.println(4);
+ }
+}
+```
+
+- a) 1 `Incorrect: The value of k is 15, which is not greater than 20`.
+- b) 2 `Correct: The value of k is 15, which is greater than 10`.
+- c) 3 `Incorrect: The value of k is 15, which is less than 20, but the previous condition (k > 10) was already met and its block was executed`.
+- d) 4 `Incorrect: The else block would only execute if none of the previous conditions were met, but the condition (k > 10) was met`【56†source】.
+
+### Question 35
+
+What is the output of the following code snippet?
+
+```java
+public static void puzzleTwo() {
+ int l = 15;
+ if(l < 20)
+ System.out.println("l < 20");
+ if(l > 20)
+ System.out.println("l > 20");
+ else
+ System.out.println("Who Am I?");
+}
+```
+
+- a) l < 20 `Incorrect: While it's true that l < 20, the subsequent else clause is associated with the second if statement (l > 20), not the first one`.
+- b) l > 20 `Incorrect: The value of l is 15, which is not greater than 20`.
+- c) Who Am I? `Correct: The else clause is associated with the second if statement, and since l is not greater than 20, "Who Am I?" is printed`【57†source】.
+
+### Question 36
+
+What is the output of the following code snippet?
+
+```java
+public static void puzzleThree() {
+ int m = 15;
+ if(m > 20)
+ if(m < 20)
+ System.out.println("m > 20"); else
+ System.out.println("Who Am I?");
+}
+```
+
+- a) m > 20 `Incorrect: The outer condition (m > 20) is not met, so none of the code inside the outer if statement is executed`.
+- b) Who Am I? `Incorrect: The outer condition (m > 20) is not met, so none of the code inside the outer if statement is executed`.
+- c) Nothing is printed. `Correct: The outer condition (m > 20) is not met, so none of the code inside the outer if statement is executed`【58†source】.
+
+
+### Question 37
+
+What is the output of the following code snippet?
+
+```java
+int i = 0;
+if(i) {
+ System.out.println("i");
+}
+```
+
+- a) i `Incorrect: This code will not compile because i is an integer and the if statement requires a boolean`.
+- b) Compiler Error `Correct: This code will not compile because i is an integer and the if statement requires a boolean`.
+- c) Nothing is printed `Incorrect: This code will not compile, so there is no opportunity for anything to be printed`【59†source】.
+
+### Question 38
+
+What is the output of the following code snippet?
+
+```java
+public static void puzzleFive() {
+ int number = 5;
+ if(number < 0)
+ number = number + 10;
+ number++;
+ System.out.println(number);
+}
+```
+
+- a) 4 `Incorrect: The value of number is 5, it is incremented to 6 and then printed`.
+- b) 5 `Incorrect: The value of number is 5, but it is incremented before it is printed`.
+- c) 6 `Correct: The value of number is 5, it is incremented to 6 and then printed`【60†source】.
+
+### Question 39
+
+What is the purpose of using the Scanner class in Java?
+
+- a) To scan user input from the console `Correct: The Scanner class is used to read input from various sources, including the console`.
+- b) To read input from a file `Incorrect: While the Scanner class can be used to read input from a file, the question is about the main purpose of the Scanner class`.
+- c) To generate random numbers `Incorrect: The Scanner class does not generate random numbers`【61†source】.
+
+### Question 40
+
+What do you need to pass as a parameter to the Scanner constructor?
+
+- a) System.in `Correct: To read input from the console, System.in is passed as a parameter to the Scanner constructor`.
+- b) System.out `Incorrect: System.out is not used for input, but rather to output data`.
+- c) System.error `Incorrect: System.error does not exist in Java. You may be thinking of System.err, which is used for error output, not input`【62†source】.
+
+
+### Question 41
+
+How do you read an integer input from the console using the Scanner class?
+
+- a) scanner.nextInt() `Correct: The nextInt() method of the Scanner class is used to read an integer input from the console`.
+- b) scanner.readInt() `Incorrect: The Scanner class does not have a readInt() method`.
+- c) scanner.getInt() `Incorrect: The Scanner class does not have a getInt() method`【63†source】.
+
+### Question 42
+
+What is the purpose of the following code snippet?
+
+```java
+Scanner scanner = new Scanner(System.in);
+```
+
+- a) To initialize the Scanner class `Incorrect: This statement creates an instance of the Scanner class, not initializes it`.
+- b) To import the Scanner class `Incorrect: This statement creates an instance of the Scanner class, not imports it`.
+- c) To create an instance of the Scanner class `Correct: This statement creates an instance of the Scanner class`【64†source】.
+
+### Question 43
+
+What does the following line of code do?
+
+```java
+int number1 = Scanner.nextInt();
+```
+
+- a) Imports the next integer from the keyboard `Incorrect: This statement initializes the value of number1 to the next integer read from the keyboard`.
+- b) Initializes the value of number1 to the next integer from the keyboard `Correct: This statement initializes the value of number1 to the next integer read from the keyboard`.
+- c) Creates an instance of the nextInt method `Incorrect: This statement does not create an instance of a method`【65†source】.
+
+### Question 44
+
+What does the following code snippet do?
+
+```java
+System.out.println("Your Inputs Are:");
+System.out.println("Number1: " + number1);
+System.out.println("Number2: " + number2);
+System.out.println("Choice: " + choice);
+```
+
+- a) Imports the values of number1, number2, and choice from the keyboard `Incorrect: This code snippet does not import any values. It outputs them to the console`.
+- b) Writes the values of number1, number2, and choice to the console `Correct: This code snippet outputs the values of number1, number2, and choice to the console`.
+- c) Initializes the values of number1, number2, and choice `Incorrect: This code snippet does not initialize any values. It outputs them to the console`【66†source】.
+
+
+### Question 45
+
+What is the purpose of the if-else-else if statement in the code?
+
+- a) To check for 4 favorable conditions `Incorrect: While it may look at multiple conditions, it's not specifically for checking 4 conditions`.
+- b) To handle invalid operation choice `Correct: If-else-else if statement is used to handle various possibilities including invalid operation choice`.
+- c) To handle both favorable conditions and invalid operation choice `Correct: This statement is used to handle multiple conditions, both favorable and unfavorable (including invalid operation choice)`.
+- d) None of the above `Incorrect: The if-else-else if statement serves to check conditions and execute code based on those conditions`【67†source】.
+
+### Question 46
+
+What does the statement `"System.out.println("Result = " + (number1 + number2));"` do in the code?
+
+- a) Prints the sum of number1 and number2 `Correct: This statement calculates the sum of number1 and number2 and prints it`.
+- b) Prints the difference of number1 and number2 `Incorrect: This statement is calculating and printing the sum, not the difference`.
+- c) Prints the product of number1 and number2 `Incorrect: This statement is calculating and printing the sum, not the product`.
+- d) Prints the quotient of number1 and number2 `Incorrect: This statement is calculating and printing the sum, not the quotient`【68†source】.
+
+### Question 47
+
+What is the output when choice is 5?
+
+- a) Result = 55 `Incorrect: If choice is not one of the options (1, 2, 3, or 4), the output would be "Invalid Operation"`.
+- b) Invalid Operation `Correct: If choice is not one of the options (1, 2, 3, or 4), the output would be "Invalid Operation"`.
+- c) Number1: 25 `Incorrect: The value of Number1 or Number2 is not outputted based on the value of choice`.
+- d) Number2: 35 `Incorrect: The value of Number1 or Number2 is not outputted based on the value of choice`【69†source】.
+
+
+### Question 48
+
+Which of the following is NOT true about a switch statement in Java?
+
+- A) A switch statement is used to test multiple conditions `Incorrect: The switch statement in Java is used to select one of many code blocks to be executed, essentially testing multiple conditions`.
+- B) The default clause is executed when none of the cases match `Correct: The default clause in a switch statement is indeed executed when none of the case conditions match`.
+- C) The switch statement can handle the default possibility `Correct: The switch statement can include a default clause which is executed when no matching case has been found`.
+- D) The switch statement is used to test only one condition `Correct: This statement is false. The switch statement is used to test multiple conditions (cases) based on a single variable/expression`【70†source】.
+
+### Question 49
+
+What is the purpose of the break statement in a switch statement in Java?
+
+- A) To break out of the switch after a successful match `Correct: The break statement is used to stop the execution of the remaining cases in the switch statement after a case has been executed`.
+- B) To continue to the next case in the switch `Incorrect: Without a break statement, the program will continue executing the next case, even if the case condition does not match. The break statement serves to prevent this`.
+- C) To stop the execution of the program `Incorrect: The break statement only stops the execution of the current switch statement, not the entire program`.
+- D) To continue to the default clause in the switch `Incorrect: The break statement is used to exit the switch statement, not to jump to the default case`【71†source】.
+
+### Question 50
+
+What will the following code snippet output in Java?
+
+```java
+int number = 2;
+switch(number) {
+ case 1:
+ System.out.println(1);
+ case 2:
+ System.out.println(2);
+ case 3:
+ System.out.println(3);
+ default:
+ System.out.println("default");
+}
+```
+
+- A) 1 `Incorrect: Given that "number" is 2, it won't print 1`.
+- B) 2 `Incorrect: Given that "number" is 2, it will start at case 2 but since there are no break statements, it will also execute the remaining cases and the default`.
+- C) 3 `Incorrect: Given that "number" is 2, it will print 3 as well, but it will also print 2 and "default"`.
+- D) 1, 2, 3, default `Correct: Given that "number" is 2 and there are no break statements, it will start at case 2 and also execute the remaining cases (3) and the default`【72†source】.
+
+
+
+### Question 51
+
+What type of conditions can be evaluated using an if-family conditional?
+
+- a. Only boolean conditions `Correct: if, else if, and else in Java evaluate boolean conditions. They run or skip code blocks based on whether a condition is true or false.`
+- b. Only integer values `Incorrect: While integer values can be part of a condition, the condition itself is evaluated as a boolean.`
+- c. Both boolean and integer values `Incorrect: The conditions are always evaluated as booleans, although they can compare integer values.`
+- d. None of the above `Incorrect: Option a is the correct one.`【73†source】
+
+### Question 52
+
+What is the advantage of using a switch conditional over an if-family conditional?
+
+- a. More readable and compact `Correct: Switch cases can be more readable and compact when comparing a variable to several constant values.`
+- b. Can be used to check for only integer values `Incorrect: Switch cases can also handle characters and enumerated types, not only integers.`
+- c. More strict rules `Incorrect: If-else conditionals can be more flexible, since they can evaluate any boolean condition, not just value comparisons.`
+- d. More versatile `Incorrect: If-else conditionals are more versatile since they can evaluate any boolean condition.`【74†source】
+
+### Question 53
+
+What is the disadvantage of using a switch conditional over an if-family conditional?
+
+- a. Can lead to subtle errors in the program `Correct: One such error can occur if the 'break' keyword is forgotten after a case.`
+- b. More versatile `Incorrect: Versatility is not a disadvantage.`
+- c. Can only check for boolean conditions `Incorrect: Switch cases do not evaluate boolean conditions, but rather check the value of a variable against constant values.`
+- d. Not as strict as if-family conditional `Incorrect: Strictness in this context doesn't refer to a disadvantage.`【75†source】
+
+### Question 54
+
+What is the name of the day represented by the number 3 in the determineNameOfDay method?
+
+- A. Monday `Incorrect: Monday is usually represented by 1 in such systems.`
+- B. Tuesday `Incorrect: Tuesday is usually represented by 2.`
+- C. Wednesday `Correct: In this system, Wednesday would be represented by 3.`
+- D. Thursday `Incorrect: Thursday would typically be represented by 4.`【76†source】
+
+### Question 55
+
+What is the name of the month represented by the number 9 in the determinenameofMonth method?
+
+- A. January `Incorrect: January is usually represented by 1 in such systems.`
+- B. February `Incorrect: February is usually represented by 2.`
+- C. March `Incorrect: March is usually represented by 3.`
+- D. September `Correct: In this system, September would be represented by 9.`【77†source】
+
+### Question 56
+
+Is the day represented by the number 1 considered to be a week day in the isWeekDay method?
+
+- A. Yes `Correct: In many systems, the days of the week are numbered from 1 (Monday) to 7 (Sunday), so 1 would be a weekday.`
+- B. No `Incorrect: As stated above, 1 usually represents Monday, which is a weekday.`【78†source】
+
+### Question 57
+
+What is the purpose of the ternary operator ?: in Java?
+
+- A. To perform addition of two operands `Incorrect: The ternary operator is not used for addition. It's used for conditional operations.`
+- B. To perform subtraction of two operands `Incorrect: The ternary operator is not used for subtraction. It's used for conditional operations.`
+- C. To perform conditional operations `Correct: The ternary operator is used to perform a simple if-else check in one line.`【79†source】
+
+### Question 58
+
+What should be the return type of both expressions in the ternary operator ?: in Java?
+
+- A. Both expressions can return any type of value `Incorrect: While the expressions can be of any type, they both need to be of the same type or compatible types.`
+- B. Both expressions should return different types of value `Incorrect: Both expressions should return values of the same type or of compatible types.`
+- C. Both expressions should return values of the same type `Correct: Both expressions in a ternary operation should be of the same type, or of types that can be automatically converted to a common type.`【80†source】
+
+### Question 59
+
+What is the syntax of the ternary operator ?: in Java?
+
+- A. result = (expression-if-condition-true ? condition : expression:if-condition-false); `Incorrect: The syntax for the ternary operator starts with the condition, followed by the '?' operator, the value for if condition is true, the ':' operator, and the value for if condition is false.`
+- B. result = (expression-if-condition-false ? condition : expression-if-condition-true); `Incorrect: Similar to the above explanation, the syntax starts with the condition to be evaluated.`
+- C. result = (condition ? expression-if-condition-true : expression-if-condition-false); `Correct: This is the correct syntax for the ternary operator in Java.`【81†source】
+
diff --git a/00-Quiz-Explanation/Q09-ReferenceTypes.md b/00-Quiz-Explanation/Q09-ReferenceTypes.md
new file mode 100644
index 00000000..8aa6bc38
--- /dev/null
+++ b/00-Quiz-Explanation/Q09-ReferenceTypes.md
@@ -0,0 +1,429 @@
+
+### Step 01: Introducing Reference Types
+
+**Question 60**
+
+What is the purpose of reference variables in Java?
+
+ * A. To store primitive values `Incorrect: Reference variables are used to store references to objects, not primitive values.`
+ * B. To store objects on the Heap `Incorrect: Reference variables store references (addresses), not the actual objects.`
+ * C. To store the memory location of an object `Correct: Reference variables store the memory location (reference) of an object.`【60†source】
+
+**Question 61**
+
+What is the main difference between reference types and primitive types in Java?
+
+ * A. Primitive types are stored on the Stack, reference types on the Heap `Correct: Primitive types are stored on the Stack and reference types are stored on the Heap.`
+ * B. Primitive types are stored on the Heap, reference types on the Stack `Incorrect: This is the opposite of the actual situation.`
+ * C. Both are stored on the Heap `Incorrect: Primitive types are stored on the Stack, not on the Heap.`【61†source】
+
+**Question 62**
+
+In the following code snippet, where are the objects `jupiter` and `dog` stored?
+
+```java
+class Planet { ... }
+Planet jupiter = new Planet();
+
+class Animal { ... }
+Animal dog = new Animal(12);
+```
+
+ * A. Stack `Incorrect: Objects are stored on the Heap in Java.`
+ * B. Heap `Correct: Objects are stored on the Heap in Java.`
+ * C. Both Stack and Heap `Incorrect: In Java, the Stack is used for storing method calls and primitive types, while the Heap is used for storing objects.`【62†source】
+
+### Step 02: References: Usage And Puzzles
+
+**Question 63**
+
+What is the value of a reference variable that is not initialized by the programmer in Java?
+
+ * A. 0 `Incorrect: 0 is a default value for numeric primitive types, not for reference types.`
+ * B. Empty `Incorrect: Empty is not a default value for a reference variable.`
+ * C. Null `Correct: If a reference variable is not initialized, its default value will be null.`【63†source】
+
+**Question 64**
+
+What happens when you compare two reference variables in Java?
+
+ * A. It compares the values stored inside the referenced objects `Incorrect: By default, comparing two reference variables checks if they point to the same object, not the content of the objects.`
+ * B. It compares the memory locations where the objects are stored `Correct: When you compare two reference variables, it checks whether they point to the same object, i.e., they have the same memory location.`
+ * C. It compares the size of the objects `Incorrect: Java does not compare the size of the objects when comparing two reference variables.`【64†source】
+
+**Question 65**
+
+What happens when you assign one reference variable to another in Java?
+
+ * A. It creates a copy of the entire referenced object `Incorrect: Assigning one reference variable to another does not copy the object, only the reference.`
+ * B. It only copies the reference `Correct: When you assign one reference variable to another, it copies the reference, not the object. As a result, both variables point to the same object.`
+ * C. It creates a new object with the same values as the referenced object `Incorrect: Assigning one reference variable to another does not create a new object.`【65†source】
+
+### Step 03: Introducing String Quiz
+
+**Question 66**
+
+What is a string in Java?
+
+ * A. A sequence of numbers `Incorrect: In Java, a string is not a sequence of numbers.`
+ * B. A sequence of characters `Correct: In Java, a string is a sequence of characters.`
+ * C. A sequence of symbols `Incorrect: In Java, a string is not a sequence of symbols, it is a sequence of characters.`【66†source】
+
+**Question 67**
+
+What is the output of the following code:
+
+```java
+String str = "Test";
+System.out.println(str.charAt(2));
+```
+
+ * A. 'e' `Incorrect: The character at index 2 of the string "Test" is 's', not 'e'.`
+ * B. 's' `Correct: The character at index 2 of the string "Test" is 's'.`
+ * C. 'T' `Incorrect: The character at index 2 of the string "Test" is 's', not 'T'.`【67†source】
+
+**Question 68**
+
+What does the substring method of the String class return?
+
+ * A. A sequence of numbers `Incorrect: The substring method returns a sequence of characters, not numbers.`
+ * B. A sequence of characters `Correct: The substring method returns a sequence of characters from the original string.`
+ * C. A sequence of symbols `Incorrect: The substring method returns a sequence of characters, not symbols.`【68†source】
+
+### Step 04: Programming Exercise PE-01, And String Utilities
+
+**Question 102**
+
+What does the indexOf() method in the String class do?
+
+ * A. Returns the position of a character in a string `Correct but not the complete answer: The indexOf() method does return the position of the first occurrence of a specified character in a string.`
+ * B. Returns the starting position of a substring in a string `Correct but not the complete answer: The indexOf() method does return the position of the first occurrence of a specified substring in a string.`
+ * C. Both of the above `Correct: The indexOf() method can return the position of a character or a substring in a string.`
+ * D. None of the above `Incorrect: The indexOf() method does perform the functions stated in option C.`【102†source】
+
+**Question 103**
+
+How does the endsWith() method determine if a string ends with a given suffix?
+
+ * A. It returns the position of the last occurrence of the suffix in the string `Incorrect: The endsWith() method does not return a position.`
+ * B. It returns true if the string ends with the given suffix, false otherwise `Correct: The endsWith() method checks if a string ends with the specified suffix and returns a boolean result.`
+ * C. It returns false if the string ends with the given suffix, true otherwise `Incorrect: The endsWith() method returns true if the string ends with the specified suffix, not false.`
+ * D. None of the above `Incorrect: The endsWith() method does perform the function stated in option B.`【103†source】
+
+**Question 104**
+
+When using the equals() method, what is the result if the string is identical to the argument?
+
+ * A. Returns true `Correct: The equals() method compares the string to the argument and returns true if they are identical.`
+ * B. Returns false `Incorrect: The equals() method returns false if the strings are not identical, not if they are.`
+ * C. Returns the position of the first occurrence of the argument in the string `Incorrect: The equals() method does not return a position.`
+ * D. None of the above `Incorrect: The equals() method does perform the function stated in option A.`【104†source】
+
+### Step 05: String Immutability
+
+**Question 72**
+
+What is the meaning of the word "immutable"?
+
+ * A. Changeable `Incorrect: "Immutable" means unchangeable.`
+ * B. Unchangeable `Correct: "Immutable" means unchangeable.`
+ * C. Mutable `Incorrect: "Mutable" is the opposite of "immutable". It means changeable.`【72†source】
+
+**Question 73**
+
+Can the value of a string object be changed after it is created?
+
+ * A. Yes `Incorrect: String objects are immutable in Java, meaning their value cannot be changed once created.`
+ * B. No `Correct: String objects are immutable in Java, meaning their value cannot be changed once created.`【73†source】
+
+**Question 74**
+
+What does the method concat() do
+
+ in Java?
+
+ * A. Changes the original string by appending another string `Incorrect: The concat() method does not change the original string; instead, it returns a new string.`
+ * B. Returns a new string resulting from appending another string to the original string `Correct: The concat() method returns a new string that is the result of appending the specified string to the end of the original string.`
+ * C. Replaces the original string with a new string `Incorrect: The concat() method does not replace the original string; it returns a new string.`【74†source】
+
+**Question 75**
+
+What is String Pool in Java?
+
+ * A. A pool of methods for the String class `Incorrect: The String Pool is a pool of literal strings, not methods.`
+ * B. A pool of literal strings stored in the heap memory `Correct: The String Pool in Java is a pool of literal strings stored in the heap memory.`
+ * C. A pool of references to the String objects `Incorrect: The String Pool is a pool of literal strings, not references to String objects.`【75†source】
+
+
+### Step 05: String Immutability Continued
+
+**Question 76**
+
+What happens to the original string object when the method toUpperCase() is used on it?
+
+ * A. The original string object is changed to upper case `Incorrect: In Java, strings are immutable. The toUpperCase() method returns a new string.`
+ * B. The original string object remains unchanged, a new string object is returned with the changed value `Correct: The toUpperCase() method does not change the original string; it returns a new string.`【76†source】
+
+**Question 77**
+
+What is the output of the following code:
+
+```java
+String str = "in28Minutes";
+str = str.concat(" is awesome");
+System.out.println(str);
+```
+
+ * A. "in28Minutes is awesome" `Correct: The concat() method appends the given string to the end of the original string and the result is stored in 'str'.`
+ * B. "in28Minutes" `Incorrect: The concat() method appends the given string to the end of the original string.`
+ * C. "in28Minutes is awesome" and "in28Minutes" `Incorrect: The System.out.println() method will print only one string - the value of 'str'.`【77†source】
+
+### Step 06: More String Utilities
+
+**Question 78**
+
+What is the result of the following code:
+
+```java
+int i = 20;
+System.out.println("Value is " + i + 20);
+```
+
+ * A. Value is 40 `Incorrect: In this case, 'i + 20' will not perform integer addition because of string concatenation, and will result in '2020'.`
+ * B. Value is 2020 `Correct: The "+" operator in this context is used for string concatenation, not numerical addition.`
+ * C. Value is 2040 `Incorrect: The "+" operator in this context is used for string concatenation, not numerical addition.`【78†source】
+
+**Question 79**
+
+What is the result of the following code:
+
+```java
+String.join(",", "2", "3", "4");
+```
+
+ * A. "2,3,4" `Correct: The join() method concatenates the given strings with a comma as a delimiter.`
+ * B. "23,4" `Incorrect: The join() method concatenates all the given strings with a comma as a delimiter.`
+ * C. "234" `Incorrect: The join() method concatenates the given strings with a comma as a delimiter.`【79†source】
+
+**Question 80**
+
+What is the result of the following code:
+
+```java
+"abcd".replace("ab", "xyz");
+```
+
+ * A. "xyzcd" `Correct: The replace() method replaces all occurrences of the first argument with the second argument in the string.`
+ * B. "xyzabcd" `Incorrect: The replace() method does not append the replacement at the start of the string.`
+ * C. "abcdxyz" `Incorrect: The replace() method does not append the replacement at the end of the string.`【80†source】
+
+### Step 07: Storing mutable text
+
+**Question 81**
+
+What is the difference between StringBuffer and StringBuilder?
+
+ * A. StringBuffer is mutable while StringBuilder is immutable `Incorrect: Both StringBuffer and StringBuilder are mutable.`
+ * B. StringBuilder is mutable while StringBuffer is immutable `Incorrect: Both StringBuffer and StringBuilder are mutable.`
+ * C. Both StringBuffer and StringBuilder are immutable `Incorrect: Both StringBuffer and StringBuilder are mutable.`【81†source】
+
+**Question 82**
+
+What is the main advantage
+
+ of using StringBuilder over StringBuffer?
+
+ * A. StringBuilder is thread-safe `Incorrect: StringBuffer is thread-safe, not StringBuilder.`
+ * B. StringBuilder offers better performance in both execution-time and memory usage `Correct: Because StringBuilder is not thread-safe, it doesn't have the overhead of synchronization, which makes it faster and more efficient than StringBuffer.`
+ * C. StringBuilder is a built-in class in Java `Incorrect: Both StringBuffer and StringBuilder are built-in classes in Java.`【82†source】
+
+**Question 83**
+
+Can we modify a string literal using StringBuffer?
+
+ * A. Yes, we can modify a string literal using StringBuffer `Incorrect: String literals are immutable in Java, so they cannot be modified by StringBuffer or any other class.`
+ * B. No, we cannot modify a string literal using StringBuffer `Correct: String literals are immutable in Java, so they cannot be modified.`
+ * C. It depends on the situation `Incorrect: String literals are always immutable in Java, regardless of the situation.`【83†source】
+
+### Step 08: Introducing Wrapper Classes
+
+**Question 84**
+
+What is the purpose of using Wrapper Classes in Java?
+
+ * A. To access type information about the corresponding primitive type `Incorrect: Wrapper classes in Java are primarily used to convert primitive data types into objects.`
+ * B. To promote primitive data to an object reference type `Correct: Wrapper classes in Java are used to convert primitive data types into objects. This is often necessary because certain Java collections can only handle objects and not primitive types.`
+ * C. To move primitive type data around data structures `Incorrect: While it's true that wrapper classes can help move primitive data around in object-oriented data structures, their primary purpose is to convert primitive types into objects.`【84†source】
+
+**Question 85**
+
+What is Auto-Boxing in Java?
+
+ * A. The process of promoting primitive data to an object reference type `Incorrect: Auto-boxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes.`
+ * B. The process of converting an object reference type to a primitive data type `Incorrect: This process is known as unboxing, not auto-boxing.`
+ * C. The process of converting a primitive data type to an object reference type `Correct: Auto-boxing is the automatic conversion of primitive types to their corresponding object wrapper classes.`【85†source】
+
+**Question 86**
+
+Can we modify the value of a wrapper class once it is assigned?
+
+ * A. Yes, we can modify the value of a wrapper class `Incorrect: Once a value has been assigned to a wrapper class, it cannot be changed.`
+ * B. No, the value of a wrapper class is immutable `Correct: Once a value has been assigned to a wrapper class, it cannot be changed. This is because all wrapper classes in Java are immutable.`
+ * C. It depends on the type of wrapper class being used. `Incorrect: All wrapper classes in Java are immutable, regardless of the type.`【86†source】
+
+### Step 09: Creating Wrapper Objects
+
+**Question 87**
+
+What are Wrapper Classes in Java?
+
+ * A. Classes that provide a mechanism to convert primitive data types into objects `Correct: This is one of the main functions of wrapper classes in Java.`
+ * B. Classes that provide a mechanism to convert objects into primitive data types `Correct: This is one of the main functions of wrapper classes in Java. They allow us to "unwrap" the value of an object into a primitive type through a process known as unboxing.`
+ * C. Both of the above `Correct: Wrapper classes in Java both convert primitive data types
+
+ into objects (known as boxing), and provide a mechanism to convert objects into primitive data types (known as unboxing).`
+ * D. None of the above `Incorrect: Wrapper classes in Java serve both of the functions listed above.`【87†source】
+
+**Question 88**
+
+What is the difference between creating a Wrapper object using 'new' and 'valueOf()'?
+
+ * A. There is no difference `Incorrect: There is a significant difference between these two methods.`
+ * B. 'new' creates a new object every time, whereas 'valueOf()' reuses existing objects with the same value `Correct: The 'new' keyword always creates a new object, while 'valueOf()' may return a cached object for certain ranges of values (particularly small integers).`
+ * C. 'new' reuses existing objects with the same value, whereas 'valueOf()' creates a new object every time `Incorrect: It is 'valueOf()' that may reuse objects, not 'new'.`
+ * D. None of the above `Incorrect: The correct answer is option B.`【88†source】
+
+**Question 89**
+
+Are Wrapper Classes mutable in Java?
+
+ * A. Yes `Incorrect: Wrapper classes in Java are immutable.`
+ * B. No `Correct: Once a value has been assigned to a wrapper class, it cannot be changed.`
+ * C. Depends on the implementation `Incorrect: All wrapper classes in Java are immutable, regardless of the implementation.`
+ * D. None of the above `Incorrect: The correct answer is option B.`【89†source】
+
+### Step 10: Auto-Boxing, And Some Wrapper Constants
+
+**Question 90**
+
+What is Auto-Boxing in Java?
+
+ * A. A feature that provides new functionality to the Java language `Incorrect: While it is true that auto-boxing was a new feature introduced in Java 5, it is not the definition of auto-boxing.`
+ * B. A mechanism to make code more readable `Incorrect: While auto-boxing can make code more readable, that is not its primary function.`
+ * C. A mechanism to upgrade a primitive data type to its corresponding object type `Correct: Auto-boxing is the automatic conversion of primitive types to their corresponding object wrapper classes.`
+ * D. None of the above `Incorrect: The correct answer is option C.`【90†source】
+
+**Question 91**
+
+What is the mechanism used by Auto-Boxing in Java?
+
+ * A. It uses the 'new' operator to create new objects every time `Incorrect: Auto-boxing uses the valueOf() method, not the new operator.`
+ * B. It uses the 'valueOf()' method to create objects `Correct: Auto-boxing uses the valueOf() method to create an instance of the wrapper class for the corresponding primitive type.`
+ * C. It uses the 'toString()' method to create objects `Incorrect: The toString() method is used to convert an object to a string, not to create new objects.`
+ * D. None of the above `Incorrect: The correct answer is option B.`【91†source】
+
+**Question 92**
+
+Are there any constants available on Wrapper Classes in Java to check the size and range of values they can store?
+
+ * A. No `Incorrect: Each wrapper class does indeed contain constants that represent the minimum and maximum values that can be stored.`
+ * B. Yes `Correct: Each wrapper class contains constants MIN_VALUE and MAX_VALUE that represent the minimum and maximum values that can be stored in an object of that type.`
+ * C. Depends on the implementation `Incorrect: All standard wrapper classes in Java contain these constants.`
+ * D.
+
+ None of the above `Incorrect: The correct answer is option B.`【92†source】
+
+### Step 11: The Java Date API Quiz
+
+**Question 93**
+
+What is the main purpose of the Java Date API?
+
+ * a. To perform arithmetic operations on date and time objects `Incorrect: While the Java Date API does allow arithmetic operations on date and time objects, this is not its main purpose.`
+ * b. To provide an interface for date and time classes `Incorrect: The Java Date API provides more than just an interface; it provides a full implementation for handling date and time.`
+ * c. To provide a framework for date and time classes `Correct: The Java Date API is a framework that provides classes for handling date and time in a way that is both easier to understand and more accurate than using just the Date class.`
+ * d. To provide a library for date and time classes `Incorrect: While the Java Date API can be considered a library, the most accurate description is that it is a framework.`【93†source】
+
+**Question 94**
+
+What is the main difference between LocalDate, LocalTime, and LocalDateTime?
+
+ * a. They are used for different purposes `Incorrect: While these classes are used for different purposes, the key difference is what they represent.`
+ * b. They are different classes in Java `Incorrect: While this is technically true, it doesn't describe the functional differences between these classes.`
+ * c. They are used to represent different values for date and time `Correct: LocalDate represents a date (year, month, day), LocalTime represents a time (hour, minute, second, nanosecond), and LocalDateTime represents both a date and a time.`
+ * d. They are used for different date and time formats `Incorrect: While these classes can be used to format dates and times in different ways, the key difference is what they represent.`【94†source】
+
+**Question 95**
+
+What is the difference between the LocalDate.now() and LocalDate.of() methods in the Java Date API?
+
+ * a. LocalDate.now() returns the current date and time, while LocalDate.of() returns a specific date and time `Incorrect: LocalDate.now() returns the current date, not the current date and time.`
+ * b. LocalDate.now() returns the current date, while LocalDate.of() returns a specific date `Correct: LocalDate.now() returns the current date, and LocalDate.of() can be used to create a LocalDate object for a specific date.`
+ * c. LocalDate.now() returns the current time, while LocalDate.of() returns a specific time `Incorrect: LocalDate objects do not contain time information.`
+ * d. LocalDate.now() returns a date and time object, while LocalDate.of() returns a date object `Incorrect: Both methods return LocalDate objects, which contain only date information.`【95†source】
+
+### Step 12: Playing With java.time.LocalDate Quiz
+
+**Question 96**
+
+What information can you retrieve from a LocalDate object?
+
+ * a. Date information such as Day/Month/Year and related attributes `Correct: LocalDate objects contain date information and related attributes, but do not contain any time information.`
+ * b. Time information such as Hour/Minute/Second and related attributes `Incorrect: LocalDate objects do not contain any time information.`
+ * c. Both date and time information `Incorrect: LocalDate objects contain only date information, not time information.`
+ * d. None of the above `Incorrect: The correct answer is option A.`【96†source】
+
+**Question 97**
+
+Are LocalDate, LocalTime, and LocalDateTime objects mutable?
+
+ * a. Yes `Incorrect: Objects of these classes are immutable.`
+ * b. No `Correct: Objects of LocalDate, LocalTime, and LocalDateTime are immutable. Once created, their
+
+ state cannot be changed.`【97†source】
+
+**Question 98**
+
+What is the result of the following code snippet?
+
+```java
+LocalDate today = LocalDate.now();
+LocalDate tomorrow = today.plusDays(1);
+System.out.println(today.isBefore(tomorrow));
+```
+
+ * a. True `Correct: The method `isBefore()` returns true because the date `tomorrow` is after `today`.`
+ * b. False `Incorrect: The correct answer is true.`
+ * c. Error `Incorrect: The code will not result in an error.`【98†source】
+
+### Step 13: Comparing LocalDate Objects Quiz
+
+**Question 99**
+
+What is the purpose of the isBefore() and isAfter() methods in the Java Date API?
+
+ * a. To compare the order of two LocalDate objects `Correct: The `isBefore()` and `isAfter()` methods are used to determine if one LocalDate is before or after another, respectively.`
+ * b. To determine if a LocalDate object is earlier or later than a specific date `Incorrect: While this can be a result of using these methods, it's not the purpose. Their purpose is to compare two LocalDate objects.`
+ * c. To compare the value of two LocalDate objects `Incorrect: These methods do not compare the value of two LocalDate objects. They check the order of the dates.`
+ * d. To determine if a LocalDate object is equal to a specific date `Incorrect: For equality checks, the `isEqual()` method should be used.`【99†source】
+
+**Question 100**
+
+What is the result of the following code snippet?
+
+```java
+LocalDate today = LocalDate.now();
+LocalDate yesterday = LocalDate.of(2018, 01, 31);
+System.out.println(today.isAfter(yesterday));
+```
+
+ * a. True `Correct: Unless this code is run on January 31, 2018, `today` will be after `yesterday`, and so `isAfter()` will return true.`
+ * b. False `Incorrect: Unless this code is run on January 31, 2018, the method `isAfter()` will return true.`
+ * c. Error `Incorrect: The code will not result in an error.`【100†source】
+
+**Question 101**
+
+Can you compare LocalTime and LocalDateTime objects using the isBefore() and isAfter() methods?
+
+ * a. Yes `Correct: The `isBefore()` and `isAfter()` methods are available in both LocalTime and LocalDateTime classes.`
+ * b. No `Incorrect: The correct answer is yes.`【101†source】
\ No newline at end of file
diff --git a/00-Quiz-Explanation/Q11-ObjectOrientedProgrammingAgain.md b/00-Quiz-Explanation/Q11-ObjectOrientedProgrammingAgain.md
new file mode 100644
index 00000000..5aa1562f
--- /dev/null
+++ b/00-Quiz-Explanation/Q11-ObjectOrientedProgrammingAgain.md
@@ -0,0 +1,285 @@
+### Step 01: Objects Revisited - State And Behavior
+
+**Question 1: What defines an object's state?**
+
+- A. Its methods `Incorrect: Methods define the behavior of an object, not its state.`
+- B. Its behavior `Incorrect: Behavior is how an object acts, but it doesn't define its state.`
+- C. Its attributes `Correct: The state of an object is determined by its attributes or properties.`
+
+**Question 2: What delivers messages to an object?**
+
+- A. Attributes `Incorrect: Attributes don't deliver messages; they store state information.`
+- B. Methods `Correct: Methods are used to send messages to an object to perform certain actions.`
+- C. Constructors `Incorrect: Constructors are used to initialize an object, not to send messages.`
+
+**Question 3: What is the effect of behavior on an object's state?**
+
+- A. No effect `Incorrect: Behavior, defined by methods, can affect an object's state.`
+- B. Positive effect `Incorrect: The term "positive effect" is not precise in this context.`
+- C. Negative effect `Incorrect: The term "negative effect" is not precise in this context.`
+
+### Step 02: Managing class state
+
+**Question 1: What corresponds to the state of a class?**
+
+- A. Member variables `Correct: Member variables hold the state of an object of a class.`
+- B. Methods `Incorrect: Methods define the behavior of the objects, not their state.`
+- C. Constructors `Incorrect: Constructors are used to initialize an object, not to define its state.`
+
+**Question 2: What is the purpose of constructors in a class?**
+
+- A. To define behavior `Incorrect: Constructors are used to initialize an object, not to define its behavior.`
+- B. To create objects `Correct: Constructors are used to create and initialize objects of a class.`
+- C. To set attributes `Incorrect: Although constructors can be used to set attribute values, their primary purpose is to create objects.`
+
+**Question 3: What is the purpose of the toString() method in a class?**
+
+- A. To define behavior `Incorrect: The toString() method does not define behavior.`
+- B. To create objects `Incorrect: The toString() method is used to provide a String representation of an object, not to create objects.`
+- C. To provide a string representation of the object's state `Correct: The toString() method provides a string representation of an object's state.`
+
+### Step 03: Augmenting Fan With Behavior
+
+**Question 1: What is the state attribute that needs to be exposed to change by Fan object users?**
+
+- A. make `Incorrect: "make" is not typically changed by users.`
+- B. color `Incorrect: "color" is not typically changed by users.`
+- C. isOn `Correct: Users need to be able to change whether the fan is on or off.`
+- D. speed `Correct: Users need to be able to change the speed of the fan.`
+
+**Question 2: What is the purpose of the switchOn() and switchOff() methods in the Fan class?**
+
+- A. To toggle the isOn state attribute `Correct: These methods are used to change the "isOn" state attribute of a Fan object.`
+- B. To toggle the speed state attribute `Incorrect: These methods don't directly change the speed state attribute.`
+- C. To create a new Fan object `Incorrect: These methods are used to modify the state of an existing Fan object, not to create a new one.`
+
+**Question 3: What is the
+
+ purpose of the setSpeed() method in the Fan class?**
+
+- A. To toggle the isOn state attribute `Incorrect: This method doesn't change the "isOn" state attribute.`
+- B. To toggle the speed state attribute `Correct: This method is used to set the speed of the Fan.`
+- C. To create a new Fan object `Incorrect: This method is used to modify the state of an existing Fan object, not to create a new one.`
+
+
+**Step 04: Programming Exercise PE-OOP-01**
+
+**Question 1: What are the state attributes of a Rectangle object?**
+- A. Length and width `Correct: A rectangle is defined by its length and width.`
+- B. Height and width `Incorrect: Height is not typically a characteristic used to define a rectangle.`
+- C. Length and breadth `Incorrect: The term "breadth" is less commonly used to describe a rectangle's dimensions.`
+
+**Question 2: What is the purpose of the area() method in the Rectangle class?**
+- A. To calculate the perimeter of the rectangle `Incorrect: The area() method calculates the area, not the perimeter.`
+- B. To calculate the area of the rectangle `Correct: The area() method calculates the area of a rectangle.`
+- C. To set the length of the rectangle `Incorrect: The area() method doesn't set any attribute; it calculates a value.`
+
+**Question 3: What is the purpose of the perimeter() method in the Rectangle class?**
+- A. To calculate the perimeter of the rectangle `Correct: The perimeter() method calculates the perimeter of a rectangle.`
+- B. To calculate the area of the rectangle `Incorrect: The perimeter() method calculates the perimeter, not the area.`
+- C. To set the length of the rectangle `Incorrect: The perimeter() method doesn't set any attribute; it calculates a value.`
+
+**Step 06: Understanding Object Composition**
+
+**Question 1: What are the state attributes of the Fan class?**
+- A) make, radius, color, isOn, speed `Correct: These are the attributes that define the state of a Fan object.`
+- B) brand, diameter, hue, isRunning, velocity `Incorrect: These attributes may define similar features, but the specific names differ from those in the Fan class.`
+- C) manufacturer, size, tone, isActive, rate `Incorrect: These attributes may define similar features, but the specific names differ from those in the Fan class.`
+
+**Question 2: What is object composition?**
+- A) Combining primitive types into a complex object `Incorrect: While this is a form of composition, it's not specific to object composition in OOP.`
+- B) Creating multiple objects of the same type `Incorrect: This doesn't define object composition.`
+- C) Combining different objects to create a more complex object `Correct: Object composition involves using different objects to build more complex ones.`
+
+**Question 3: What is the purpose of constructors in object composition?**
+- A) To create new objects of a class `Correct: Constructors are used to create and initialize new objects.`
+- B) To modify the state of an object `Incorrect: Constructors initialize an object's state, not modify it after creation.`
+- C) To add behaviors to an object `Incorrect: While constructors can assign methods, their main purpose is to create and initialize new objects.`
+
+**Step 07: Programming Exercise PE-OOP-02**
+
+**Question 1: What are the attributes of the Book class?**
+- A) Id, Name, Author `Correct: These are the attributes that define the state of a Book object.`
+- B) Title, Author, Description `Incorrect: While these could be valid attributes for a Book, they do not match the provided Book class structure.`
+- C) Id, Title, Author `Incorrect: While these could be valid attributes for a Book, they do not match the provided Book class structure.`
+
+**Question 2: What is the purpose of the Review class?**
+- A) To manage Books `Incorrect: The Review class is meant to manage reviews, not
+
+ books.`
+- B) To manage Authors `Incorrect: The Review class is meant to manage reviews, not authors.`
+- C) To manage reviews associated with a Book `Correct: The Review class is used to manage and associate reviews with a Book.`
+
+**Question 3: What is the output of the following code?**
+
+```java
+Book book = new Book(123, "Object Oriented Programming With Java", "Ranga");
+book.addReview(new Review(10, "Great Book", 4));
+book.addReview(new Review(101, "Awesome", 5));
+System.out.println(book);
+```
+
+- A) Book-123, Object Oriented Programming With Java, Ranga, [(Review-10, Great Book", 4), (Review-101, Awesome, 5)] `Correct: This is the expected output based on the provided code.`
+- B) Book-123, Object Oriented Programming With Java, Ranga, [(10, Great Book, 4), (101, Awesome, 5)] `Incorrect: The output format includes the word "Review-" before the review IDs.`
+- C) Book-123, Object Oriented Programming With Java, Ranga, [(Review-10, Great Book", 5), (Review-101, Awesome, 4)] `Incorrect: The review ratings do not match those given in the code.`
+
+**Step 07: The Need For Inheritance**
+
+**Question 1: What is Inheritance in Object Oriented Programming?**
+- A) A mechanism of code reuse `Correct: Inheritance allows the reuse of code from one class in another.`
+- B) A mechanism to create new objects `Incorrect: While inheritance can be part of creating new objects, it primarily refers to code reuse between classes.`
+- C) A mechanism to modify existing objects `Incorrect: Inheritance involves classes and their relationships, not modifying existing objects.`
+
+**Question 2: What is a superclass in Inheritance relationship?**
+- A) A class that extends another class `Incorrect: A superclass is the class that gets extended, not the one that does the extending.`
+- B) A class that inherits from another class `Incorrect: A superclass is the class that is inherited from, not the class that does the inheriting.`
+- C) A class that is neither extended nor inherited `Incorrect: In the context of inheritance, a superclass is a class that is inherited from.`
+
+**Question 3: How does a subclass access fields and methods of its superclass?**
+- A) By using the keyword 'super' `Correct: In Java, the 'super' keyword is used to refer to the superclass of the current object.`
+- B) By using the keyword 'this' `Incorrect: The 'this' keyword refers to the current object, not its superclass.`
+- C) By using the keyword 'extends' `Incorrect: The 'extends' keyword is used to establish an inheritance relationship, not to access superclass members.`
+
+**Step 12: Constructors, And Calling super()**
+
+**Question 1: What does the super keyword do in Java?**
+- a. Allows a subclass to access the attributes present in the superclass `Correct: The super keyword in Java is used to refer to the immediate parent class instance variable.`
+- b. Creates a new instance of a superclass `Incorrect: The super keyword does not create new instances; it refers to the superclass.`
+- c. Allows a superclass to access the attributes present in the subclass `Incorrect: The super keyword is used in the context of a subclass referring to its superclass, not the other way around.`
+
+**Step 13: Multiple Inheritance, Reference Variables And instanceof**
+
+**Question 1: Can a Java class directly inherit from two or more classes?**
+- a. Yes `Incorrect: Java doesn't support multiple inheritance directly due to the "Diamond Problem".`
+- b. No `Correct: A class in Java can directly inherit from only one class.`
+
+**Question 2: What is the output of the Dog object's toString() method in Snippet-02?**
+- a. Dog@23a6e47f `Correct: If not overridden, the toString() method returns the class name followed by the "@" sign and the unsigned hexadecimal representation of the hash code of the object.`
+- b. Pet Groom `Incorrect: The output of toString() wouldn't be a string literal unless explicitly defined in the Dog class.`
+- c. null `Incorrect: The toString() method will not return null unless explicitly defined to do so.`
+
+**Question 3: What is the output of the instanceof operator when pet instanceof String is executed in Snippet-02?**
+- a. Pet cannot be converted to java.lang.String `Correct: The 'instanceof' operator in Java is used to test whether an object is an instance of a specific class or not. In this case, 'pet' is not a String.`
+- b. true `Incorrect: The pet is not an instance of String.`
+- c. false `Incorrect: It throws a compile-time error because 'pet' can't be compared with 'String'.`
+
+**Step 14: Introducing Abstract Classes**
+
+**Question 1: What is an abstract method?**
+- A) A method without any parameters `Incorrect: Abstract methods are defined by lack of implementation, not lack of parameters.`
+- B) A method with a method definition `Incorrect: Abstract methods lack a method definition.`
+- C) A method without a method definition `Correct: Abstract methods in Java are declared without a body.`
+
+**Question 2: Can an abstract class be instantiated?**
+- A) Yes `Incorrect: Abstract classes in Java cannot be instantiated.`
+- B) No `Correct: Abstract classes can't be instantiated directly; they can only be subclassed.`
+
+**Question 3: What is a concrete class?**
+- A) A class that can be instantiated `Correct: A concrete class is a class that can be instantiated.`
+- B) A class that cannot be instantiated `Incorrect: A concrete class, unlike an abstract class, can be instantiated.`
+- C) A class with a method definition `Incorrect: While a concrete class does have defined methods, it's primarily characterized by its ability to be instantiated.`
+
+**Step 15: Abstract Classes - Design Aspects**
+
+**Question 1: What is the purpose of an abstract class?**
+- A) To provide implementation for all its methods `Incorrect: Abstract classes don't provide full implementation; they contain one or more abstract methods.`
+- B) To declare methods without providing implementation `Correct: Abstract classes declare methods without providing their implementation.`
+- C) To create a hierarchy of classes `Incorrect: While abstract classes do play a role in class hierarchies, their primary purpose is to declare methods without providing implementation.`
+
+**Question 2: What is the advantage of using an abstract class to create a recipe hierarchy?**
+- A) It allows for the order of steps to be defined `Incorrect: The order of steps is not inherently defined by using an abstract class.`
+- B) It allows for the implementation of each step to be defined by the sub-classes `Correct: Abstract classes allow subclasses to provide specific implementations of abstract methods.`
+- C) It allows for the creation of multiple
+
+ recipe types easily `Incorrect: While it might be true, the main advantage is in the encapsulation of a general process structure while enabling specific step implementations.`
+
+**Question 3: Which design pattern is used in the recipe hierarchy example?**
+- A) Observer pattern `Incorrect: The observer pattern is a design pattern where an object maintains a list of dependents and notifies them of any changes. It's not used here.`
+- B) Decorator pattern `Incorrect: The decorator pattern allows behavior to be added to an individual object, either statically or dynamically, without affecting the behavior of other objects from the same class. It's not used here.`
+- C) Template method pattern `Correct: The template method pattern is a behavioral design pattern that defines the program skeleton in an operation but defers some steps to subclasses.`
+
+**Step 16: Abstract Classes - Puzzles**
+
+**Question 1: Can an abstract class be created without any abstract member methods?**
+- A) Yes `Correct: Abstract classes can exist without abstract methods. They can't be instantiated, but they can include actual method implementations.`
+- B) No `Incorrect: It's not required for an abstract class to have abstract methods, although it's common.`
+
+**Question 2: Can an abstract class have member variables?**
+- A) Yes `Correct: Abstract classes can have member variables like any other classes.`
+- B) No `Incorrect: Abstract classes, like any other class, can have member variables.`
+
+**Question 3: Can an abstract class have non-abstract methods?**
+- A) Yes `Correct: Abstract classes can have both abstract and non-abstract methods.`
+- B) No `Incorrect: Abstract classes can include fully implemented (non-abstract) methods.`
+
+**Step 17: Introducing Interfaces**
+
+**Question 1: What is an interface in Java?**
+- A) A class that provides implementation for all its methods `Incorrect: Interfaces do not provide implementation for any methods, only their signatures.`
+- B) A class that declares methods without providing implementation `Incorrect: While interfaces do declare methods without implementation, they are not classes.`
+- C) A class that cannot be instantiated but can be implemented by other classes `Correct: An interface can't be instantiated, but other classes can implement it to define the methods.`
+
+**Question 2: Who provides the implementation of methods declared in an interface?**
+- A) The interface itself `Incorrect: Interfaces in Java do not provide implementation for methods.`
+- B) The implementing classes `Correct: The classes implementing the interface provide the method implementation.`
+- C) The superclass of the interface `Incorrect: Interfaces do not have superclasses. Method implementation is provided by the classes implementing the interface.`
+
+**Question 3: How can an interface be used to enforce a contract for its implementors?**
+- A) By providing default implementations for its methods `Incorrect: While interfaces can provide default methods, the primary means of enforcing a contract is by declaring methods without providing implementation.`
+- B) By declaring methods without providing implementation `Correct: Interfaces enforce a contract by declaring methods without providing implementation. The implementing classes are obliged to provide the implementation.`
+- C) By creating a hierarchy of interfaces `Incorrect: While interfaces can inherit from other interfaces, the primary way they enforce a contract is by declaring methods without implementation.`
+
+**Step 18: Using Interfaces To Design APIs**
+
+**Question 1: Which of the following is not a way to ensure compatibility between teams working on different parts of an application?**
+- a) Define an interface for the external team to implement `Incorrect: Defining interfaces is indeed a good way to ensure compatibility, as it sets the expectations for method signatures
+
+.`
+- b) Work on the parts of the application simultaneously `Incorrect: Working simultaneously doesn't inherently ensure compatibility; clear contracts and communication do.`
+- c) Define an algorithm for the external team to implement directly into the application `Correct: This approach does not ensure compatibility as it lacks a defined contract for how components should interact.`
+
+**Question 2: What is the purpose of defining an interface between two teams working on different parts of an application?**
+- a) To allow teams to work independently without worrying about compatibility issues `Incorrect: While interfaces allow teams to work independently, they primarily serve to define a contract between the two teams.`
+- b) To define a contract between the two teams `Correct: Interfaces provide a defined contract of methods, which facilitates the independent work of different teams on separate components.`
+- c) To ensure that both teams use the same programming language `Incorrect: An interface doesn't enforce the use of a specific programming language, it's about defining the methods that classes implementing it should have.`
+
+**Question 3: Which of the following is an implementation of the ComplexAlgorithm interface?**
+- a) OneComplexAlgorithm `Incorrect: Without more context, we can't confirm if "OneComplexAlgorithm" is an implementation of the ComplexAlgorithm interface.`
+- b) ActualComplexAlgorithm `Incorrect: Without more context, we can't confirm if "ActualComplexAlgorithm" is an implementation of the ComplexAlgorithm interface.`
+- c) Both a and b `Correct: Assuming that both "OneComplexAlgorithm" and "ActualComplexAlgorithm" implement the ComplexAlgorithm interface.`
+
+**Step 19: Interfaces - Puzzles And Interesting Facts**
+
+**Question 1: Which of the following is true about interfaces in Java?**
+- a) An interface can be extended by another interface `Correct: Interfaces can extend one or more other interfaces.`
+- b) An implementation of an interface needs to implement all methods declared in the interface and its super interfaces `Incorrect: While an implementation class generally needs to implement all methods of an interface, if the class is abstract, it doesn't have to implement all methods.`
+- c) Interfaces can have member variables `Incorrect: Interfaces can have constants (static final variables) but not regular member variables.`
+
+**Question 2: Which of the following is not a way to provide a default implementation for a method in an interface?**
+- a) Include the keyword "default" in the method signature `Incorrect: This is indeed one way to provide a default method in an interface.`
+- b) Provide a body for the method in the interface definition `Incorrect: This is another way to provide a default method in an interface.`
+- c) Override the method in the implementation class `Correct: Overriding the method in the implementation class is not providing a default implementation. It's providing a class-specific implementation.`
+
+**Question 3: Why is providing default method implementations useful in building and extending frameworks?**
+- a) It allows for a new method to be added to an interface without breaking the implementation classes `Correct: Default methods enable new functionality to be added to the interfaces of libraries and ensure binary compatibility with code written for older versions of those interfaces.`
+- b) It ensures that all implementation classes have the same behavior for the default method `Incorrect: While this might happen, the main purpose is to allow extension without breaking existing implementations.`
+- c) It reduces the amount of code needed to implement the interface `Incorrect: The amount of code is not necessarily reduced as the default method can still be overridden.`
+
+**Step 20: abstract class And interface : A Comparison**
+
+**Question 1: Which of the following is a primary use case for an interface?**
+- a) Generalizing behavior by
+
+ defining a set of methods that a class must implement `Correct: This is indeed a primary use case for interfaces.`
+- b) Providing default implementations for methods `Incorrect: While interfaces can provide default method implementations, it's not their primary use case.`
+- c) Defining member variables `Incorrect: Interfaces in Java can't define member variables (only constants).`
+
+**Question 2: Which of the following is a primary use case for an abstract class?**
+- a) Providing partial implementation for a class `Correct: This is a primary use case for abstract classes. They allow for the definition of both abstract and non-abstract methods.`
+- b) Defining a contract for methods that a class must implement `Incorrect: This is a primary use case for interfaces, not abstract classes.`
+- c) Extending multiple classes `Incorrect: In Java, a class (including abstract class) can't extend multiple classes directly.`
+
+**Question 3: Which of the following can be instantiated?**
+- a) An interface `Incorrect: Interfaces cannot be instantiated.`
+- b) An abstract class `Incorrect: Abstract classes cannot be instantiated.`
+- c) A concrete class `Correct: A concrete class, unlike interfaces or abstract classes, can be instantiated.`
\ No newline at end of file
From a42530a7f8fcdeb8c40dde6b7c81c3548ee066fe Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sun, 21 May 2023 13:38:32 +0530
Subject: [PATCH 160/178] Update
Q02-IntroductionToMethods-MultiplicationTable.md
---
.../Q02-IntroductionToMethods-MultiplicationTable.md | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/00-Quiz-Explanation/Q02-IntroductionToMethods-MultiplicationTable.md b/00-Quiz-Explanation/Q02-IntroductionToMethods-MultiplicationTable.md
index fc25ab5c..59406465 100644
--- a/00-Quiz-Explanation/Q02-IntroductionToMethods-MultiplicationTable.md
+++ b/00-Quiz-Explanation/Q02-IntroductionToMethods-MultiplicationTable.md
@@ -169,7 +169,7 @@ What would happen if you try to call the method `sayHelloWorld` with a string ar
-``### Question 11
+### Question 11
What is method overloading in Java?
@@ -248,4 +248,4 @@ What is the benefit of using a return mechanism in a method?
- A) It allows the method to print the result of the computation. `Incorrect: Printing is not the job of the return statement, rather it returns the result to the calling code`.
- B) It enables sharing computed results with other code and methods, and improves breaking down a problem into sub-problems. `Correct: The return mechanism enables the reuse of computed results in other parts of the code`.
-- C) It simplifies the syntax of the method. `Incorrect: While the use of return can make a method more readable, it does not necessarily simplify the syntax`【22†source】.
\ No newline at end of file
+- C) It simplifies the syntax of the method. `Incorrect: While the use of return can make a method more readable, it does not necessarily simplify the syntax`【22†source】.
From f5556db54f669e29c3a630fa84d7285b5d15c80c Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sun, 21 May 2023 19:32:53 +0530
Subject: [PATCH 161/178] .
---
00-Quiz-Explanation/Q12-Collections.md | 300 +++++++++++++++++++++++++
1 file changed, 300 insertions(+)
create mode 100644 00-Quiz-Explanation/Q12-Collections.md
diff --git a/00-Quiz-Explanation/Q12-Collections.md b/00-Quiz-Explanation/Q12-Collections.md
new file mode 100644
index 00000000..c53921a6
--- /dev/null
+++ b/00-Quiz-Explanation/Q12-Collections.md
@@ -0,0 +1,300 @@
+**Step 00: Collections Overview**
+
+**Question 1: What are Collections in Java?**
+- a) Collections is a package in Java `Incorrect: While there is a Collections class in Java, it is not a package.`
+- b) Collections are in-built implementations available to support dynamic data structures in Java programs. `Correct: Collections in Java are data structures that hold objects and provide various operations on data including insertion, deletion, sorting, etc.`
+- c) Collections are used to sort static data structures in Java programs. `Incorrect: Collections provide more than just sorting; they provide a variety of operations for managing groups of objects.`
+
+**Question 2: What are some common collections?**
+- a) List, Set, Queue, Map `Correct: These are some of the common interfaces in the Java Collections Framework.`
+- b) Stack, Heap, Tree `Incorrect: These are data structures but not necessarily collection types in Java.`
+- c) Graph, Queue, Hash Table `Incorrect: While Queue is a collection in Java, Graph and Hash Table aren't.`
+
+**Question 3: What is List Interface used for?**
+- a) List Interface is used to implement an ordered collection in Java programs. `Correct: List interface is used for collections that have a specific order and can contain duplicate elements.`
+- b) List Interface is used to implement an unordered collection in Java programs. `Incorrect: Lists are ordered collections.`
+- c) List Interface is used to implement a stack data structure in Java programs. `Incorrect: While a List could technically be used to implement a Stack, it is not its primary purpose.`
+
+**Step 00: Comparator for ArrayList.sort()**
+
+```java
+package collections;
+import java.util.Collections;
+import java.util.List;
+import java.util.ArrayList;
+import java.util.Comparator;
+
+public class StudentsCollectionRunner {
+ public static void main(String[] args) {
+ List students = List.of(new Student(1, "Ranga"),
+ new Student(100, "Adam"),
+ new Student(2, "Eve"));
+
+ ArrayList studentsAl = new ArrayList<>(students);
+ System.out.println(studentsAl);
+ studentsAl.sort(new AscStudentComparator());
+ System.out.println("Asc : " + studentsAl);
+ studentsAl.sort(new DescStudentComparator());
+ System.out.println("Desc : " + studentsAl);
+ }
+}
+```
+
+**Question 1: What is the purpose of the StudentsCollectionRunner class?**
+- a) To sort a list of students by their names `Incorrect: The class sorts students by their IDs, not names.`
+- b) To sort a list of students by their IDs in ascending and descending order `Correct: The class uses comparators to sort a list of students by their IDs.`
+- c) To create a new student object `Incorrect: Although new Student objects are created, the primary purpose is to sort them.`
+
+**Question 2: What is the output of the following code?**
+
+```java
+ArrayList studentsAl = new ArrayList<>(students);
+studentsAl.sort(new DescStudentComparator());
+System.out.println("Desc : " + studentsAl);
+```
+
+- a) [100 Adam, 2 Eve, 1 Ranga] `Correct: The code sorts the Student objects in descending order of their IDs.`
+- b) [1 Ranga, 2 Eve, 100 Adam] `Incorrect: This would be the output for ascending order sort, not descending.`
+- c) [100 Adam, 1 Ranga, 2 Eve] `Incorrect: The order does not match the descending sort of IDs.`
+
+**Question 3: Which interface is used to provide the custom sorting order for studentsAl?**
+- a) Comparable `Incorrect: Comparable is used for natural ordering, not custom ordering.`
+- b) Comparator `Correct: Comparator interface is used to define custom ordering.`
+- c) Iterable `Incorrect: Iterable interface is not used for ordering.`
+
+**Step 01: The Set interface**
+
+**Question 1: How does the Java Set interface handle duplicates?**
+- a) It stores all duplicate elements `Incorrect: Set interface doesn't allow duplicates.`
+- b) It only stores the first occurrence of an element `Correct: In a Set, duplicate elements are not stored.`
+- c) It throws an exception when duplicates are added `Incorrect: The Set interface doesn't throw exceptions when attempting to add duplicate elements
+
+, it just ignores them.`
+
+**Question 2: What does the equals method need to return for two objects to be considered equal and treated as duplicates by a Set implementation?**
+- a) true `Correct: If equals method returns true, the objects are considered equal and treated as duplicates.`
+- b) false `Incorrect: If equals method returns false, the objects are considered unequal.`
+- c) It depends on the specific implementation `Incorrect: The equality check depends on the equals method returning true.`
+
+**Question 3: What is one feature that is not provided by the Set interface?**
+- a) Iteration over elements `Incorrect: The Set interface allows iteration over its elements.`
+- b) Removing elements `Incorrect: The Set interface allows removing elements.`
+- c) Positional element access `Correct: The Set interface does not support positional access like Lists do.`
+
+**Step 02: Understanding Data Structures**
+Hash Table
+**Question 1: What is a hash table?**
+- a) A table of sorted elements `Incorrect: Hash table is not about sorted elements.`
+- b) A table of unique elements `Incorrect: While a Hash table does not allow duplicates, this description is too narrow.`
+- c) A data structure that combines efficient element access and element insertion/deletion `Correct: A Hash table is a data structure that uses hash functions for efficient element access and operations.`
+
+**Question 2: What is a bucket in a hash table?**
+- a) A slot in the table where elements are inserted and chained together `Correct: In a hash table, a bucket is where elements with the same hash value are stored.`
+- b) A subset of elements in the table that share the same hash value `Incorrect: It's not about subsets but about specific slots in the table.`
+- c) A container used to store the hash function `Incorrect: A bucket doesn't store the hash function.`
+
+**Step 17: PriorityQueue**
+```java
+Queue queue = new PriorityQueue<>();
+queue.addAll(List.of("Apple", "Zebra", "Monkey", "Cat"));
+```
+
+**Question 1: What is the output of queue.poll() after adding the elements to the PriorityQueue?**
+- a) "Apple" `Correct: The PriorityQueue follows natural ordering, so the first element to be polled would be "Apple".`
+- b) "Zebra" `Incorrect: "Zebra" is not the first element in natural ordering.`
+- c) "Cat" `Incorrect: "Cat" is not the first element in natural ordering.`
+- d) "Monkey" `Incorrect: "Monkey" is not the first element in natural ordering.`
+
+**Question 2: What is the default ordering of elements in a PriorityQueue?**
+- a) Descending order `Incorrect: The default ordering is not descending.`
+- b) Ascending order based on natural order `Correct: PriorityQueue orders elements in their natural ordering by default.`
+- c) Insertion order `Incorrect: PriorityQueue does not maintain insertion order.`
+- d) Random order `Incorrect: PriorityQueue does not use a random order.`
+
+**Question 3: What is the output of queue.poll() after executing queue.poll() three times?**
+- a) "Cat" `Incorrect: "Cat" would have already been removed after the second poll.`
+- b) "Monkey" `Incorrect: "Monkey" would have already been removed after the third poll.`
+- c) "Zebra" `Incorrect: "Zebra" is not the fourth element in the queue.`
+- d) null `Correct: After polling three times, the fourth poll would return null because the queue is empty.`
+
+
+
+**Step 18: Custom Priority PriorityQueue**
+
+```java
+Queue queue = new PriorityQueue<>(new StringLengthComparator());
+queue.addAll(List.of("Zebra", "Monkey", "Cat"));
+```
+
+**Question 1: What is the output of queue.poll() after adding the elements to the PriorityQueue?**
+- a) "Zebra" `Incorrect: With the custom comparator, "Zebra" is not the shortest string.`
+- b) "Monkey" `Incorrect: With the custom comparator, "Monkey" is not the shortest string.`
+- c) "Cat" `Correct: With the custom comparator sorting by string length, "Cat" is the shortest and therefore polled first.`
+- d) null `Incorrect: The queue is not empty at this point.`
+
+**Question 2: What interface must be implemented to specify a custom priority order in a PriorityQueue?**
+- a) Comparable `Incorrect: Comparable is used for natural ordering, not custom ordering.`
+- b) Comparator `Correct: Comparator interface is used to define custom ordering.`
+- c) PriorityQueue `Incorrect: PriorityQueue is a class, not an interface for custom ordering.`
+- d) Queue `Incorrect: Queue is a broader interface, not specifically for custom ordering.`
+
+**Question 3: What is the output of the following code snippet after executing queue.poll() three times?**
+```java
+Queue queue = new PriorityQueue<>(new StringLengthComparator());
+queue.addAll(List.of("Zebra", "Monkey", "Cat"));
+queue.poll();
+queue.poll();
+queue.poll();
+queue.poll();
+```
+
+- a) null `Correct: After polling three times, the fourth poll would return null because the queue is empty.`
+- b) "Cat" `Incorrect: "Cat" would have already been removed after the first poll.`
+- c) "Monkey" `Incorrect: "Monkey" would have already been removed after the second poll.`
+- d) "Zebra" `Incorrect: "Zebra" would have already been removed after the third poll.`
+
+**Step 19: Basic Map Operations**
+```java
+Map map = Map.of("A", 3, "B", 5, "Z", 10);
+```
+
+**Question 1: What is the size of map?**
+- A. 3 `Correct: The map contains three key-value pairs, hence the size is 3.`
+- B. 4 `Incorrect: The map only has three key-value pairs.`
+- C. 5 `Incorrect: The map only has three key-value pairs.`
+- D. 6 `Incorrect: The map only has three key-value pairs.`
+
+**Question 2: What is the value associated with the key "Z" in map?**
+- A. 3 `Incorrect: The value associated with the key "Z" is 10.`
+- B. 5 `Incorrect: The value associated with the key "Z" is 10.`
+- C. 10 `Correct: The key "Z" is associated with the value 10.`
+- D. null `Incorrect: There is a value associated with the key "Z".`
+
+**Question 3: What is the output of map.containsValue(4)?**
+- A. true `Incorrect: The map does not contain the value 4.`
+- B. false `Correct: The map does not contain the value 4.`
+- C. compilation error `Incorrect: The method call is valid and will not result in a compilation error.`
+- D. runtime error `Incorrect: The method call is valid and will not result in a runtime error.`
+
+**Step 20: Mutable Maps**
+```java
+Map map = Map.of("A", 3, "B", 5, "Z", 10);
+Map hashMap = new HashMap<>(map);
+```
+
+**Question 1: What is the output of hashMap.put("F", 5)?**
+- A. 5 `Incorrect: The put() method returns the previous value associated with the key, or null if there was no mapping for the key.`
+- B. null `Correct: There was no previous mapping for the key "F".`
+- C. "F" `Incorrect: The put() method does not return the key.`
+- D. compilation error `Incorrect: The code is valid and will not result in a compilation error.`
+
+**Step 21: Map Implementations**
+
+```java
+HashMap hashMap = new HashMap<>();
+hashMap.put("Z", 5);
+hashMap.put("A", 15);
+hashMap.put("F", 25);
+hashMap.put("L", 250);
+hashMap // {A=15, F=25, Z=5, L=250}
+
+LinkedHashMap linkedHashMap = new LinkedHashMap<>();
+linkedHashMap.put("Z", 5);
+linkedHashMap.put("A", 15);
+linkedHashMap.put("F", 25);
+linkedHashMap.put("L", 250);
+linkedHashMap // {Z=5, A=15, F=25, L=250}
+
+TreeMap treeMap = new TreeMap<>();
+treeMap.put("Z", 5);
+treeMap.put("A", 15);
+treeMap.put("F", 25);
+treeMap.put("L", 250);
+treeMap // {A=15, F=25, L=250, Z=5}
+```
+
+**Question 1: Which of the following map implementations maintains natural sorted order of the keys?**
+- A. HashMap `Incorrect: HashMap does not maintain a natural sorted order.`
+- B. LinkedHashMap `Incorrect: LinkedHashMap maintains the order of insertion, not natural sorted order.`
+- C. TreeMap `Correct: TreeMap maintains a natural sorted order.`
+
+**Question 2: Which of the following map implementations does not guarantee the order of stored elements?**
+- A. HashMap `Correct: HashMap does not maintain any specific order.`
+- B. LinkedHashMap `Incorrect: LinkedHashMap maintains the order of insertion.`
+- C. TreeMap `Incorrect: TreeMap maintains a natural sorted order.`
+
+**Question 3: Which of the following map implementations maintains insertion order of elements?**
+- A. HashMap `Incorrect: HashMap does not maintain any specific order.`
+- B. LinkedHashMap `Correct: LinkedHashMap maintains the order of insertion.`
+- C. TreeMap `Incorrect: TreeMap maintains a natural sorted order, not the order of insertion.`
+
+**Step 22: Basic Map Operations**
+
+```java
+Map map = Map.of("A", 3, "B", 5, "Z", 10);
+map // {Z=10, A=3, B=5}
+map.get("Z") // 10
+map.get("A") // 3
+map.get("C") // null
+map.size() // 3
+map.isEmpty() // false
+map.containsKey("A") // true
+map.containsKey("F") // false
+map.containsValue(3) // true
+map.containsValue(4) // false
+map.keySet() // [Z, A, B]
+map.values() // [10, 3, 5]
+```
+
+**Question 1: What is the output of the following code?**
+```java
+Map map = Map.of("A", 1, "B", 2, "C", 3);
+map.put("D", 4);
+System.out.println(map.size());
+```
+
+- A. 3 `Incorrect: The map is immutable, the put() operation would result in a compilation error.`
+- B. 4 `Incorrect: The map is immutable, the put() operation would result in a compilation error.`
+- C. 5 `Incorrect: The map is immutable, the put() operation would result in a compilation error.`
+- D. Compilation error `Correct: Map created with Map.of() is immutable, any modification attempts would result in a compilation
+
+ error.`
+
+**Question 2: What is the output of the following code?**
+```java
+Map map = Map.of("A", 1, "B", 2, "C", 3);
+System.out.println(map.containsValue(2));
+```
+- A. true `Correct: The map does contain the value 2.`
+- B. false `Incorrect: The map contains the value 2.`
+- C. Compilation error `Incorrect: The code is valid and will not result in a compilation error.`
+
+**Question 3: What is the output of the following code?**
+```java
+Map map = Map.of("A", 1, "B", 2, "C", 3);
+System.out.println(map.keySet());
+```
+- A. ["A", "B", "C"] `Correct: The map contains the keys "A", "B", and "C".`
+- B. [1, 2, 3] `Incorrect: keySet() returns a set of keys, not values.`
+- C. ["A"], ["B"], ["C"] `Incorrect: keySet() returns a single set, not separate sets for each key.`
+- D. Compilation error `Incorrect: The code is valid and will not result in a compilation error.`
+
+**Step 23: Sorting Collections**
+
+**Question 1: Which data structure always maintains the natural sorted order of its elements?**
+- a) HashSet `Incorrect: HashSet does not maintain any specific order.`
+- b) LinkedHashMap `Incorrect: LinkedHashMap maintains insertion order, not natural sorted order.`
+- c) TreeMap `Correct: TreeMap maintains a natural sorted order of its keys.`
+- d) PriorityQueue `Incorrect: PriorityQueue maintains a natural order but not necessarily sorted.`
+
+**Question 2: Which interface provides a contract to implement collections of elements in the form of (key, value) pairs?**
+- a) List `Incorrect: List represents an ordered collection (also known as a sequence).`
+- b) Set `Incorrect: Set is a collection that cannot contain duplicate elements.`
+- c) Queue `Incorrect: Queue typically orders elements in a FIFO (first-in-first-out) manner.`
+- d) Map `Correct: Map is an object that maps keys to values. A map cannot contain duplicate keys.`
+
+**Question 3: What is the main difference between a HashMap and a TreeMap?**
+- a) HashMap stores elements in natural sorted order while TreeMap is unordered. `Incorrect: It's the other way around. TreeMap maintains natural sorted order, while HashMap is unordered.`
+- b) HashMap maintains insertion order while TreeMap is unsorted. `Incorrect: LinkedHashMap maintains insertion order, not HashMap. TreeMap is sorted.`
+- c) HashMap and TreeMap are both unordered and unsorted. `Incorrect: HashMap is unordered, but TreeMap is ordered and sorted.`
+- d) HashMap is based on a hash table while TreeMap is stored in a tree data structure and maintains natural sorted order. `Correct: HashMap uses hashing principle and TreeMap internally uses Red-Black tree to maintain the natural sorted order.`
From 51ff0164e408d1f465479e9971617516fb2665d6 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sun, 21 May 2023 20:10:41 +0530
Subject: [PATCH 162/178] .
---
00-Quiz-Explanation/Q10-ArraysAndArrayList.md | 295 ++++++++++++++++++
1 file changed, 295 insertions(+)
create mode 100644 00-Quiz-Explanation/Q10-ArraysAndArrayList.md
diff --git a/00-Quiz-Explanation/Q10-ArraysAndArrayList.md b/00-Quiz-Explanation/Q10-ArraysAndArrayList.md
new file mode 100644
index 00000000..1154399a
--- /dev/null
+++ b/00-Quiz-Explanation/Q10-ArraysAndArrayList.md
@@ -0,0 +1,295 @@
+**Step 01: The Need For Array Quiz**
+
+**Question 1: Why do we need arrays?**
+- a. To store different types of data. `Incorrect: Arrays in Java can only hold similar types of data.`
+- b. To store similar types of data. `Correct: Arrays are used to store similar types of data (e.g., multiple integers, strings, etc.).`
+- c. To store data in an unorganized manner. `Incorrect: Arrays store data in a structured, indexed manner, not in an unorganized way.`
+
+**Question 2: What is the use of indexing operator, ‘[]’ in arrays?**
+- a. To access elements from the array. `Correct: The indexing operator is used to access a specific element in an array by its index.`
+- b. To store elements in the array. `Incorrect: While the indexing operator can be used to assign values to elements in the array, the phrasing of this option makes it a bit misleading.`
+- c. To change the elements in the array. `Incorrect: The indexing operator can be used to modify the value of a specific element in the array, but it's primary purpose is to access elements.`
+
+**Question 3: What is the purpose of enhanced for loop in arrays?**
+- a. To store elements in the array. `Incorrect: The enhanced for loop is used to traverse elements, not store them.`
+- b. To access elements from the array. `Incorrect: While this is a part of what the enhanced for loop does, it's not the full picture.`
+- c. To iterate through all elements in the array. `Correct: The enhanced for loop, also known as for-each loop, is used to iterate over all elements in the array.`
+
+**Step 02: Storing and Accessing Array Values Quiz**
+
+**Question 1: What is the purpose of using the new operator in arrays?**
+- a. To initialize an array with specific values. `Incorrect: The new keyword is used to allocate memory for an array, not to initialize specific values.`
+- b. To create an array with a specific size. `Correct: The new keyword is used to instantiate an array of a specific size.`
+- c. To assign values to an array. `Incorrect: The new keyword is used to create an array, not to assign values.`
+
+**Question 2: How can we access elements from an array?**
+- a. By using the indexing operator, ‘[]’. `Correct: Array elements can be accessed using their index with the help of indexing operator.`
+- b. By using the length property of the array. `Incorrect: The length property is used to get the size of the array, not to access specific elements.`
+- c. By using the for loop. `Incorrect: While we can use a for loop to iterate through the array, the actual access is done using the indexing operator.`
+
+**Question 3: What is the length property in arrays used for?**
+- a. To find the size of an array. `Incorrect: Length property gives the number of elements in an array, not the size of the array in memory.`
+- b. To find the number of elements in an array. `Correct: Length property returns the number of elements in an array.`
+- c. To find the value of an element in an array. `Incorrect: The length property does not provide information about the value of an element.`
+
+**Step 04: Array Initialization, Data Types and Exceptions Quiz**
+
+**Question 1: What is the value of an array element of type int when it is not initialized?**
+- a. Null `Incorrect: Primitive types, such as int, cannot be null.`
+- b. False `Incorrect: False is not a valid value for an int. It is a boolean value.`
+- c. 0 `Correct: Uninitialized int variables (including array elements) default to 0 in Java.`
+
+**Question 2: What is the value of an array element of type boolean when it is not initialized?**
+- a. Null `Incorrect: Primitive types, such as boolean, cannot be null.`
+- b. False `Correct: Uninitialized boolean variables (including array elements) default to false in Java.`
+- c. 0 `Incorrect: 0 is not a valid value for a boolean. It is an int value.`
+
+**Question 3: What is the declaration part of an array definition not allowed to include?**
+- a. The type of elements stored in the array. `Incorrect: The declaration part of an array definition does include the type of elements.`
+- b. The dimension of the array. `Correct: The dimension (size) of the array cannot be specified in the declaration part. It's defined during the array's instantiation.`
+- c. The name of the array. `Incorrect: The declaration part of an array definition does include the name of the array.`
+
+**Step 05: Array Utilities Quiz**
+
+**Question 1: What is the purpose of the method Arrays.fill?**
+- a. To compare two arrays `Incorrect: Arrays.fill method is used to fill an array with a specified value, not to compare arrays.`
+- b. To fill an array with a specified value `Correct: Arrays.fill method fills all the elements of the specified array with the specified value.`
+- c. To perform an in-position sorting of elements `Incorrect: Arrays.fill method does not perform sorting, it fills the array with a specific value.`
+- d. To store zero or more number of elements in an array `Incorrect: Arrays.fill method fills an array with a specific value, not just to store elements.`
+
+**Question 2: What is the output of the following code?**
+
+```java
+int[] marks = new int[5];
+Arrays.fill(marks, 100);
+System.out.println(marks);
+```
+
+- a. [100,100,100,100,100] `Correct: The Arrays.fill method fills all elements of the array with the specified value, so every element is now 100.`
+- b. [0,0,0,0,0] `Incorrect: All the elements in the array have been filled with 100, not 0.`
+- c. 100,100,100,100,100 `Incorrect: The output would be in array format, not as a comma-separated string.`
+- d. I@6c49835d `Incorrect: This looks like the default Object.toString() representation, but we're trying to print the content of an array, not the array's memory address.`
+
+**Question 3: What is the result of the following code?**
+
+```java
+int[] array1 = {1, 2, 3};
+int[] array2 = {1, 2, 3};
+Arrays.equals(array1, array2);
+```
+- a. false `Incorrect: The two arrays have identical contents, so the Arrays.equals method will return true.`
+- b. true `Correct: The Arrays.equals method compares two arrays for equality, and these two arrays are indeed equal.`
+- c. [1,2,3] `Incorrect: The Arrays.equals method returns a boolean, not an array.`
+- d. I@6c49835d `Incorrect: The Arrays.equals method returns a boolean, not a memory address.`
+
+
+**Step 06: Classroom Exercise CE-AA-02**
+
+**Question 1: Which of the following utility methods can be used to get the total number of marks of a Student object?**
+
+- A) getNumberOfmarks() `Correct: The getNumberOfmarks() method retrieves the total number of marks associated with a Student object.`
+- B) getTotalSumOfMarks() `Incorrect: This method, if it exists, seems like it would retrieve the sum of the marks, not the total number of marks.`
+- C) getAverageMarks() `Incorrect: This method, if it exists, seems like it would calculate the average of the marks, not the total number of marks.`
+
+**Question 2: Which of the following is an implementation of the Student class as an array?**
+
+- A) Student student = new Student(name, list-of-marks); `Incorrect: This is the instantiation of a Student object but not specifically an array implementation.`
+- B) int[] marks = {99, 98, 100}; `Correct: This is an array of integers, which could represent marks in the context of a Student class.`
+- C) BigDecimal average = student.getAverageMarks(); `Incorrect: This line retrieves the average of the marks as a BigDecimal, not an array of marks.`
+
+**Question 3: Which of the following utility methods can be used to get the maximum mark of a Student object?**
+
+- A) getNumberOfmarks() `Incorrect: This method retrieves the total number of marks, not the maximum mark.`
+- B) getMaximumMark() `Correct: This method seems to return the maximum mark of a Student.`
+- C) getMinimumMark() `Incorrect: This method seems to return the minimum mark of a Student, not the maximum.`
+
+**Step 08: Variable Arguments - The Basics**
+
+**Question 1: What is the critical part when creating a method which can accept a variable number of arguments?**
+
+- A) The int data type `Incorrect: The data type is not as critical as the variable arguments symbol. A variable argument can be of any data type.`
+- B) The ... symbol `Correct: The '...' symbol is used to denote variable arguments in a method.`
+- C) The Arrays.toString() method `Incorrect: While this can be used within a method to print an array, it is not specifically relevant to variable arguments.`
+
+**Question 2: What is the output of the following code snippet?**
+
+```java
+class Something {
+ public void doSomething(int... values) {
+ System.out.println(Arrays.toString(values));
+ }
+}
+Something thing = new Something();
+thing.doSomething(1, 2, 3);
+```
+
+- A) [1, 2] `Incorrect: The doSomething method is called with three arguments, so all three values should be printed.`
+- B) [1, 2, 3] `Correct: The doSomething method is called with three arguments, so all three values are printed.`
+- C) 1 2 3 `Incorrect: Arrays.toString() returns a string in the format [element1, element2, ...], not as a space-separated list.`
+
+**Question 3: Where should the variable arguments list be placed in the parameter list passed to a method?**
+
+- A) At the beginning `Incorrect: The variable arguments list should always be the last parameter in a method.`
+- B) In the middle `Incorrect: The variable arguments list should always be the last parameter in a method.`
+- C) At the end `Correct: The variable arguments list should always be the last parameter in a method.`
+
+**Step 09: Variable Argument Methods For Student**
+
+**Question 1: Which of the following is an example of a variable argument method in the Student class?**
+
+- A) public int getNumberOfMarks() `Incorrect: This method does not accept any arguments, hence it can't be a variable argument method.`
+- B) public int[] getMarks() `Incorrect: This method also does not accept any arguments.`
+- C) public Student(String name, int... marks) `Correct: This method accepts a variable number of int arguments after a String argument, thus it is a variable argument method.`
+
+**Question 2: What is the output of the following code snippet?**
+
+```java
+Student student = new Student("Ranga", 97, 98, 100);
+System.out.println(student.getNumberOfMarks());
+```
+
+- A) 3 `Correct: The getNumberOfMarks() method should return the number of marks, which is three in this case.`
+- B) 97, 98, 100 `Incorrect: The getNumberOfMarks() method doesn't return the actual marks, but the count of them.`
+- C) 295 `Incorrect: This seems to be the sum of the marks, but the method should return the count of them.`
+
+**Question 3: What happens if you pass the wrong data type to a variable argument method?**
+
+- A) The Java compiler will throw an error. `Correct: The compiler checks the data types of arguments and would throw an error if the data types do not match.`
+- B) The program will run, but with unexpected results. `Incorrect: The compiler would prevent the program from running in the first place.`
+- C) The program will crash. `Incorrect: The compiler would prevent the program from running and therefore it won't crash.`
+
+**Step 10: Arrays - Some Puzzles And Exercises**
+
+**Question 1: When creating an array of objects, what does the array hold?**
+
+- A) The actual objects themselves `Incorrect: Java is pass-by-value. Thus, when an object is assigned to an array, it's actually the object reference that's being stored.`
+- B) Copies of the objects `Incorrect: The array does not hold copies of the objects, but references to them.`
+- C) References to the created objects `Correct: In Java, arrays of objects hold references to the objects, not the objects themselves.`
+
+**Question 2: What is the output of the following code snippet?**
+
+```java
+Person[] persons = new Person[3];
+persons[0] = new Person();
+persons[2] = new Person();
+System.out.println(persons[1]);
+```
+
+- A) null `Correct: The Person at index 1 has not been initialized, hence it would be null.`
+- B) An error will be thrown `Incorrect: Java does not throw an error for uninitialized object references, it assigns them null by default.`
+- C) A memory address `Incorrect: Java does not show memory addresses, it would print null for uninitialized object references.`
+
+**Question 3: What is the output of the following code snippet?**
+
+```java
+String[] textValues = {"Apple", "Ball", "Cat"};
+System.out.println(textValues[2].charAt(0));
+```
+
+- A) A `Incorrect: This would be the first character of the first String, not the third.`
+- B) B `Incorrect: This would be the first character of the second String, not the third.`
+- C) C `Correct: This is the first character of the third String in the array.`
+
+**Step 11: Problems With Arrays**
+
+**Question 1
+
+: Why is it difficult to add or remove elements in an array?**
+
+- A) Because the size of an array is fixed `Correct: Once an array is created, its size cannot be changed, which makes adding or removing elements difficult.`
+- B) Because arrays are only for primitive types `Incorrect: Arrays can hold both primitive types and objects.`
+- C) Because arrays cannot store non-homogeneous types `Incorrect: While this is true, it is not the reason why adding or removing elements in an array is difficult.`
+
+**Question 2: How can we add an element to an array?**
+
+- A) By increasing the size of the array dynamically `Correct: To add an element to an array, we need to create a new array with a larger size and copy the old elements over.`
+- B) By decreasing the size of the array dynamically `Incorrect: Decreasing the size of the array would not allow us to add an element.`
+- C) By converting the array to an ArrayList `Incorrect: While this would allow you to add an element, it is not directly adding an element to an array.`
+
+**Question 3: What is the drawback of adding or removing elements from an array?**
+
+- A) It can cause an ArrayIndexOutOfBoundsException `Incorrect: While this exception could occur if you try to access an index outside the valid range, it's not a specific drawback of adding or removing elements.`
+- B) It can be very inefficient `Correct: Each time you add or remove elements, you need to create a new array, which can be inefficient for large arrays.`
+- C) It can cause a NullPointerException `Incorrect: This could occur if you try to access an element at an index where there is no object, but it's not a specific drawback of adding or removing elements.`
+
+**Step 12: Introducing ArrayList**
+
+**Question 1: What is the main advantage of ArrayList over arrays?**
+
+- A) ArrayList can store only primitive types `Incorrect: ArrayList can store objects, not primitive types.`
+- B) ArrayList provides operations to add and remove elements `Correct: ArrayList provides methods such as add() and remove() to manipulate elements.`
+- C) ArrayList has a fixed size `Incorrect: Unlike arrays, ArrayList is dynamic and can grow or shrink at runtime.`
+
+**Question 2: How do you remove an element from an ArrayList?**
+
+- A) Using the remove() method `Correct: The remove() method is used to remove an element from an ArrayList.`
+- B) Using the delete() method `Incorrect: There's no delete() method in the ArrayList class.`
+- C) Using the clear() method `Incorrect: The clear() method removes all elements, not a single one.`
+
+**Question 3: What is the warning message displayed when adding non-homogeneous types to an ArrayList?**
+
+- A) "Type safety: The method add(Object) belongs to the raw type ArrayList. References to generic type ArrayList should be parameterized." `Correct: This is a typical warning when using a raw ArrayList.`
+- B) "Unchecked call to add(E) as a member of the raw type java.util.ArrayList" `Incorrect: This message could be seen when you call an add() method on a raw type ArrayList without checking the type.`
+- C) "Type mismatch: cannot convert from int to String" `Incorrect: This message appears when there's an attempt to assign a value of one type to a variable of another type.`
+
+**Step 13: Refactoring Student To Use ArrayList**
+
+**Question 1: How can we create an ArrayList that can hold only String values?**
+
+- A) ArrayList items = new ArrayList<>(); `Correct: This
+
+ is the correct way to declare an ArrayList that holds String objects.`
+- B) ArrayList items = new ArrayList(); `Correct: This is also a correct way, but the type specification in the diamond operator can be omitted in Java 7 and later.`
+- C) ArrayList items = new ArrayList(); `Incorrect: While this would compile, it would be a raw type, and you wouldn't have the type safety benefits.`
+
+**Question 2: Why do we use ArrayList instead of arrays in the Student class?**
+
+- A) Because ArrayLists can store any type of data `Incorrect: While ArrayLists can store objects of any type, the primary reason to use them over arrays is not this flexibility.`
+- B) Because ArrayLists provide dynamic sizing and convenient methods for manipulation `Correct: These features of ArrayList make it preferable for storing elements when the count can change.`
+- C) Because ArrayLists are faster than arrays `Incorrect: This is generally not true. The performance of ArrayLists and arrays can depend on specific use cases.`
+
+**Question 3: What happens if we invoke the remove() method on an empty ArrayList?**
+
+- A) An ArrayIndexOutOfBoundsException is thrown `Incorrect: This exception is specific to array index errors, not ArrayList.`
+- B) A NullPointerException is thrown `Incorrect: This exception is thrown when you try to access an object through a null reference, not when removing an element from an empty ArrayList.`
+- C) An IndexOutOfBoundsException is thrown `Correct: If you try to remove an element at a certain index from an empty ArrayList, it throws an IndexOutOfBoundsException.`
+
+**Step 14: Creating and Manipulating Subjects**
+
+**Question 1: Why do we declare the subjects field in the Student class as private?**
+
+- A) To prevent direct access from outside the class `Correct: This is one of the key concepts of encapsulation in object-oriented programming. By making fields private, we can control their access and modification.`
+- B) To allow other classes to modify the subjects `Incorrect: The private keyword restricts access to the field from other classes.`
+- C) Because it's mandatory in Java `Incorrect: It's not mandatory, but it's a good practice for encapsulation.`
+
+**Question 2: Why do we use the `this` keyword in the constructor of the Subject class?**
+
+- A) To refer to the current instance `Correct: In Java, `this` is a reference to the current object, which is being used to distinguish instance variables from local variables.`
+- B) To create a new instance of the class `Incorrect: The `new` keyword is used to create a new instance of a class, not `this`.`
+- C) To call a method in the class `Incorrect: The `this` keyword could be used to call a method, but in this context, it's being used to refer to instance variables.`
+
+**Question 3: What is the benefit of using the `addSubject()` method instead of directly modifying the `subjects` field?**
+
+- A) It provides a consistent interface to add subjects to a student `Correct: This method encapsulates the details of how subjects are stored and provides a consistent way to add subjects.`
+- B) It makes the program run faster `Incorrect: There's no reason to believe that this method would make the program run faster.`
+- C) It reduces the amount of memory used by the program `Incorrect: This method does not reduce memory usage.`
+
+**Step 15: Overriding ToString**
+
+**Question 1: Why do we override the `toString()` method in the Student class?**
+
+- A) To provide a meaningful string representation of the student `Correct: By default, the `toString()` method returns a string that isn't very useful for understanding the object's state. Overriding it allows us to provide a more meaningful string representation.`
+- B) To increase the performance of the program `Incorrect: Overriding `toString()` does not increase performance.`
+- C) To reduce memory usage `Incorrect: Overriding `toString()` does not reduce memory usage.`
+
+**Question 2: What happens if we don't override the `toString()` method and try to print the Student object directly?**
+
+- A) It will print the string representation of the object as defined in the Object class `Correct: By default, the `toString()` method in the Object class returns a string consisting of the class name followed by an '@' sign and the hash code of the object.`
+- B) It will throw a NullPointerException `Incorrect: A NullPointerException would only be thrown if you try to call a method on a null object.`
+- C) It will print all the fields of the object `Incorrect: Without overriding, the default `toString()` does not print the fields of the object.`
+
+**Question 3: How do you call the overridden `toString()` method for a Student object?**
+
+- A) `Student.toString()` `Incorrect: This is the syntax for calling a static method. `toString()` is an instance method, so it needs to be called on an instance of Student.`
+- B) `Student student = new Student(); student.toString();` `Correct: This is the correct way to call the `toString()` method on a Student object.`
+- C) `toString(Student)` `Incorrect: This is not the correct syntax for calling the `toString()` method.`
\ No newline at end of file
From cac877b1c313a8f4bc773cb763703a26dd1533d5 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Sun, 21 May 2023 20:25:48 +0530
Subject: [PATCH 163/178] .
---
.../Q06-PrimitiveDataTypesAndAlternatives.md | 331 ++++++++++++++++
.../Q06-PrimitiveDataTypesAndAlternatives.md | 362 +++++-------------
2 files changed, 436 insertions(+), 257 deletions(-)
create mode 100644 00-Quiz-Explanation/Archive/Q06-PrimitiveDataTypesAndAlternatives.md
diff --git a/00-Quiz-Explanation/Archive/Q06-PrimitiveDataTypesAndAlternatives.md b/00-Quiz-Explanation/Archive/Q06-PrimitiveDataTypesAndAlternatives.md
new file mode 100644
index 00000000..879dd81e
--- /dev/null
+++ b/00-Quiz-Explanation/Archive/Q06-PrimitiveDataTypesAndAlternatives.md
@@ -0,0 +1,331 @@
+Step 01: The Integer Types
+
+Question 1: Which of the following wrapper classes corresponds to the int primitive type in Java?
+
+- A) Byte (Incorrect: The `Byte` class corresponds to the byte primitive type, not int.)
+- B) Integer (Correct: The `Integer` class is the wrapper class for the `int` primitive type. It provides methods to work with int values.)
+- C) Short (Incorrect: The `Short` class corresponds to the short primitive type, not int.)
+
+Explanation:
+
+- Option A is incorrect because the `Byte` class corresponds to the byte primitive type, not int.
+- Option B is correct because the `Integer` class is the wrapper class specifically designed to work with int values.
+- Option C is incorrect because the `Short` class corresponds to the short primitive type, not int.
+
+Question 2: What is the maximum value of a short data type in Java?
+
+- A) 127
+- B) 32767 (Correct: The maximum value of a `short` is 32767)
+- C) 2147483647 (Incorrect: The value 2147483647 is the maximum value for the `int` data type, not short.)
+
+Explanation:
+
+- Option A is incorrect because 127 is the maximum value for the `byte` data type, not short.
+- Option B is correct because 32767 is the maximum value for the `short` data type in Java.
+- Option C is incorrect because 2147483647 is the maximum value for the `int` data type, not short.
+
+Question 3: What type of cast is used to store a smaller data value in a larger data type variable?
+
+- A) Implicit cast (Correct: Implicit casting is used to automatically convert a smaller data type to a larger data type)
+- B) Explicit cast
+
+Explanation:
+
+- Option A is correct because implicit casting is used to automatically convert a smaller data type to a larger data type without any loss of data.
+- Option B is incorrect because explicit casting is used when converting a larger data type to a smaller data type and requires explicit specification.
+
+
+
+Step 02: Integer Representations, And Other Puzzles
+
+Question 1: What are the three number systems supported by Java for integers?
+
+- A) Decimal, Octal, and Binary
+- B) Decimal, Octal, and Hexadecimal (Correct: The three number systems supported by Java for integers are decimal, octal, and hexadecimal)
+- C) Decimal, Binary, and Hexadecimal (Incorrect: Binary is also a number system supported by Java for integers)
+
+Explanation:
+
+- Option A is incorrect because it doesn't include hexadecimal, which is one of the number systems supported by Java for integers.
+- Option B is correct because decimal, octal, and hexadecimal are the three number systems supported by Java for integers.
+- Option C is incorrect because it includes binary, but it doesn't include octal.
+
+Question 2: Which of the following is the correct representation for the value 16 in a hexadecimal system?
+
+- A) 0x10 (Correct: In a hexadecimal system, 16 is represented as 0x10)
+- B) 010 (Incorrect: This represents the value 10 in an octal system)
+- C) 0x16 (Incorrect: This represents the value 22 in a hexadecimal system)
+
+Explanation:
+
+- Option A is correct because in a hexadecimal system, the prefix "0x" is used, followed by the digits representing the value. Therefore, 16 is represented as 0x10.
+- Option B is incorrect because "010" represents the value 10 in an octal system, not hexadecimal.
+- Option C is incorrect because "0x16" represents the value 22 in a hexadecimal system, not 16.
+
+Question 3: What is the difference between prefix and post-fix increment operators in Java?
+
+- A) Prefix increment takes place before the assignment, and post-fix increment takes place after the assignment. (Correct: Prefix increment happens before the assignment, while postfix increment happens after the assignment.)
+- B) Prefix increment takes place after the assignment, and post-fix increment takes place before the assignment. (Incorrect: The order of increment is reversed in the explanation)
+- C) There is no difference between prefix and post-fix increment operators in Java. (Incorrect: There is a difference in the order of increment)
+
+Explanation:
+
+- Option A is correct because prefix increment (++variable) happens before the assignment, meaning the variable is incremented and then used in the expression.
+- Option B is incorrect because the explanation states that postfix increment happens before the assignment, which is incorrect.
+- Option C is incorrect because there is indeed a difference between prefix and postfix increment operators in Java.
+
+
+
+Step 03: Classroom Exercise CE-01 (With Solutions)
+
+Question 1: What is the purpose of the BiNumber class?
+
+- A) To store a single integer and perform basic arithmetic operations
+- B) To store a pair of integers and perform basic arithmetic operations (Correct: The purpose of the BiNumber class is to store a pair of integers and perform basic arithmetic operations)
+- C) To store a list of integers and perform basic arithmetic operations
+
+Explanation:
+
+- Option A is incorrect because it mentions storing a single integer, while the BiNumber class is specifically designed to store a pair of integers.
+- Option B is correct because the BiNumber class is used to store a pair of integers and provides methods to perform basic arithmetic operations on those numbers.
+- Option C is incorrect because it mentions storing a list of integers, which is not the purpose of the BiNumber class.
+
+Question 2: Which method is used to double the values of both numbers in a BiNumber object?
+
+- A) double()
+- B) doubleNumbers() (Correct: The `doubleNumbers()` method is used to double the values of both numbers in a BiNumber object)
+- C) doubleValue()
+
+Explanation:
+
+- Option A is incorrect because `double()` is not a valid method for doubling the values of both numbers in a BiNumber object.
+- Option B is correct because the `doubleNumbers()` method specifically performs the operation of doubling the values of both numbers in a BiNumber object.
+- Option C is incorrect because `doubleValue()` is not the method responsible for doubling both numbers in a BiNumber object.
+
+Question 3: What will be the output of the following code snippet?
+
+```java
+BiNumber numbers = new BiNumber(4, 5);
+System.out.println(numbers.add());
+numbers.doubleValue();
+System.out.println(numbers.getNumber1());
+System.out.println(numbers.getNumber2());
+```
+
+- A) 9, 8, 10
+- B) 9, 8, 5
+- C) 9, 4, 5 (Correct: The output will be 9, 4, 5 after adding the numbers and doubling the value of the BiNumber object)
+
+Explanation:
+
+- The first line creates a BiNumber object with values 4 and 5.
+- The second line prints the result of adding the two numbers, which is 9.
+- The third line calls the `doubleValue()` method on the BiNumber object, doubling both numbers internally.
+- The fourth line prints the first number of the BiNumber object, which is now 4.
+- The fifth line prints the second number of the BiNumber object, which remains 5.
+- Therefore, the output will be 9, 4, 5.
+
+
+
+Step 05: Floating-Point Types
+
+Question 1: What is the default type for floating-point literals in Java?
+
+- A) float
+- B) double (Correct: The default type for floating-point literals in Java is `double`)
+
+Explanation:
+
+- Option A is incorrect because the default type for floating-point literals in Java is `double`.
+- Option B is correct because `double` is the default type for floating-point literals in Java.
+
+Question 2: How can you create a float literal?
+
+- A) float f = 34.5
+- B) float f = 34.5f; (Correct: To create a float literal, you need to append the suffix `f` to the value)
+- C) float f = (float)34.5
+
+Explanation:
+
+- Option A is incorrect because 34.5 without the `f` suffix is considered a `double` literal, not a `float` literal.
+- Option B is correct because adding the `f` suffix to the value makes it a `float` literal.
+- Option C is incorrect because explicitly casting the value to a `float` is another way to create a `float` literal, but it is not necessary when assigning a literal value directly.
+
+Question 3: Which type of casting is needed to convert a double value to a float value?
+
+- A) Implicit casting
+- B) Explicit casting (Correct: Explicit casting is required to convert a `double` value to a `float` value)
+
+Explanation:
+
+- Option A is incorrect because implicit casting is not sufficient to convert a `double` value to a `float` value. It could result in a loss of precision.
+- Option B is correct because explicit casting, specifically `(float)`, is needed to convert a `double` value to a `float` value. It explicitly tells the compiler to perform the conversion, even though there may be potential loss of precision.
+
+
+
+Step 06: Introducing BigDecimal
+
+Question 1: What is the main reason for using the BigDecimal data type in Java?
+
+- To represent floating-point numbers with higher precision (Correct: The main reason for using the BigDecimal data type is to represent floating-point numbers with higher precision)
+- To perform faster calculations
+- To store large integer values
+
+Explanation:
+
+- Option A is correct because the BigDecimal data type is used to represent floating-point numbers with higher precision, avoiding issues with rounding errors that can occur with other floating-point types.
+- Option B is incorrect because the primary purpose of BigDecimal is precision, not performance.
+- Option C is incorrect because BigDecimal is not specifically designed for storing large integer values; it is more focused on decimal numbers with high precision.
+
+Question 2: What is the best way to construct a BigDecimal object to achieve high precision?
+
+- Using integer literals
+- Using double literals
+- Using string literals (Correct: The best way to construct a BigDecimal object to achieve high precision is by using string literals)
+
+Explanation:
+
+- Option A is incorrect because using integer literals might result in the loss of precision when constructing a BigDecimal object.
+- Option B is incorrect because using double literals may introduce rounding errors when constructing a BigDecimal object.
+- Option C is correct because using string literals, such as "0.12345678901234567890", allows you to specify the exact precision and avoid any potential rounding errors.
+
+Question 3: What is the main characteristic of BigDecimal objects?
+
+- Mutable
+- Immutable (Correct: BigDecimal objects are immutable, meaning their values cannot be changed once created)
+- Synchronized
+
+Explanation:
+
+- Option A is incorrect because BigDecimal objects are immutable, meaning their values cannot be changed once created.
+- Option B is correct because BigDecimal objects have the characteristic of immutability, ensuring that their values remain unchanged.
+- Option C is incorrect because synchronization is not a characteristic specific to BigDecimal objects. It is related to thread safety.
+
+
+
+Step 06: BigDecimal Operations
+
+Question: Which of the following methods can be used for arithmetic operations on BigDecimal objects?
+
+- a. add()
+- b. multiply()
+- c. subtract()
+- d. All of the above (Correct: All of the mentioned methods can be used for arithmetic operations on BigDecimal objects)
+
+Explanation:
+
+- Option a is correct because the `add()` method is used for addition of BigDecimal objects.
+- Option b is correct because the `multiply()` method is used for multiplication of BigDecimal objects.
+- Option c is correct because the `subtract()` method is used for subtraction of BigDecimal objects.
+- Option d is correct because all of the mentioned methods (add(), multiply(), and subtract()) can be used for arithmetic operations on BigDecimal objects.
+
+Question: Can you perform arithmetic operations directly between a BigDecimal object and a primitive data type, like an int or a double?
+
+- a. Yes
+- b. No (Correct: No, arithmetic operations between BigDecimal objects and primitive data types require explicit conversion)
+
+Explanation:
+
+- Option a is incorrect because arithmetic operations between BigDecimal objects and primitive data types cannot be performed directly without explicit conversion.
+- Option b is correct because explicit conversion, using methods like `BigDecimal.valueOf()`, is required to perform arithmetic operations between BigDecimal objects and primitive data types.
+
+Question: How can you perform an arithmetic operation between a BigDecimal object and a primitive int value?
+
+- a. Convert the int to a BigDecimal using BigDecimal.valueOf() (Correct: To perform an arithmetic operation between a BigDecimal object and a primitive int value, you need to convert the int to a BigDecimal using BigDecimal.valueOf())
+
+Explanation:
+
+- Option a is correct because to perform an arithmetic operation between a BigDecimal object and a primitive int value, you need to convert the int to a BigDecimal using the `BigDecimal.valueOf()` method.
+- Using this method, you can create a BigDecimal object representing the int value and then perform arithmetic operations with other BigDecimal objects.
+
+
+
+Step 08: boolean, Relational and Logical Operators
+
+Question: Which of the following operators is a logical operator in Java?
+
+- a) >
+- b) &&
+- c) <= (Correct: The logical operator in Java is represented by the symbol &&)
+
+Explanation:
+
+- Option a is incorrect because the ">" operator is a relational operator used for comparison.
+- Option b is correct because the "&&" operator is the logical AND operator in Java, which combines two boolean expressions.
+- Option c is incorrect because the "<=" operator is a relational operator used for comparison, not a logical operator.
+
+Question: Given the following code snippet, what will be the value of result?
+
+```java
+int a = 10;
+int b = 5;
+boolean result = (a > b) && (a < 2 * b);
+```
+
+- a) true (Correct: The value of result will be true)
+- b) false
+
+Explanation:
+
+- In the given code snippet, the expression `(a > b) && (a < 2 * b)` is evaluated.
+- `(a > b)` evaluates to true because 10 is greater than 5.
+- `(a < 2 * b)` also evaluates to true because 10 is less than 2 times 5, which is 10.
+- The logical AND operator `&&` combines these two boolean expressions and returns true only if both expressions are true.
+- Since both expressions are true, the value of `result` will be true.
+
+Question: What will the following expression evaluate to?
+
+```java
+boolean x = true;
+boolean y = false;
+boolean z = !(x || y);
+```
+
+- a) true
+- b) false (Correct: The expression will evaluate to false)
+
+Explanation:
+
+- The expression `(x || y)` evaluates to true because at least one of the operands (x or y) is true.
+- The `!` operator negates the result, so `!(x || y)` evaluates to false.
+- Therefore, the value of `z` will be false.
+
+
+
+Step 10: Character Types
+
+Question 1: What is the Unicode representation of the double quotation mark?
+
+- \u0021
+- \u0022 (Correct: The Unicode representation of the double quotation mark is \u0022)
+- \u0023
+
+Explanation:
+
+- Option \u0021 represents the Unicode character for exclamation mark (!), not the double quotation mark.
+- Option \u0022 is correct because it represents the Unicode character for double quotation mark (").
+- Option \u0023 represents the Unicode character for hash or number sign (#), not the double quotation mark.
+
+Question 2: What data type in Java is used to store Unicode characters?
+
+- String
+- char (Correct: The `char` data type in Java is used to store Unicode characters)
+- int
+
+Explanation:
+
+- Option String is incorrect because `String` is a data type used to store sequences of characters, not a single Unicode character.
+- Option char is correct because the `char` data type is specifically designed to store a single Unicode character.
+- Option int is incorrect because `int` is used to store integer values, not Unicode characters.
+
+Question 3: What happens when you perform the following operation in Java: `char cn = 65;`?
+
+- A character with a Unicode value of 65 is stored in the variable cn. (Correct: The character with Unicode value 65, which is 'A', is stored in the variable cn)
+- An integer value of 65 is stored in the variable cn.
+- A compilation error occurs.
+
+Explanation:
+
+- Option A is correct because assigning the value 65 to a char variable `cn` will store the character 'A' in `cn`. In Java, characters are internally represented using Unicode values.
+- Option B is incorrect because 65 is the Unicode value of 'A', not an integer value.
+- Option C is incorrect because there is no compilation error in assigning a Unicode value to a char variable.
diff --git a/00-Quiz-Explanation/Q06-PrimitiveDataTypesAndAlternatives.md b/00-Quiz-Explanation/Q06-PrimitiveDataTypesAndAlternatives.md
index 879dd81e..5bde4bd7 100644
--- a/00-Quiz-Explanation/Q06-PrimitiveDataTypesAndAlternatives.md
+++ b/00-Quiz-Explanation/Q06-PrimitiveDataTypesAndAlternatives.md
@@ -1,108 +1,59 @@
-Step 01: The Integer Types
+**Step 1: The Integer Types**
-Question 1: Which of the following wrapper classes corresponds to the int primitive type in Java?
+**Question 1: Which of the following wrapper classes corresponds to the int primitive type in Java?**
-- A) Byte (Incorrect: The `Byte` class corresponds to the byte primitive type, not int.)
-- B) Integer (Correct: The `Integer` class is the wrapper class for the `int` primitive type. It provides methods to work with int values.)
-- C) Short (Incorrect: The `Short` class corresponds to the short primitive type, not int.)
+- A) Byte `Incorrect: Byte corresponds to the byte primitive type, not int.`
+- B) Integer `Correct: Integer is the wrapper class for the int primitive type in Java.`
+- C) Short `Incorrect: Short corresponds to the short primitive type, not int.`
-Explanation:
+**Question 2: What is the maximum value of a short data type in Java?**
-- Option A is incorrect because the `Byte` class corresponds to the byte primitive type, not int.
-- Option B is correct because the `Integer` class is the wrapper class specifically designed to work with int values.
-- Option C is incorrect because the `Short` class corresponds to the short primitive type, not int.
+- A) 127 `Incorrect: 127 is the maximum value for a byte, not short.`
+- B) 32767 `Correct: 32767 is indeed the maximum value a short can take in Java.`
+- C) 2147483647 `Incorrect: This is the maximum value for int, not short.`
-Question 2: What is the maximum value of a short data type in Java?
+**Question 3: What type of cast is used to store a smaller data value in a larger data type variable?**
-- A) 127
-- B) 32767 (Correct: The maximum value of a `short` is 32767)
-- C) 2147483647 (Incorrect: The value 2147483647 is the maximum value for the `int` data type, not short.)
+- A) Implicit cast `Correct: Java will automatically perform an implicit cast when storing a smaller data type in a larger one.`
+- B) Explicit cast `Incorrect: Explicit casting is used when we want to convert a larger type to a smaller one, potentially losing information.`
-Explanation:
+**Step 2: Integer Representations, And Other Puzzles**
-- Option A is incorrect because 127 is the maximum value for the `byte` data type, not short.
-- Option B is correct because 32767 is the maximum value for the `short` data type in Java.
-- Option C is incorrect because 2147483647 is the maximum value for the `int` data type, not short.
+**Question 1: What are the three number systems supported by Java for integers?**
-Question 3: What type of cast is used to store a smaller data value in a larger data type variable?
+- A) Decimal, Octal, and Binary `Incorrect: Java supports Decimal, Octal, Binary and also Hexadecimal.`
+- B) Decimal, Octal, and Hexadecimal `Correct: Java supports these three number systems as well as binary.`
+- C) Decimal, Binary, and Hexadecimal `Correct: Java indeed supports these three number systems.`
-- A) Implicit cast (Correct: Implicit casting is used to automatically convert a smaller data type to a larger data type)
-- B) Explicit cast
+**Question 2: Which of the following is the correct representation for the value 16 in a hexadecimal system?**
-Explanation:
+- A) 0x10 `Correct: 0x prefix denotes hexadecimal in Java, and 10 is 16 in hexadecimal.`
+- B) 010 `Incorrect: The 0 prefix is for octal numbers in Java, not hexadecimal.`
+- C) 0x16 `Incorrect: 0x16 represents 22 in decimal, not 16.`
-- Option A is correct because implicit casting is used to automatically convert a smaller data type to a larger data type without any loss of data.
-- Option B is incorrect because explicit casting is used when converting a larger data type to a smaller data type and requires explicit specification.
+**Question 3: What is the difference between prefix and post-fix increment operators in Java?**
+- A) Prefix increment takes place before the assignment, and post-fix increment takes place after the assignment. `Correct: In prefix, the value is incremented first then used whereas in postfix the value is used then incremented.`
+- B) Prefix increment takes place after the assignment, and post-fix increment takes place before the assignment. `Incorrect: It's the other way around. Prefix increment occurs before assignment and post-fix increment after assignment.`
+- C) There is no difference between prefix and post-fix increment operators in Java. `Incorrect: The order of operations differs between the two.`
+**Step 3: Classroom Exercise CE-01 (With Solutions)**
-Step 02: Integer Representations, And Other Puzzles
+**Question 1: What is the purpose of the BiNumber class?**
-Question 1: What are the three number systems supported by Java for integers?
+- A) To store a single integer and perform basic arithmetic operations `Incorrect: BiNumber is designed to store and operate on a pair of numbers, not a single integer.`
+- B) To store a pair of integers and perform basic arithmetic operations `Correct: The BiNumber class is designed to store two numbers and perform operations on them.`
+- C) To store a list of integers and perform basic arithmetic operations `Incorrect: BiNumber class is not intended for storing a list of integers.`
-- A) Decimal, Octal, and Binary
-- B) Decimal, Octal, and Hexadecimal (Correct: The three number systems supported by Java for integers are decimal, octal, and hexadecimal)
-- C) Decimal, Binary, and Hexadecimal (Incorrect: Binary is also a number system supported by Java for integers)
+**Question 2: Which method is used to double the values of both numbers in a BiNumber object?**
-Explanation:
+- A)
-- Option A is incorrect because it doesn't include hexadecimal, which is one of the number systems supported by Java for integers.
-- Option B is correct because decimal, octal, and hexadecimal are the three number systems supported by Java for integers.
-- Option C is incorrect because it includes binary, but it doesn't include octal.
+ double() `Incorrect: There's no double() method in the BiNumber class.`
+- B) doubleNumbers() `Correct: The doubleNumbers() method doubles the values of both numbers in the BiNumber object.`
+- C) doubleValue() `Incorrect: The doubleValue() method is not used to double the numbers in the BiNumber class.`
-Question 2: Which of the following is the correct representation for the value 16 in a hexadecimal system?
-
-- A) 0x10 (Correct: In a hexadecimal system, 16 is represented as 0x10)
-- B) 010 (Incorrect: This represents the value 10 in an octal system)
-- C) 0x16 (Incorrect: This represents the value 22 in a hexadecimal system)
-
-Explanation:
-
-- Option A is correct because in a hexadecimal system, the prefix "0x" is used, followed by the digits representing the value. Therefore, 16 is represented as 0x10.
-- Option B is incorrect because "010" represents the value 10 in an octal system, not hexadecimal.
-- Option C is incorrect because "0x16" represents the value 22 in a hexadecimal system, not 16.
-
-Question 3: What is the difference between prefix and post-fix increment operators in Java?
-
-- A) Prefix increment takes place before the assignment, and post-fix increment takes place after the assignment. (Correct: Prefix increment happens before the assignment, while postfix increment happens after the assignment.)
-- B) Prefix increment takes place after the assignment, and post-fix increment takes place before the assignment. (Incorrect: The order of increment is reversed in the explanation)
-- C) There is no difference between prefix and post-fix increment operators in Java. (Incorrect: There is a difference in the order of increment)
-
-Explanation:
-
-- Option A is correct because prefix increment (++variable) happens before the assignment, meaning the variable is incremented and then used in the expression.
-- Option B is incorrect because the explanation states that postfix increment happens before the assignment, which is incorrect.
-- Option C is incorrect because there is indeed a difference between prefix and postfix increment operators in Java.
-
-
-
-Step 03: Classroom Exercise CE-01 (With Solutions)
-
-Question 1: What is the purpose of the BiNumber class?
-
-- A) To store a single integer and perform basic arithmetic operations
-- B) To store a pair of integers and perform basic arithmetic operations (Correct: The purpose of the BiNumber class is to store a pair of integers and perform basic arithmetic operations)
-- C) To store a list of integers and perform basic arithmetic operations
-
-Explanation:
-
-- Option A is incorrect because it mentions storing a single integer, while the BiNumber class is specifically designed to store a pair of integers.
-- Option B is correct because the BiNumber class is used to store a pair of integers and provides methods to perform basic arithmetic operations on those numbers.
-- Option C is incorrect because it mentions storing a list of integers, which is not the purpose of the BiNumber class.
-
-Question 2: Which method is used to double the values of both numbers in a BiNumber object?
-
-- A) double()
-- B) doubleNumbers() (Correct: The `doubleNumbers()` method is used to double the values of both numbers in a BiNumber object)
-- C) doubleValue()
-
-Explanation:
-
-- Option A is incorrect because `double()` is not a valid method for doubling the values of both numbers in a BiNumber object.
-- Option B is correct because the `doubleNumbers()` method specifically performs the operation of doubling the values of both numbers in a BiNumber object.
-- Option C is incorrect because `doubleValue()` is not the method responsible for doubling both numbers in a BiNumber object.
-
-Question 3: What will be the output of the following code snippet?
+**Question 3: What will be the output of the following code snippet?**
```java
BiNumber numbers = new BiNumber(4, 5);
@@ -112,168 +63,89 @@ System.out.println(numbers.getNumber1());
System.out.println(numbers.getNumber2());
```
-- A) 9, 8, 10
-- B) 9, 8, 5
-- C) 9, 4, 5 (Correct: The output will be 9, 4, 5 after adding the numbers and doubling the value of the BiNumber object)
-
-Explanation:
-
-- The first line creates a BiNumber object with values 4 and 5.
-- The second line prints the result of adding the two numbers, which is 9.
-- The third line calls the `doubleValue()` method on the BiNumber object, doubling both numbers internally.
-- The fourth line prints the first number of the BiNumber object, which is now 4.
-- The fifth line prints the second number of the BiNumber object, which remains 5.
-- Therefore, the output will be 9, 4, 5.
-
-
-
-Step 05: Floating-Point Types
-
-Question 1: What is the default type for floating-point literals in Java?
-
-- A) float
-- B) double (Correct: The default type for floating-point literals in Java is `double`)
-
-Explanation:
-
-- Option A is incorrect because the default type for floating-point literals in Java is `double`.
-- Option B is correct because `double` is the default type for floating-point literals in Java.
-
-Question 2: How can you create a float literal?
-
-- A) float f = 34.5
-- B) float f = 34.5f; (Correct: To create a float literal, you need to append the suffix `f` to the value)
-- C) float f = (float)34.5
+- A) 9, 8, 10 `Correct: The add() method returns the sum of the numbers (4+5=9). The doubleValue() method doubles the values (4*2=8 and 5*2=10).`
+- B) 9, 8, 5 `Incorrect: The second number is also doubled by the doubleValue() method, it should be 10 not 5.`
+- C) 9, 4, 5 `Incorrect: The doubleValue() method doubles the values of both numbers.`
-Explanation:
+**Step 5: Floating-Point Types**
-- Option A is incorrect because 34.5 without the `f` suffix is considered a `double` literal, not a `float` literal.
-- Option B is correct because adding the `f` suffix to the value makes it a `float` literal.
-- Option C is incorrect because explicitly casting the value to a `float` is another way to create a `float` literal, but it is not necessary when assigning a literal value directly.
+**Question 1: What is the default type for floating-point literals in Java?**
-Question 3: Which type of casting is needed to convert a double value to a float value?
+- A) float `Incorrect: In Java, floating-point literals are by default considered double.`
+- B) double `Correct: Double is indeed the default data type for floating-point literals in Java.`
-- A) Implicit casting
-- B) Explicit casting (Correct: Explicit casting is required to convert a `double` value to a `float` value)
+**Question 2: How can you create a float literal?**
-Explanation:
+- A) float f = 34.5 `Incorrect: This will lead to a compilation error as 34.5 is a double literal by default. A suffix of 'f' or 'F' is needed to make it a float literal.`
+- B) float f = 34.5f; `Correct: This is the correct way to create a float literal in Java. The 'f' suffix indicates a float literal.`
+- C) float f = (float)34.5 `Correct: Explicitly casting a double literal to a float will also work, but the 'f' suffix is generally preferred.`
-- Option A is incorrect because implicit casting is not sufficient to convert a `double` value to a `float` value. It could result in a loss of precision.
-- Option B is correct because explicit casting, specifically `(float)`, is needed to convert a `double` value to a `float` value. It explicitly tells the compiler to perform the conversion, even though there may be potential loss of precision.
+**Question 3: Which type of casting is needed to convert a double value to a float value?**
+- A) Implicit casting `Incorrect: Implicit casting is used when we convert a smaller type to a larger one.`
+- B) Explicit casting `Correct: When converting a larger type to a smaller one, such as double to float, explicit casting is needed.`
+**Step 6: Introducing BigDecimal**
-Step 06: Introducing BigDecimal
+**Question 1: What is the main reason for using the BigDecimal data type in Java?**
-Question 1: What is the main reason for using the BigDecimal data type in Java?
+- A) To represent floating-point numbers with higher precision `Correct: BigDecimal allows us to represent floating-point numbers with almost arbitrary precision, making it a good choice for financial and monetary calculations.`
+- B) To perform faster calculations `Incorrect: BigDecimal computations are generally slower than primitive types due to the higher precision and object overhead.`
+- C) To store large integer values `Incorrect: Although BigDecimal can indeed store large numbers, its primary purpose is to offer precise floating-point computations.`
-- To represent floating-point numbers with higher precision (Correct: The main reason for using the BigDecimal data type is to represent floating-point numbers with higher precision)
-- To perform faster calculations
-- To store large integer values
+**Question 2: What is the best way to construct a BigDecimal object to achieve high precision?**
-Explanation:
+- A) Using integer literals `Incorrect: Although you can construct a BigDecimal with an integer literal, for high precision you should prefer string literals.`
+- B) Using double literals `Incorrect: This can introduce rounding errors because of the binary representation of double literals. It's not the preferred way for high precision.`
+- C) Using string literals `Correct: Constructing BigDecimal objects using string literals is the preferred way when high precision is required.`
-- Option A is correct because the BigDecimal data type is used to represent floating-point numbers with higher precision, avoiding issues with rounding errors that can occur with other floating-point types.
-- Option B is incorrect because the primary purpose of BigDecimal is precision, not performance.
-- Option C is incorrect because BigDecimal is not specifically designed for storing large integer values; it is more focused on decimal numbers with high precision.
+**Question 3: What is the main characteristic of BigDecimal objects?**
-Question 2: What is the best way to construct a BigDecimal object to achieve high precision?
+- A) Mutable `Incorrect: BigDecimal objects are immutable, which means their value
-- Using integer literals
-- Using double literals
-- Using string literals (Correct: The best way to construct a BigDecimal object to achieve high precision is by using string literals)
+ cannot be changed once created.`
+- B) Immutable `Correct: Indeed, BigDecimal objects are immutable.`
+- C) Synchronized `Incorrect: Synchronization isn't a characteristic of BigDecimal. It's a concept related to multi-threading.`
-Explanation:
+**Step 6: BigDecimal Operations**
-- Option A is incorrect because using integer literals might result in the loss of precision when constructing a BigDecimal object.
-- Option B is incorrect because using double literals may introduce rounding errors when constructing a BigDecimal object.
-- Option C is correct because using string literals, such as "0.12345678901234567890", allows you to specify the exact precision and avoid any potential rounding errors.
+**Question 1: Which of the following methods can be used for arithmetic operations on BigDecimal objects?**
-Question 3: What is the main characteristic of BigDecimal objects?
+- A) add() `This method is used for addition operations on BigDecimal objects.`
+- B) multiply() `This method is used for multiplication operations on BigDecimal objects.`
+- C) subtract() `This method is used for subtraction operations on BigDecimal objects.`
+- D) All of the above `Correct: All these methods can be used for arithmetic operations on BigDecimal objects.`
-- Mutable
-- Immutable (Correct: BigDecimal objects are immutable, meaning their values cannot be changed once created)
-- Synchronized
+**Question 2: Can you perform arithmetic operations directly between a BigDecimal object and a primitive data type, like an int or a double?**
-Explanation:
+- A) Yes `Incorrect: You cannot directly perform arithmetic operations between a BigDecimal object and a primitive data type.`
+- B) No `Correct: You need to convert the primitive to a BigDecimal first.`
-- Option A is incorrect because BigDecimal objects are immutable, meaning their values cannot be changed once created.
-- Option B is correct because BigDecimal objects have the characteristic of immutability, ensuring that their values remain unchanged.
-- Option C is incorrect because synchronization is not a characteristic specific to BigDecimal objects. It is related to thread safety.
+**Question 3: How can you perform an arithmetic operation between a BigDecimal object and a primitive int value?**
+- A) Convert the int to a BigDecimal using BigDecimal.valueOf() `Correct: This is the best way to convert a primitive int to a BigDecimal for arithmetic operations.`
+- B) Use a type cast to convert the int to a BigDecimal `Incorrect: You can't use casting to convert a primitive to a BigDecimal.`
+- C) Perform the operation directly as the BigDecimal class automatically handles primitive types `Incorrect: The BigDecimal class doesn't automatically handle arithmetic with primitives.`
+**Step 8: boolean, Relational and Logical Operators**
-Step 06: BigDecimal Operations
+**Question 1: Which of the following operators is a logical operator in Java?**
-Question: Which of the following methods can be used for arithmetic operations on BigDecimal objects?
-
-- a. add()
-- b. multiply()
-- c. subtract()
-- d. All of the above (Correct: All of the mentioned methods can be used for arithmetic operations on BigDecimal objects)
-
-Explanation:
-
-- Option a is correct because the `add()` method is used for addition of BigDecimal objects.
-- Option b is correct because the `multiply()` method is used for multiplication of BigDecimal objects.
-- Option c is correct because the `subtract()` method is used for subtraction of BigDecimal objects.
-- Option d is correct because all of the mentioned methods (add(), multiply(), and subtract()) can be used for arithmetic operations on BigDecimal objects.
-
-Question: Can you perform arithmetic operations directly between a BigDecimal object and a primitive data type, like an int or a double?
-
-- a. Yes
-- b. No (Correct: No, arithmetic operations between BigDecimal objects and primitive data types require explicit conversion)
-
-Explanation:
-
-- Option a is incorrect because arithmetic operations between BigDecimal objects and primitive data types cannot be performed directly without explicit conversion.
-- Option b is correct because explicit conversion, using methods like `BigDecimal.valueOf()`, is required to perform arithmetic operations between BigDecimal objects and primitive data types.
-
-Question: How can you perform an arithmetic operation between a BigDecimal object and a primitive int value?
-
-- a. Convert the int to a BigDecimal using BigDecimal.valueOf() (Correct: To perform an arithmetic operation between a BigDecimal object and a primitive int value, you need to convert the int to a BigDecimal using BigDecimal.valueOf())
-
-Explanation:
-
-- Option a is correct because to perform an arithmetic operation between a BigDecimal object and a primitive int value, you need to convert the int to a BigDecimal using the `BigDecimal.valueOf()` method.
-- Using this method, you can create a BigDecimal object representing the int value and then perform arithmetic operations with other BigDecimal objects.
-
-
-
-Step 08: boolean, Relational and Logical Operators
-
-Question: Which of the following operators is a logical operator in Java?
-
-- a) >
-- b) &&
-- c) <= (Correct: The logical operator in Java is represented by the symbol &&)
-
-Explanation:
-
-- Option a is incorrect because the ">" operator is a relational operator used for comparison.
-- Option b is correct because the "&&" operator is the logical AND operator in Java, which combines two boolean expressions.
-- Option c is incorrect because the "<=" operator is a relational operator used for comparison, not a logical operator.
-
-Question: Given the following code snippet, what will be the value of result?
+- A) > `Incorrect: '>' is a relational operator, not a logical operator.`
+- B) && `Correct: '&&' is a logical AND operator. It returns true if both operands are true.`
+- C) <= `Incorrect: '<=' is a relational operator, not a logical operator.`
+**Question 2: Given the following code snippet, what will be the value of result?**
```java
-int a = 10;
-int b = 5;
-boolean result = (a > b) && (a < 2 * b);
+ int a = 10;
+ int b = 5;
+ boolean result = (a > b) && (a < 2 * b);
```
-- a) true (Correct: The value of result will be true)
-- b) false
+- A) true `Correct: Since both conditions (a > b and a < 2 * b) are true, the result will be true.`
+- B) false `Incorrect: Given the values of a and b, the result of the boolean expression is true.`
-Explanation:
-
-- In the given code snippet, the expression `(a > b) && (a < 2 * b)` is evaluated.
-- `(a > b)` evaluates to true because 10 is greater than 5.
-- `(a < 2 * b)` also evaluates to true because 10 is less than 2 times 5, which is 10.
-- The logical AND operator `&&` combines these two boolean expressions and returns true only if both expressions are true.
-- Since both expressions are true, the value of `result` will be true.
-
-Question: What will the following expression evaluate to?
+**Question 3: What will the following expression evaluate to?**
```java
boolean x = true;
@@ -281,51 +153,27 @@ boolean y = false;
boolean z = !(x || y);
```
-- a) true
-- b) false (Correct: The expression will evaluate to false)
-
-Explanation:
-
-- The expression `(x || y)` evaluates to true because at least one of the operands (x or y) is true.
-- The `!` operator negates the result, so `!(x || y)` evaluates to false.
-- Therefore, the value of `z` will be false.
-
-
-
-Step 10: Character Types
-
-Question 1: What is the Unicode representation of the double quotation mark?
-
-- \u0021
-- \u0022 (Correct: The Unicode representation of the double quotation mark is \u0022)
-- \u0023
-
-Explanation:
-
-- Option \u0021 represents the Unicode character for exclamation mark (!), not the double quotation mark.
-- Option \u0022 is correct because it represents the Unicode character for double quotation mark (").
-- Option \u0023 represents the Unicode character for hash or number sign (#), not the double quotation mark.
+- A) true `Incorrect: Since 'x' is true, 'x || y' is also true. The negation of true is false.`
+- B) false `Correct: The expression '(x || y)' is true, so the negation of this expression is false.`
-Question 2: What data type in Java is used to store Unicode characters?
+**Step 10: Character Types**
-- String
-- char (Correct: The `char` data type in Java is used to store Unicode characters)
-- int
+**Question 1: What is the Unicode representation of the double quotation mark?**
-Explanation:
+- A) \u0021 `Incorrect: \u0021 is the Unicode representation for the exclamation mark (!).`
+- B) \u0022 `Correct: \u0022 is the Unicode representation for the double quotation mark (").`
+- C) \u0023 `Incorrect: \u0023 is the Unicode representation for the number sign (#).`
-- Option String is incorrect because `String` is a data type used to store sequences of characters, not a single Unicode character.
-- Option char is correct because the `char` data type is specifically designed to store a single Unicode character.
-- Option int is incorrect because `int` is used to store integer values, not Unicode characters.
+**Question 2: What data type in Java is used to store Unicode characters?**
-Question 3: What happens when you perform the following operation in Java: `char cn = 65;`?
+- A) String `Incorrect: Although a String can contain Unicode characters, the data type specifically designed to store a single Unicode character is char.`
+- B) char `Correct: The char data type in Java is used to store a single Unicode character.`
+-
-- A character with a Unicode value of 65 is stored in the variable cn. (Correct: The character with Unicode value 65, which is 'A', is stored in the variable cn)
-- An integer value of 65 is stored in the variable cn.
-- A compilation error occurs.
+ C) byte `Incorrect: Although a byte can represent a character in some encodings, the char data type is specifically designed for this purpose in Java.`
-Explanation:
+**Question 3: What will the following code print out?**
-- Option A is correct because assigning the value 65 to a char variable `cn` will store the character 'A' in `cn`. In Java, characters are internally represented using Unicode values.
-- Option B is incorrect because 65 is the Unicode value of 'A', not an integer value.
-- Option C is incorrect because there is no compilation error in assigning a Unicode value to a char variable.
+- A) The character 'a' `Incorrect: The code will print the character corresponding to the Unicode value 0x0041, which is 'A'.`
+- B) The character 'A' `Correct: The Unicode value 0x0041 corresponds to the character 'A'.`
+- C) The number 65 `Incorrect: The code will print the character corresponding to the Unicode value 0x0041, not the value itself.`
From 3d3dbbe66e6b0a23d060401ef1e552c310584c52 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Mon, 22 May 2023 09:39:12 +0530
Subject: [PATCH 164/178] Create 1.md
---
00-Quiz-Explanation/1.md | 664 +++++++++++++++++++++++++++++++++++++++
1 file changed, 664 insertions(+)
create mode 100644 00-Quiz-Explanation/1.md
diff --git a/00-Quiz-Explanation/1.md b/00-Quiz-Explanation/1.md
new file mode 100644
index 00000000..b1544c8a
--- /dev/null
+++ b/00-Quiz-Explanation/1.md
@@ -0,0 +1,664 @@
+**Step 02: Introducing JShell**
+
+**Question 4: What does JShell stand for?**
+
+- A) JavaShell `Correct: JShell stands for Java Shell. It's a Read-Eval-Print Loop (REPL) tool introduced in Java 9.`
+- B) JavaScriptShell `Incorrect: JShell is a Java feature and has no relation to JavaScript, a separate programming language.`
+- C) JupyterShell `Incorrect: Jupyter is a different open-source project providing interactive computing for multiple programming languages. It isn't directly connected to Java or JShell.`
+
+**Question 5: What is the purpose of JShell?**
+
+- A) To create graphical user interfaces `Incorrect: GUI creation in Java typically involves libraries like Swing or JavaFX, not JShell.`
+- B) To evaluate and execute Java code and provide immediate results `Correct: JShell is designed to evaluate and execute Java code and provide immediate results, a feature known as a Read-Eval-Print Loop (REPL).`
+- C) To debug Java code `Incorrect: Although you can use JShell to test small code snippets, its primary function isn't debugging. Traditional debugging involves tools that step through code, inspect variables, set breakpoints, etc.`
+
+**Question 6: What command can be used to exit JShell?**
+
+- A) /end `Incorrect: /end is not a valid command in JShell.`
+- B) /exit `Correct: /exit is the command to exit JShell, terminating the session and returning you to your system's command line.`
+- C) /quit `Incorrect: /quit is not a recognized command in JShell.`
+
+**Step 03: Welcome to Problem Solving**
+
+**Question 7: What is the problem solving technique used in this step?**
+
+- A) Reverse Engineering `Incorrect: Reverse Engineering starts with a finished product, working backward to understand how it was made. It doesn't apply in this context.`
+- B) Subdivision `Correct: Subdivision is a technique where a complex problem is broken down into smaller, more manageable parts. It's used in this step to simplify the task of creating a multiplication table.`
+- C) Deductive Reasoning `Incorrect: Deductive Reasoning is a process of reasoning from general statements to a certain conclusion. It's not the primary technique used in this situation.`
+
+**Question 8: What is the result of 5 * 3?**
+
+- A) 8 `Incorrect: 5 times 3 equals to 15, not 8.`
+- B) 10 `Incorrect: 5 times 3 equals to 15, not 10.`
+- C) 15 `Correct: The result of multiplying 5 by 3 is indeed 15.`
+
+**Question 9: How many times do we repeat the calculation in this step?**
+
+- A) 5 times `Incorrect: The calculation is not repeated 5 times in this step.`
+- B) 10 times `Correct: The calculation is repeated 10 times in this step.`
+- C) 15 times `Incorrect: The calculation is not repeated 15 times in this step.`
+
+**Step 04: Introducing Expressions**
+
+**Question 10: What is the result of 5 * 3?**
+
+- A) 8 `Incorrect: 5 times 3 equals to 15, not 8.`
+- B) 10 `Incorrect: 5 times 3 equals to 15, not 10.`
+- C) 15 `Correct: The result of multiplying 5 by 3 is indeed 15.`
+
+**Question 11: What are the operands in the expression 5 * 3?**
+
+- A) 5, 3 `Correct: In the expression 5 * 3, 5 and 3 are the operands being multiplied.`
+- B) 5 `Incorrect: Both 5 and 3 are operands in the expression, not just 5.`
+- C) 3 `Incorrect: Both 5 and 3 are operands in the expression, not just 3.`
+
+**Question 12: What is the modulo operator in Java?**
+
+- A) * `Incorrect: The asterisk (*) is the multiplication operator in Java, not the modulo operator.`
+- B) % `Correct: The percentage symbol (%) represents the modulo operator in Java. It returns the remainder of a division operation.`
+- C) + `Incorrect: The plus symbol (+) is the addition operator in Java, not the modulo operator.`
+
+**Step 05: Programming Exercise PE-1 (With Solutions)**
+
+**Question 13: Write an expression to calculate the number of minutes in a day.**
+
+- A) 24 * 60 `Incorrect: This is the number of hours in a day times the number of minutes in an hour, not the number of minutes in a day.`
+- B) 60 + 24 `Incorrect: This expression adds the number of hours in a day to the number of minutes in an hour, which doesn't give the number of minutes in a day.`
+- C) 60 * 24 `Correct: There are 60 minutes in an hour and 24 hours in a day. Therefore, the number of minutes in a day is 60 * 24.`
+
+**Question 14: Write an expression to calculate the number of seconds in a day.**
+
+- A) 24 * 60 * 60 `Incorrect: This is the number of hours in a day times the number of minutes in an hour times the number of seconds in a minute, which doesn't yield the number of seconds in a day.`
+- B) 60 + 60 + 24 `Incorrect: This expression adds the number of minutes in an hour, the number of seconds in a minute, and the number of hours in a day. It doesn't calculate the number of seconds in a day.`
+- C) 60 * 60 * 24 `Correct: There are 60 seconds in a minute, 60 minutes in an hour, and 24 hours in a day. So, the number of seconds in a day is 60 * 60 * 24.`
+
+**Step 06: Operators**
+
+**Question 15: Which of the following is a valid operator in Java?**
+
+- A) ** `Incorrect: Java doesn't have a ** operator. This is used in some languages for exponentiation, but Java uses Math.pow() for this purpose.`
+- B) $ `Incorrect: The dollar symbol ($) is not an operator in Java.`
+- C) * `Correct: The asterisk (*) is the multiplication operator in Java.`
+
+**Question 16: What is the result of 5 / 2 in Java?**
+
+- A) 2 `Correct: In Java, when you divide an integer by another integer, the result is an integer. So, 5 divided by 2 equals 2, with remainder 1.`
+- B) 2.0 `Incorrect: 5 divided by 2 yields 2.5, but since both are integers, the result is an integer (2), not a floating-point number (2.0).`
+- C) 2.5 `Incorrect: 5 divided by 2 equals 2.5, but in Java, when you divide an integer by another integer, the result is an integer (2), not a floating-point number (2.5).`
+
+**Question 17: What is the order of sub-expression evaluation in the expression 5 + 5 * 6?**
+
+- A) 5 + 5, then 10 * 6 `Incorrect: In Java, multiplication and division are performed before addition and subtraction. Therefore, 5 * 6 is evaluated first, then 5 + 30.`
+- B) 5 * 6, then 5 + 30 `Correct: Java follows the order of operations, which means that multiplication and division are performed before addition and subtraction.`
+- C) Depends on operand types `Incorrect: The order of operations in Java doesn't depend on operand types.`
+
+**Question 18: How can parentheses be used to group parts of an expression?**
+
+- A) They have no effect on the evaluation of an expression `Incorrect: Parentheses do have an effect on expression evaluation; they dictate the order in which operations are performed.`
+- B) They are used to specify the order of sub-expression evaluation `Correct: Parentheses can be used to change the order of operations in an expression, ensuring certain parts are evaluated first.`
+- C) They are used to introduce new operators `Incorrect: Parentheses don't introduce new operators; they are used to change the order of operations in an expression.`
+
+**Step 07: Introducing Console Output**
+
+**Question 19: Which built-in Java method displays text on the console?**
+
+- A) System.out.print() `Incorrect: While this method does display text, it does not add a new line after the text.`
+- B) System.out.display() `Incorrect: There's no display() method in System.out in Java.`
+- C) System.out.println() `Correct: This method displays text on the console and adds a new line after the text.`
+
+**Question 20: What is a String literal in Java?**
+
+- A) A sequence of numbers `Incorrect: A string literal is a sequence of characters enclosed in double quotes, not necessarily numbers.`
+- B) A piece of text with numeric characters `Incorrect: A string literal can be any sequence of characters, not just numeric characters.`
+- C) A keyword used for control flow `Incorrect: A string literal isn't a keyword. It's a sequence of characters enclosed in double quotes.`
+
+**Question 21: How do you print the exact text "Hello World" on the console using System.out.println()?**
+
+- A) System.out.println("Hello World") `Correct: This is the correct way to print "Hello World" in Java. The text to be printed is enclosed in double quotes.`
+- B) System.out.println(Hello World) `Incorrect: This will cause a compilation error, as Hello and World are not valid variables or keywords, and the text is not enclosed in double quotes.`
+- C) System.out.print("Hello World") `Incorrect: While this will print "Hello World", it will not add a new line afterwards, unlike System.out.println().`
+
+**Question 22: Can you pass a mathematical expression like 5 * 3 = 15 as an argument to System.out.println() in Java?**
+
+- A) Yes, it will evaluate the expression and print the result `Incorrect: You can't pass a mathematical expression with an equals sign (=) to System.out.println() in Java. This will cause a syntax error.`
+- B) No, it will throw an error `Correct: In Java, you can't pass a mathematical expression with an equals sign (=) as an argument to System.out.println(). You can only pass an expression without an equals
+
+ sign, such as 5 * 3, and Java will evaluate and print the result.`
+- C) Yes, it will print the expression as it is without evaluating it `Incorrect: You can't pass a mathematical expression with an equals sign (=) to System.out.println() in Java. This will cause a syntax error.`
+
+
+**Step 09: Solutions to PE-02**
+
+**Question 23: What is the output of the following code?**
+
+```java
+System.out.println("Hello World");
+```
+
+- A) HelloWorld `Incorrect: The correct output will include a space between "Hello" and "World", because the argument to the println method is a single string with a space included.`
+- B) Hello World `Correct: This option correctly reproduces the argument to the println method, including the space between "Hello" and "World".`
+- C) "Hello World" `Incorrect: The quotation marks are not included in the output of the println method. They are used in the code to define the string that is printed.`
+
+**Question 24: What is the output of the following code?**
+
+```java
+System.out.println("5 * 3");
+```
+
+- A) 5 * 3 `Correct: This will print the string "5 * 3" as it is without evaluating it because it's in the double quotes.`
+- B) 15 `Incorrect: Java won't evaluate the expression inside the quotes. It will consider it as a string.`
+- C) "5 * 3" `Incorrect: The output will not include the double quotes. They are used in the code to define the string that is printed.`
+
+**Question 25: What is the output of the following code?**
+
+```java
+System.out.println(5 * 3);
+```
+
+- A) 5 * 3 `Incorrect: Java will evaluate the expression 5 * 3 as it's not inside the double quotes and print the result.`
+- B) 15 `Correct: This statement is doing arithmetic operation (multiplication) and the result of 5 * 3 is 15.`
+- C) "15" `Incorrect: The output is the integer 15, not the string "15". There are no quotation marks in the output.`
+
+**Question 26: What is the output of the following code?**
+
+```
+System.out.println(60 * 60 * 24);
+```
+
+- A) 86400 `Correct: This statement is doing arithmetic operation (multiplication) and the result of 60 * 60 * 24 is 86400.`
+- B) 86400.0 `Incorrect: The output is the integer 86400, not the floating-point number 86400.0. The multiplication operation does not involve any floating-point numbers.`
+- C) "86400" `Incorrect: The output is the integer 86400, not the string "86400". There are no quotation marks in the output.`
+
+**Step 10: Whitespace, Case Sensitiveness and Escape Characters**
+
+**Question 27: What does whitespace refer to in Java?**
+- A) Any sequence of continuous digits.
+ - `Incorrect: Whitespace does not refer to digits in Java. It refers to spaces, tabs, and newlines.`
+- B) Any sequence of continuous space, tab or newline characters.
+ - `Correct: In Java, "whitespace" refers to any space, tab, or newline character. These characters are often used to format code to make it more readable.`
+- C) Any sequence of continuous special symbols.
+ - `Incorrect: Whitespace does not refer to special symbols in Java. It refers to spaces, tabs, and newlines.`
+
+**Question 28: Why is it important to use the correct case when calling pre-defined Java elements?**
+- A) Because Java is case-sensitive, and using the incorrect case will result in an error.
+ - `Correct: Java is case-sensitive. For instance, the method "println" is different from "Println" or "PRINTLN". Incorrect case can cause a compilation error.`
+- B) Because Java is not case-sensitive, and using the incorrect case will make the code more readable.
+ - `Incorrect: Java is case-sensitive. The readability of the code depends on following coding conventions, not on the case-sensitivity of the language.`
+- C) It is not important to use the correct case when calling pre-defined Java elements.
+ - `Incorrect: Java is a case-sensitive language, meaning that using the incorrect case will result in a compilation error.`
+
+**Question 29: What does an escape character do in Java?**
+- A) It helps to escape from the current method.
+ - `Incorrect: An escape character does not have anything to do with escaping from a method. It is used to introduce special character sequences.`
+- B) It helps to insert special character sequences.
+ - `Correct: An escape character (\) in Java is used to introduce special character sequences like \n for newline, \t for tab, \" for double quote, etc.`
+- C) It helps to escape from the current class.
+ - `Incorrect: An escape character does not have anything to do with escaping from a class. It is used to introduce special character sequences.`
+
+**Question 30: What is the purpose of the '\n' escape sequence?**
+- A) To insert a new method.
+ - `Incorrect: The '\n' escape sequence doesn't relate to inserting methods. It's used to insert a newline in the text at this point.`
+- B) To insert a newline.
+ - `Correct: The '\n' escape sequence is used to insert a newline in the text at this point.`
+- C) To insert a tab.
+ - `Incorrect: The '\n' escape sequence does not insert a tab. The '\t' escape sequence is used for that purpose.`
+
+**Question 78: What is the escape sequence for inserting a tab in a string literal?**
+- A) \n
+ - `Incorrect: The \n escape sequence represents a newline, not a tab.`
+- B) \t
+ - `Correct: The \t escape sequence is used for inserting a tab.`
+- C) \b
+ - `Incorrect: The \b escape sequence represents a backspace, not a tab.`
+
+
+**Step 11: More On Method Calls**
+
+**Question 31: What is the purpose of parentheses in method calls?**
+- A) They are optional and can be left out
+ - `Incorrect: Parentheses are not optional in method calls and cannot be left out. They are part of the syntax.`
+- B) They are used to separate individual parameters with a comma
+ - `Incorrect: While parameters are indeed separated by commas within parentheses, the primary purpose of parentheses in method calls is to enclose all the parameters.`
+- C) They enclose all the parameters and are a necessary part of the syntax
+ - `Correct: In method calls, parentheses are used to enclose all parameters and are a necessary part of the syntax.`
+
+**Question 32: What does the Math.random() method do?**
+- A) It prints a random integer between 0 and 1
+ - `Incorrect: Math.random() returns a random double value between 0 (inclusive) and 1 (exclusive). It does not print anything.`
+- B) It returns a random real number between 0 and 1
+ - `Correct: Math.random() generates a random double value between 0.0 (inclusive) and 1.0 (exclusive).`
+- C) It returns the maximum of two given numbers
+ - `Incorrect: Math.random() does not compare or return maximum values. It returns a random double value.`
+
+**Question 33: What does the Math.min() method return?**
+- A) The maximum of two given numbers
+ - `Incorrect: The Math.min() method is used to find the minimum of the two numbers, not the maximum.`
+- B) The minimum of two given numbers
+ - `Correct: The Math.min() method returns the smallest of two numbers.`
+- C) The sum of two given numbers
+ - `Incorrect: The Math.min() method does not sum numbers. It returns the smallest of the two numbers.`
+
+**Step 12: More Formatted Output**
+
+**Question 34: Which method can accept a variable number of arguments?**
+- A) System.out.println()
+ - `Incorrect: System.out.println() accepts a single argument, but it can print multiple values if they are concatenated into a single string.`
+- B) System.out.printf()
+ - `Correct: System.out.printf() can accept a variable number of arguments, allowing for formatted output of multiple values.`
+- C) Math.min()
+ - `Incorrect: The Math.min() method takes two arguments and returns the smaller one.`
+
+**Question 35: Which of the following is a predefined literal used as a format specifier in printf() to format data of type int?**
+- A) %f
+ - `Incorrect: The %f specifier is used for floating-point types, not integers.`
+- B) %d
+ - `Correct: The %d specifier is used to format integers.`
+- C) %s
+ - `Incorrect: The %s specifier is used for strings, not integers.`
+
+**Question 36: What will be the output of the following code?**
+```java
+System.out.printf("%d + %d + %d = %d", 3, 4, 5, 3 + 4 + 5).println();
+```
+- A) 3 + 4 + 5 = 12
+ - `Correct: The printf statement formats the output according to the format specifiers and arguments provided. Hence, the output will be '3 + 4 + 5 = 12'.`
+- B) 3 4 5 = 12
+ - `Incorrect: The
+
+ output includes plus signs due to the format string in the printf method.`
+- C) 3 + 4 = 7
+ - `Incorrect: The output includes 3 numbers and their sum, which is 12, not just two numbers and their sum.`
+
+**Step 13: Introducing Variables**
+
+**Question 37: What is a variable in Java?**
+- A) A method to print calculated values
+ - `Incorrect: A variable is not a method. It is used to store data, not print values.`
+- B) A keyword to reserve memory for data
+ - `Correct: A variable in Java is a location in memory where data can be stored. When we declare a variable, we reserve memory for data.`
+- C) A character to represent symbols in a string
+ - `Incorrect: A variable is not a character or a symbol. It is a memory location for storing data values.`
+
+**Question 38: How can we change the value of a variable?**
+- A) Using the System.out.printf() method
+ - `Incorrect: The System.out.printf() method is used for formatted output, not for changing variable values.`
+- B) By calling a method with a different argument
+ - `Incorrect: While it's true that a method can change a variable's value, it's not the main or direct way to do so.`
+- C) By assigning a new value to it using the assignment operator =
+ - `Correct: We can change the value of a variable by assigning a new value to it using the assignment operator (=).`
+
+**Question 39: How can we use variables to simplify code?**
+- A) By defining a new method
+ - `Incorrect: Defining a new method does not directly relate to using variables. Variables can help to store and manipulate data within methods, but creating new methods is not a direct way of using variables to simplify code.`
+- B) By storing the output of a method in a variable
+ - `Incorrect: While this is a use of variables, the most general way variables simplify code is by holding data that can be used and manipulated in many ways, including within different parts of a statement or block of code.`
+- C) By assigning changing values to a variable and using it in a statement
+ - `Correct: Variables can be used to simplify code by storing changing values, which can then be referred to and manipulated in various parts of a program.`
+
+**Step 15: Using Variables Quiz**
+
+**Question 40: Why is it important to declare variables before using them in a Java program?**
+- A) It makes the code look more organized
+ - `Incorrect: While declaring variables does help to organize code, the main reason to declare them before use is to ensure they are initialized before being used.`
+- B) It ensures that the variables have values assigned to them
+ - `Incorrect: While it's true that declaring variables can ensure they have initial values, the main reason to declare them before use is to avoid runtime errors due to uninitialized variables.`
+- C) It avoids errors due to uninitialized variables
+ - `Correct: Declaring variables before using them avoids runtime errors because it ensures that memory is allocated for them and they are initialized to default or user-specified values.`
+
+**Question 41: In Java, every variable must be declared with a __________.**
+- A) keyword
+ - `Incorrect: Although a keyword is used to indicate the data type during variable declaration (like int, double, etc.), it is not what is declared with the variable itself.`
+- B) value
+ - `Incorrect: While a variable can be declared with an initial value,
+
+ it is not a requirement.`
+- C) type
+ - `Correct: In Java, every variable must be declared with a data type. The type specifies the kind of values the variable can store and the operations that can be performed on it.`
+
+**Question 42: What happens when you try to store a double value into an integer variable?**
+- A) It is allowed without any issues
+ - `Incorrect: Java does not automatically convert a double value into an integer because it could result in loss of precision.`
+- B) An error is generated as the types are incompatible
+ - `Correct: If you try to store a double value into an integer variable, Java generates a compile-time error because of the incompatibility in types.`
+- C) The value is automatically rounded up to the nearest integer
+ - `Incorrect: Java does not automatically round the double value. Explicit casting is required for this.`
+
+**Step 16: Variables: Behind-The-Scenes**
+
+**Question 43: What is the process of giving a value to a variable during its declaration called?**
+- A) Assignment
+ - `Incorrect: While assigning a value to a variable is part of the process, the term for giving a value to a variable during its declaration is "initialization".`
+- B) Initialization
+ - `Correct: Initialization is the process of giving a value to a variable at the time of declaration.`
+- C) Declaration
+ - `Incorrect: Declaration is the process of creating a variable, not the act of giving it a value.`
+
+**Question 44: What happens when a variable's initial value is another variable previously defined?**
+- A) The initial value of the first variable is lost
+ - `Incorrect: Assigning the value of one variable to another does not affect the original variable's value.`
+- B) The value of the second variable is lost
+ - `Incorrect: The value of the second variable is updated, not lost, when it's given the value of the first variable.`
+- C) The value stored in the first variable's slot is copied to the second variable's slot
+ - `Correct: When one variable is assigned the value of another, the value in the first variable is copied into the second.`
+
+**Question 45: Which of the following is not allowed in variable assignment?**
+- A) From a literal value to a variable, having compatible types
+ - `Incorrect: This is allowed. A literal value of a compatible type can be assigned to a variable.`
+- B) From a variable to another variable, of compatible types
+ - `Incorrect: This is allowed. The value of one variable can be assigned to another, provided their types are compatible.`
+- C) Assignment to a constant literal
+ - `Correct: This is not allowed. Constant literals cannot be assigned new values.`
+
+**Step 17: Naming Variables**
+
+**Question 46: Which of the following characters is allowed in a variable name in Java?**
+- A) #
+ - `Incorrect: The # character is not allowed in a variable name in Java.`
+- B) $
+ - `Correct: The $ character is allowed in a variable name in Java.`
+- C) %
+ - `Incorrect: The % character is not allowed in a variable name in Java.`
+- D) !
+ - `Incorrect: The ! character is not allowed in a variable name in Java.`
+
+**Question 47: Which of the following variable names is not allowed in Java?**
+- A) _score
+ - `Incorrect: This is allowed. A variable name can start with an underscore (_) in Java.`
+- B) 3goals
+
+
+ - `Correct: This is not allowed. A variable name cannot start with a number in Java.`
+- C) player$1
+ - `Incorrect: This is allowed. A variable name can include $ in Java.`
+
+**Question 48: What is the purpose of using meaningful names for variables in a program?**
+- A) To make the program run faster
+ - `Incorrect: The names of variables do not affect the speed of a program.`
+- B) To make the code easier to read and understand
+ - `Correct: Using meaningful names for variables makes the code easier to read and understand, as it provides some indication of what the variables are used for.`
+- C) To use less memory
+ - `Incorrect: The names of variables do not significantly impact the amount of memory used by a program.`
+
+That's the end of the quiz. I hope this was helpful for your learning process.
+
+
+**Question 49: Which of the following characters is allowed in a variable name in Java?**
+- A) #
+ - `Incorrect: The # character is not allowed in a variable name in Java.`
+- B) $
+ - `Correct: The $ character is allowed in a variable name in Java.`
+- C) %
+ - `Incorrect: The % character is not allowed in a variable name in Java.`
+- D) !
+ - `Incorrect: The ! character is not allowed in a variable name in Java.`
+
+**Question 50: Which of the following variable names is not allowed in Java?**
+- A) _score
+ - `Incorrect: This is allowed. A variable name can start with an underscore (_) in Java.`
+- B) 3goals
+ - `Correct: This is not allowed. A variable name cannot start with a number in Java.`
+- C) yellowCard
+ - `Incorrect: This is allowed. This follows the standard naming convention in Java.`
+- D) goals3
+ - `Incorrect: This is allowed. A variable name can have numbers, but it cannot start with them.`
+
+**Question 51: Which of the following is a recommended naming convention for variables in Java?**
+- A) Start variable names with uppercase letters
+ - `Incorrect: In Java, it is common convention to start variable names with lowercase letters.`
+- B) Use long variable names to make your code more expressive
+ - `Incorrect: While clarity is important, excessively long variable names can make code harder to read. It's best to keep them concise yet meaningful.`
+- C) Use CamelCase for variable names with multiple words
+ - `Correct: In Java, it is common convention to use CamelCase for variable names that consist of multiple words.`
+- D) Use special characters like ! or % in variable names
+ - `Incorrect: Java does not allow special characters like ! or % in variable names.`
+
+**Question 52: Which of the following is NOT an integral value primitive type in Java?**
+- A) byte
+ - `Incorrect: byte is an integral value primitive type in Java.`
+- B) short
+ - `Incorrect: short is an integral value primitive type in Java.`
+- C) float
+ - `Correct: float is a floating-point primitive type, not an integral type.`
+
+**Question 53: What is the default type for floating type values in Java with size 64 bits?**
+- A) double
+ - `Correct: double is the default type for floating-point numbers in Java with a size of 64 bits.`
+- B) float
+ - `Incorrect: float is a 32-bit floating point type.`
+- C) int
+ - `Incorrect: int is an integer type, not a floating-point type.`
+
+**Question 54: What is the correct way to store a single character symbol in a char variable in Java?**
+- A) Within double quotes ""
+ - `Incorrect: Double quotes are used to denote Strings in Java. For character literals, single quotes are used.`
+- B) Within parentheses ()
+ - `Incorrect: Parentheses are not used to denote character literals in Java.`
+- C) Within single quotes ''
+ - `Correct: Single quotes are used to denote character literals in Java.`
+
+**Question 55: Which data type is best for storing the number of goals scored by a team in a football match?**
+- A) Byte
+ - `Incorrect: While byte could technically store the number of goals in a single match, it is rarely used for this purpose due to its limited range.`
+- B) Short
+
+
+ - `Correct: The short data type is a good choice for storing the number of goals in a football match, as it can comfortably accommodate the range of possible values.`
+- C) Long
+ - `Incorrect: The long data type is more than is needed for storing the number of goals in a football match. It would be wasteful in terms of memory.`
+
+**Question 56: Which data type is best for storing the average rainfall in a month?**
+- A) Int
+ - `Incorrect: Integers are not ideal for storing average rainfall, as rainfall is often measured to a decimal point.`
+- B) Float
+ - `Incorrect: Although float could work, it has less precision compared to double.`
+- C) Double
+ - `Correct: The double data type is ideal for storing the average rainfall in a month because it can comfortably accommodate decimal values to a high degree of precision.`
+
+**Question 57: Which data type is best for storing the grade of a student in a class?**
+- A) Int
+ - `Incorrect: Integers are not ideal for storing grades, especially if the grading system involves letters (A, B, C, etc.) or decimal points.`
+- B) Char
+ - `Correct: The char data type is ideal for storing the grade of a student if the grades are represented by single letters (A, B, C, etc.).`
+- C) Float
+ - `Incorrect: Float would be suitable if grades were numerical and required decimal precision, but for letter grades, char is more appropriate.`
+
+**Question 58: What is the assignment operator in Java?**
+- A) ==
+ - `Incorrect: == is the equality operator in Java, not the assignment operator.`
+- B) =
+ - `Correct: = is the assignment operator in Java.`
+- C) +
+ - `Incorrect: + is the addition operator in Java, not the assignment operator.`
+
+**Question 59: What is the output of the following code: int x = 5; x = x + 3;**
+- A) 3
+ - `Incorrect: The variable x is incremented by 3, so its new value is 8, not 3.`
+- B) 8
+ - `Correct: The variable x is incremented by 3, giving it a new value of 8.`
+- C) 5
+ - `Incorrect: The variable x is incremented by 3, so its new value is 8, not 5.`
+
+**Question 60: What is the result of the following code: int y = 10; y = y - 2; y = y - 3;**
+- A) 3
+ - `Incorrect: The variable y is decremented by 2 and then by 3, resulting in a value of 5, not 3.`
+- B) 10
+ - `Incorrect: The variable y is decremented by 2 and then by 3, resulting in a value of 5, not 10.`
+- C) 5
+ - `Correct: The variable y is decremented by 2 and then by 3, resulting in a value of 5.`
+
+**Question 61: What is the difference between prefix and postfix versions of increment and decrement operators?**
+- A) There is no difference between prefix and postfix versions.
+ - `Incorrect: There is indeed a difference: the prefix version updates the variable first and then returns the value, while the postfix version first returns the value and then updates it.`
+- B) Prefix version returns the updated value while postfix returns the original value.
+ -
+
+ `Correct: The prefix version increments or decrements the variable first and then returns the value, while the postfix version first returns the value and then increments or decrements it.`
+- C) Postfix version returns the updated value while prefix returns the original value.
+ - `Incorrect: This is the opposite of how prefix and postfix operators work in Java.`
+
+**Question 62: What is the compound assignment operator used for?**
+- A) To assign a new value to a variable.
+ - `Incorrect: Although compound assignment does involve assigning a value to a variable, its main purpose is to simplify the syntax when the variable itself is part of the operation.`
+- B) To combine the = with a numeric operator.
+ - `Correct: Compound assignment operators combine the assignment operator (=) with a numeric operator such as +, -, *, or /.`
+- C) To compare two values.
+ - `Incorrect: Compound assignment operators are not used for comparison.`
+
+**Question 63: What does the expression i %= 2 mean?**
+- A) Add 2 to the value of i and store the result back into i.
+ - `Incorrect: This would be represented by the expression i += 2, not i %= 2.`
+- B) Divide i by 2, and store the result back into i.
+ - `Incorrect: This would be represented by the expression i /= 2, not i %= 2.`
+- C) Divide i by 2, and store the remainder back into i.
+ - `Correct: The %= operator performs modulus division, dividing i by 2 and storing the remainder back into i.`
+
+
+**Question 64: Which is the correct comparison operator in Java?**
+- A) =
+ - `Incorrect: = is the assignment operator in Java, not the comparison operator.`
+- B) ==
+ - `Correct: == is the comparison operator in Java, which checks if two variables are equal.`
+
+**Question 65: What is the structure of an if statement in Java?**
+- A) if {condition} (statement);
+ - `Incorrect: Brackets are incorrectly placed in this statement. The condition should be inside parentheses and the statement inside braces.`
+- B) if {statement} (condition);
+ - `Incorrect: Brackets are incorrectly placed in this statement. The condition should be inside parentheses and the statement inside braces.`
+- C) if (condition) {statement};
+ - `Correct: This is the correct syntax for an if statement in Java.`
+
+**Question 66: What is the output of the following code:**
+```java
+int a = 5;
+int b = 10;
+if (a > b) {
+ System.out.println("a is greater than b");
+} else {
+ System.out.println("b is greater than a");
+}
+```
+- A) a is greater than b
+ - `Incorrect: The condition checks if a is greater than b, which is false as 5 is not greater than 10.`
+- B) b is greater than a
+ - `Correct: Since a is not greater than b, the else statement is executed, printing "b is greater than a".`
+
+**Question 67: What is the output of the following code snippet?**
+```java
+int x = 7;
+if (x < 10) {
+ System.out.println("x is less than 10");
+}
+else {
+ System.out.println("x is greater than or equal to 10");
+}
+```
+- A) x is less than 10
+ - `Correct: The variable x is less than 10, so this statement is printed.`
+- B) x is greater than or equal to 10
+ - `Incorrect: The variable x is less than 10, so this statement is not printed.`
+- C) Compiler Error
+ - `Incorrect: There is no compiler error. The code is correct.`
+
+**Question 68: What happens when we don't use statement blocks with if conditional?**
+- A) The condition statement only controls the execution of the first statement.
+ - `Correct: If no braces are used, an if condition only applies to the immediate statement following it.`
+- B) The condition statement controls the execution of all the statements.
+ - `Incorrect: Without braces, only the immediate following statement is controlled by the if condition.`
+- C) The code will not compile.
+ - `Incorrect: The code will compile. It's just that the if condition will only apply to the immediate next statement.`
+
+**Question 69: What is the benefit of using statement blocks with if conditionals?**
+- A) Improves code readability
+ - `Correct: Using braces makes it clear which statements are controlled by the if condition, improving readability.`
+- B) Increases the number of statements that can be executed conditionally
+ - `Incorrect: While using braces does allow multiple statements to be executed under a condition, the primary benefit is improving readability, not increasing functionality.`
+- C) Improves program efficiency
+ - `Incorrect: Using braces does not improve program efficiency. Its primary benefit is improving readability.`
+
+**Question 70: What does a for loop iterate over?**
+- A) a fixed number of iterations
+ - `Incorrect: A for loop can iterate over a
+
+ variable number of iterations, not just a fixed number.`
+- B) an infinite number of times
+ - `Incorrect: A for loop can run an infinite number of times only if its condition never becomes false, but generally it iterates over a variable number of times.`
+- C) a variable number of times
+ - `Correct: A for loop can iterate over a variable number of times, depending on its condition.`
+
+**Question 71: What is the syntax of a for loop?**
+- A) for (initialization; update; condition)
+ - `Incorrect: This is not the correct syntax for a for loop in Java. The correct order is: initialization; condition; update.`
+- B) for (update; condition; initialization)
+ - `Incorrect: This is not the correct syntax for a for loop in Java. The correct order is: initialization; condition; update.`
+- C) for (initialization; condition; update)
+ - `Correct: This is the correct syntax for a for loop in Java.`
+
+**Question 72: What is the output of the following code snippet?**
+```java
+for (int i=0; i<=10; i++) {
+ System.out.printf("%d * %d = %d", 6, i, 6*i).println();
+}
+```
+- A) Multiplication table of 6
+ - `Correct: This code prints the multiplication table of 6.`
+- B) Multiplication table of 10
+ - `Incorrect: The loop is multiplying by 6, not 10.`
+- C) Multiplication table of 7
+ - `Incorrect: The loop is multiplying by 6, not 7.`
+
+**Question 73: What is the output of the following code snippet?**
+```java
+for (int i=1; i<=10; i++) {
+ System.out.printf(i*i).println();
+}
+```
+- A) The squares of integers from 1 to 10
+ - `Correct: The code calculates and prints the squares of the integers from 1 to 10.`
+- B) The squares of first 10 even integers
+ - `Incorrect: The code calculates the squares of all integers from 1 to 10, not just the even ones.`
+- C) The squares of first 10 odd integers
+ - `Incorrect: The code calculates the squares of all integers from 1 to 10, not just the odd ones.`
+
+**Question 74: What is the output of the following code snippet?**
+```java
+for (int i=10; i>0; i--) {
+ System.out.printf(i).println();
+}
+```
+- A) The integers from 10 to 1
+ - `Correct: The code prints the integers from 10 to 1 in descending order.`
+- B) The integers from 1 to 10
+ - `Incorrect: The loop is set to decrement, not increment, so it prints from 10 to 1, not 1 to 10.`
+- C) The squares of integers from 1 to 10 in reverse order
+ - `Incorrect: The loop simply prints the numbers from 10 to 1, it does not square the numbers.`
+
+**Question 75: Which of the following is true about the for loop construct in Java?**
+- A) All components of the for loop are required.
+ - `Incorrect: All components of the for loop (initialization, condition, and update) are optional in Java.`
+- B) Only the condition component of the for loop is optional.
+ - `Incorrect: All components of the for loop are optional in Java, not just the condition.`
+- C) All components of the for loop are optional.
+ - `Correct: In a Java for loop, all components are optional.`
+
+**Question 76: What happens if the condition component of a for loop is left empty?**
+- A) The loop continues indefinitely until stopped externally.
+ - `Correct: If the condition component of a for loop is left empty, the
+
+ loop will continue indefinitely (or until an external condition, like a `break` statement, stops it).`
+- B) The loop exits immediately without executing any statements.
+ - `Incorrect: The loop will continue to execute, not exit, if the condition is left empty.`
+- C) The loop executes once and exits immediately.
+ - `Incorrect: The loop will continue to execute indefinitely, not just once, if the condition is left empty.`
+
+**Question 77: What is the output of the following code snippet?**
+```java
+int i = 1;
+for (; i <= 10; i++);
+System.out.println(i);
+```
+- A) 1
+ - `Incorrect: The variable i is incremented in the for loop until it is not less than or equal to 10, so the output will be 11.`
+- B) 10
+ - `Incorrect: The variable i is incremented in the for loop until it is not less than or equal to 10, so the output will be 11.`
+- C) 11
+ - `Correct: The variable i is incremented in the for loop until it is not less than or equal to 10, so the output will be 11.`
From c2b3a7c959f924c72eb4dbaa4af1bb90c6f5ef23 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Mon, 22 May 2023 09:39:33 +0530
Subject: [PATCH 165/178] Rename 1.md to
Q01-IntroductionToJavaProgrammingWithJShell-MultiplicationTable.md
---
...ntroductionToJavaProgrammingWithJShell-MultiplicationTable.md} | 0
1 file changed, 0 insertions(+), 0 deletions(-)
rename 00-Quiz-Explanation/{1.md => Q01-IntroductionToJavaProgrammingWithJShell-MultiplicationTable.md} (100%)
diff --git a/00-Quiz-Explanation/1.md b/00-Quiz-Explanation/Q01-IntroductionToJavaProgrammingWithJShell-MultiplicationTable.md
similarity index 100%
rename from 00-Quiz-Explanation/1.md
rename to 00-Quiz-Explanation/Q01-IntroductionToJavaProgrammingWithJShell-MultiplicationTable.md
From 598db48079460de499c09f90546020f2f0b5ba07 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Thu, 25 May 2023 11:13:11 +0530
Subject: [PATCH 166/178] Create Q13-Generics.md
---
01-Quiz/Q13-Generics.md | 103 ++++++++++++++++++++++++++++++++++++++++
1 file changed, 103 insertions(+)
create mode 100644 01-Quiz/Q13-Generics.md
diff --git a/01-Quiz/Q13-Generics.md b/01-Quiz/Q13-Generics.md
new file mode 100644
index 00000000..98fdf9ea
--- /dev/null
+++ b/01-Quiz/Q13-Generics.md
@@ -0,0 +1,103 @@
+**Question 79: What is the purpose of generics in Java?**
+- A) To allow for type safety
+ - `Correct: Generics are used in Java to ensure type safety. This means that the type of objects stored in a collection is known, reducing the risk of runtime errors.`
+- B) To improve performance
+ - `Incorrect: Generics do not directly contribute to the performance of Java code. They do, however, increase type safety, which can indirectly lead to performance improvements by reducing the need for runtime type checking and casting.`
+- C) To make code more readable
+ - `Incorrect: While the use of generics can make code more structured and predictable, their primary purpose is to provide type safety.`
+- D) All of the above
+ - `Incorrect: As explained above, the primary purpose of generics is to provide type safety, not to improve performance or readability directly.`
+
+**Question 80: What is the syntax for declaring a generic class?**
+- A) class MyClass
+ - `Correct: This is the correct syntax to declare a generic class in Java. The is a type parameter that stands for any type.`
+- B) class MyClass extends T>
+ - `Incorrect: This is not the correct syntax to declare a generic class in Java. A class cannot directly extend a type parameter.`
+- C) class MyClass implements T>
+ - `Incorrect: This is not the correct syntax to declare a generic class in Java. A class cannot directly implement a type parameter.`
+- D) None of the above
+ - `Incorrect: Option (A) is the correct syntax to declare a generic class.`
+
+**Question 81: What is the syntax for declaring a generic method?**
+- A) void myMethod(T t)
+ - `Incorrect: While this might look correct, a generic method must declare its type parameter(s) before the return type. The correct syntax is void myMethod(T t).`
+- B) T myMethod(T t)
+ - `Incorrect: While this might look correct, a generic method must declare its type parameter(s) before the return type. The correct syntax is T myMethod(T t).`
+- C) T myMethod()
+ - `Incorrect: While this might look correct, a generic method must declare its type parameter(s) before the return type. The correct syntax is T myMethod().`
+- D) None of the above
+ - `Correct: None of the above options correctly declare a generic method. The correct syntax is return_type methodName(T t)`
+
+**Question 82: What is the difference between a generic class and a non-generic class?**
+- A) A generic class can only contain objects of a specific type, while a non-generic class can contain objects of any type.
+ - `Incorrect: A generic class can actually contain objects of any given type, not only a specific type. It's the type parameter that provides the flexibility to use any type.`
+- B) A generic class can be used with any type of object, while a non-generic class can only be used with objects of a specific type.
+ - `Correct: A generic class can be used with any type of object because of its type parameter. A non-generic class usually operates on specific, hard-coded types.`
+- C) There is no difference between a generic class and a non-generic class.
+ - `Incorrect: There is a significant difference between a generic and a non-generic class. The main difference lies in type safety and reusability.`
+- D) None of the above
+ - `Incorrect: Option (B) correctly describes the difference between
+
+ a generic class and a non-generic class.`
+
+**Question 83: What is the purpose of type parameters in generics?**
+- A) To allow for type safety
+ - `Correct: Type parameters allow for type safety by ensuring that the objects being used match the declared type.`
+- B) To improve performance
+ - `Incorrect: While generics can indirectly lead to better performance by reducing the need for runtime type checking and casting, the main purpose of type parameters is not performance improvement.`
+- C) To make code more readable
+ - `Incorrect: While type parameters can make code more structured and predictable, the main purpose of type parameters is to ensure type safety.`
+- D) All of the above
+ - `Incorrect: As mentioned above, the main purpose of type parameters is to provide type safety.`
+
+**Question 84: What is the difference between a type parameter and a variable?**
+- A) A type parameter is a placeholder for a type, while a variable is a placeholder for a value.
+ - `Correct: A type parameter is a placeholder for a type, and it will be replaced with a real type when an instance of the generic class or method is created. On the other hand, a variable is a placeholder for a value and can be assigned different values during program execution.`
+- B) A type parameter is a variable that can only contain objects of a specific type, while a variable can contain objects of any type.
+ - `Incorrect: A type parameter is not a variable; it's a placeholder for a type, not for a value.`
+- C) There is no difference between a type parameter and a variable.
+ - `Incorrect: There is a significant difference between a type parameter and a variable. A type parameter is a placeholder for a type, while a variable is a placeholder for a value.`
+- D) None of the above
+ - `Incorrect: Option (A) correctly describes the difference between a type parameter and a variable.`
+
+**Question 85: What is the difference between a upper bound and a lower bound for a type parameter?**
+- A) A upper bound is the maximum type that a type parameter can be, while a lower bound is the minimum type that a type parameter can be.
+ - `Correct: In generics, an upper bound is declared using the keyword 'extends' and allows you to use a type parameter that is a subtype of a specific class or interface. On the other hand, a lower bound is declared using the keyword 'super' and allows you to use a type parameter that is a supertype of a specific class or interface.`
+- B) A upper bound is the minimum type that a type parameter can be, while a lower bound is the maximum type that a type parameter can be.
+ - `Incorrect: It's the other way around. See explanation for option (A).`
+- C) There is no difference between an upper bound and a lower bound.
+ - `Incorrect: There is a significant difference between an upper bound and a lower bound in terms of type parameters in generics.`
+- D) None of the above
+ - `Incorrect: Option (A) correctly describes the difference between an upper bound and a lower bound for a type parameter.`
+
+**Question 86: What is the purpose of wildcards in generics?**
+- A) To allow for type safety
+ - `Incorrect: While wildcards can contribute to type safety by ensuring that only compatible types are used, their main purpose is to enhance the flexibility and reusability of generic classes and methods.`
+- B) To improve performance
+ - `Incorrect: The main purpose of wildcards in generics is not to improve performance.`
+- C) To
+
+ make code more readable
+ - `Incorrect: The main purpose of wildcards in generics is not to make code more readable. Their primary role is to improve flexibility and reusability.`
+- D) None of the above
+ - `Correct: The main purpose of wildcards in generics is to improve flexibility and reusability, not directly ensuring type safety, improving performance or making code more readable.`
+
+**Question 87: What is the difference between a `? extends T` wildcard and a `? super T` wildcard?**
+- A) A `? extends T` wildcard can only be used to refer to objects of type T or any subtype of T, while a `? super T` wildcard can only be used to refer to objects of type T or any supertype of T.
+ - `Correct: The `? extends T` wildcard means that you can use any type that is a subclass of T (or T itself). Conversely, the `? super T` wildcard means that you can use any type that is a superclass of T (or T itself).`
+- B) A `? extends T` wildcard can only be used to refer to objects of type T, while a `? super T` wildcard can only be used to refer to objects of any type.
+ - `Incorrect: This description doesn't accurately represent the behavior of these wildcards. See explanation for option (A).`
+- C) There is no difference between a `? extends T` wildcard and a `? super T` wildcard.
+ - `Incorrect: There is a significant difference between these two wildcards. See explanation for option (A).`
+- D) None of the above
+ - `Incorrect: Option (A) correctly describes the difference between these two wildcards.`
+
+**Question 88: What are some of the benefits of using generics in Java?**
+- A) Generics can help to improve type safety.
+ - `Incorrect: While this statement is true, it is not the only benefit of using generics in Java.`
+- B) Generics can help to improve performance.
+ - `Incorrect: While this statement is partially true (as generics can reduce the need for runtime type checking and casting), it is not the only benefit of using generics in Java.`
+- C) Generics can help to make code more readable.
+ - `Incorrect: While this statement is true, it is not the only benefit of using generics in Java.`
+- D) All of the above
+ - `Correct: Generics in Java can help improve type safety, potentially improve performance (by reducing the need for runtime type checking and casting), and make code more readable and structured.`
From 4daf212a8275239980359ca7414df27f0c81b256 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Thu, 25 May 2023 11:14:15 +0530
Subject: [PATCH 167/178] Create Q13-Generics.md
---
00-Quiz-Explanation/Q13-Generics.md | 103 ++++++++++++++++++++++++++++
1 file changed, 103 insertions(+)
create mode 100644 00-Quiz-Explanation/Q13-Generics.md
diff --git a/00-Quiz-Explanation/Q13-Generics.md b/00-Quiz-Explanation/Q13-Generics.md
new file mode 100644
index 00000000..98fdf9ea
--- /dev/null
+++ b/00-Quiz-Explanation/Q13-Generics.md
@@ -0,0 +1,103 @@
+**Question 79: What is the purpose of generics in Java?**
+- A) To allow for type safety
+ - `Correct: Generics are used in Java to ensure type safety. This means that the type of objects stored in a collection is known, reducing the risk of runtime errors.`
+- B) To improve performance
+ - `Incorrect: Generics do not directly contribute to the performance of Java code. They do, however, increase type safety, which can indirectly lead to performance improvements by reducing the need for runtime type checking and casting.`
+- C) To make code more readable
+ - `Incorrect: While the use of generics can make code more structured and predictable, their primary purpose is to provide type safety.`
+- D) All of the above
+ - `Incorrect: As explained above, the primary purpose of generics is to provide type safety, not to improve performance or readability directly.`
+
+**Question 80: What is the syntax for declaring a generic class?**
+- A) class MyClass
+ - `Correct: This is the correct syntax to declare a generic class in Java. The is a type parameter that stands for any type.`
+- B) class MyClass extends T>
+ - `Incorrect: This is not the correct syntax to declare a generic class in Java. A class cannot directly extend a type parameter.`
+- C) class MyClass implements T>
+ - `Incorrect: This is not the correct syntax to declare a generic class in Java. A class cannot directly implement a type parameter.`
+- D) None of the above
+ - `Incorrect: Option (A) is the correct syntax to declare a generic class.`
+
+**Question 81: What is the syntax for declaring a generic method?**
+- A) void myMethod(T t)
+ - `Incorrect: While this might look correct, a generic method must declare its type parameter(s) before the return type. The correct syntax is void myMethod(T t).`
+- B) T myMethod(T t)
+ - `Incorrect: While this might look correct, a generic method must declare its type parameter(s) before the return type. The correct syntax is T myMethod(T t).`
+- C) T myMethod()
+ - `Incorrect: While this might look correct, a generic method must declare its type parameter(s) before the return type. The correct syntax is T myMethod().`
+- D) None of the above
+ - `Correct: None of the above options correctly declare a generic method. The correct syntax is return_type methodName(T t)`
+
+**Question 82: What is the difference between a generic class and a non-generic class?**
+- A) A generic class can only contain objects of a specific type, while a non-generic class can contain objects of any type.
+ - `Incorrect: A generic class can actually contain objects of any given type, not only a specific type. It's the type parameter that provides the flexibility to use any type.`
+- B) A generic class can be used with any type of object, while a non-generic class can only be used with objects of a specific type.
+ - `Correct: A generic class can be used with any type of object because of its type parameter. A non-generic class usually operates on specific, hard-coded types.`
+- C) There is no difference between a generic class and a non-generic class.
+ - `Incorrect: There is a significant difference between a generic and a non-generic class. The main difference lies in type safety and reusability.`
+- D) None of the above
+ - `Incorrect: Option (B) correctly describes the difference between
+
+ a generic class and a non-generic class.`
+
+**Question 83: What is the purpose of type parameters in generics?**
+- A) To allow for type safety
+ - `Correct: Type parameters allow for type safety by ensuring that the objects being used match the declared type.`
+- B) To improve performance
+ - `Incorrect: While generics can indirectly lead to better performance by reducing the need for runtime type checking and casting, the main purpose of type parameters is not performance improvement.`
+- C) To make code more readable
+ - `Incorrect: While type parameters can make code more structured and predictable, the main purpose of type parameters is to ensure type safety.`
+- D) All of the above
+ - `Incorrect: As mentioned above, the main purpose of type parameters is to provide type safety.`
+
+**Question 84: What is the difference between a type parameter and a variable?**
+- A) A type parameter is a placeholder for a type, while a variable is a placeholder for a value.
+ - `Correct: A type parameter is a placeholder for a type, and it will be replaced with a real type when an instance of the generic class or method is created. On the other hand, a variable is a placeholder for a value and can be assigned different values during program execution.`
+- B) A type parameter is a variable that can only contain objects of a specific type, while a variable can contain objects of any type.
+ - `Incorrect: A type parameter is not a variable; it's a placeholder for a type, not for a value.`
+- C) There is no difference between a type parameter and a variable.
+ - `Incorrect: There is a significant difference between a type parameter and a variable. A type parameter is a placeholder for a type, while a variable is a placeholder for a value.`
+- D) None of the above
+ - `Incorrect: Option (A) correctly describes the difference between a type parameter and a variable.`
+
+**Question 85: What is the difference between a upper bound and a lower bound for a type parameter?**
+- A) A upper bound is the maximum type that a type parameter can be, while a lower bound is the minimum type that a type parameter can be.
+ - `Correct: In generics, an upper bound is declared using the keyword 'extends' and allows you to use a type parameter that is a subtype of a specific class or interface. On the other hand, a lower bound is declared using the keyword 'super' and allows you to use a type parameter that is a supertype of a specific class or interface.`
+- B) A upper bound is the minimum type that a type parameter can be, while a lower bound is the maximum type that a type parameter can be.
+ - `Incorrect: It's the other way around. See explanation for option (A).`
+- C) There is no difference between an upper bound and a lower bound.
+ - `Incorrect: There is a significant difference between an upper bound and a lower bound in terms of type parameters in generics.`
+- D) None of the above
+ - `Incorrect: Option (A) correctly describes the difference between an upper bound and a lower bound for a type parameter.`
+
+**Question 86: What is the purpose of wildcards in generics?**
+- A) To allow for type safety
+ - `Incorrect: While wildcards can contribute to type safety by ensuring that only compatible types are used, their main purpose is to enhance the flexibility and reusability of generic classes and methods.`
+- B) To improve performance
+ - `Incorrect: The main purpose of wildcards in generics is not to improve performance.`
+- C) To
+
+ make code more readable
+ - `Incorrect: The main purpose of wildcards in generics is not to make code more readable. Their primary role is to improve flexibility and reusability.`
+- D) None of the above
+ - `Correct: The main purpose of wildcards in generics is to improve flexibility and reusability, not directly ensuring type safety, improving performance or making code more readable.`
+
+**Question 87: What is the difference between a `? extends T` wildcard and a `? super T` wildcard?**
+- A) A `? extends T` wildcard can only be used to refer to objects of type T or any subtype of T, while a `? super T` wildcard can only be used to refer to objects of type T or any supertype of T.
+ - `Correct: The `? extends T` wildcard means that you can use any type that is a subclass of T (or T itself). Conversely, the `? super T` wildcard means that you can use any type that is a superclass of T (or T itself).`
+- B) A `? extends T` wildcard can only be used to refer to objects of type T, while a `? super T` wildcard can only be used to refer to objects of any type.
+ - `Incorrect: This description doesn't accurately represent the behavior of these wildcards. See explanation for option (A).`
+- C) There is no difference between a `? extends T` wildcard and a `? super T` wildcard.
+ - `Incorrect: There is a significant difference between these two wildcards. See explanation for option (A).`
+- D) None of the above
+ - `Incorrect: Option (A) correctly describes the difference between these two wildcards.`
+
+**Question 88: What are some of the benefits of using generics in Java?**
+- A) Generics can help to improve type safety.
+ - `Incorrect: While this statement is true, it is not the only benefit of using generics in Java.`
+- B) Generics can help to improve performance.
+ - `Incorrect: While this statement is partially true (as generics can reduce the need for runtime type checking and casting), it is not the only benefit of using generics in Java.`
+- C) Generics can help to make code more readable.
+ - `Incorrect: While this statement is true, it is not the only benefit of using generics in Java.`
+- D) All of the above
+ - `Correct: Generics in Java can help improve type safety, potentially improve performance (by reducing the need for runtime type checking and casting), and make code more readable and structured.`
From 620ffe98856a3ce0199d4685478f2c1bc5e25e9a Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Thu, 25 May 2023 11:30:43 +0530
Subject: [PATCH 168/178] Create Q14-FunctionalProgramming.md
---
01-Quiz/Q14-FunctionalProgramming.md | 350 +++++++++++++++++++++++++++
1 file changed, 350 insertions(+)
create mode 100644 01-Quiz/Q14-FunctionalProgramming.md
diff --git a/01-Quiz/Q14-FunctionalProgramming.md b/01-Quiz/Q14-FunctionalProgramming.md
new file mode 100644
index 00000000..f8ee1eb1
--- /dev/null
+++ b/01-Quiz/Q14-FunctionalProgramming.md
@@ -0,0 +1,350 @@
+## Step 01: Introducing Functional Programming
+
+**Question 1:** What is the purpose of functional programming?
+
+- A) To loop around a list and print its content.
+- B) To focus on the "how" of programming.
+- C) To focus on the "what" of programming.
+
+**Question 2:** What is the output of the following code?
+
+```java
+List list = List.of("Apple", "Banana", "Cat", "Dog");
+for(String str:list) {
+ System.out.println(str);
+}
+```
+
+- A) Apple, Banana, Cat, Dog
+- B) Apple
+- C) Banana, Cat, Dog
+
+**Question 3:** How does functional programming differ from the approach shown in Snippet-01?
+
+- A) It allows us to loop around a list.
+- B) It focuses on the "what" of programming.
+- C) It accesses individual elements of a list.
+
+## Step 02: Looping Through A List
+
+**Question 1:** What does the following code do?
+
+```java
+List list = List.of(1, 4, 7, 9);
+list.stream().forEach(elem -> System.out.println(elem));
+```
+
+- A) Prints the list of numbers.
+- B) Filters the stream based on some logic.
+- C) Passes a function as a method argument.
+
+**Question 2:** What is the purpose of using a lambda expression in the code?
+
+- A) To iterate over the list.
+- B) To filter the stream elements.
+- C) To execute a function for each element.
+
+**Question 3:** What is the output of the following code?
+
+```java
+List list = List.of(1, 4, 7, 9);
+list.stream().filter(num -> num%2 == 1).forEach(elem -> System.out.println(elem));
+```
+
+- A) 1, 7, 9
+- B) 4
+- C) 1, 4, 7, 9
+
+## Step 03: Filtering Results
+
+**Question 1:** What is the purpose of the `filter()` method?
+
+- A) To loop around a list and print its content.
+- B) To filter the stream elements based on some logic.
+- C) To focus on the "what" of programming.
+
+**Question 2:** What is the output of the following code?
+
+```java
+List list = List.of("Apple", "Bat", "Cat", "Dog");
+list.stream()
+ .filter(elem -> elem.endsWith("at"))
+ .forEach(element -> System.out.println(element));
+```
+
+- A) Apple, Bat, Cat, Dog
+- B) Bat, Cat
+- C) Cat
+
+**Question 3:** How would you filter the list of numbers to print only the even numbers?
+
+- A) `list.stream().filter(num -> num%2 == 0)`
+- B) `list.stream().filter(num -> num%2 == 1)`
+- C) `list.stream().filter(num -> num%2 == 2)`
+
+## Step 05: Streams - Aggregated Results
+
+**Question 1:** What is the purpose of the `reduce()` method in functional programming?
+
+- A) To loop around a list and print its content.
+- B) To filter the stream elements based on some logic.
+- C) To aggregate data into a single result.
+
+**Question 2:** What is the output of the following code?
+
+```java
+List numbers = List.of(4, 6, 8, 13, 3, 15);
+int sum = numbers.stream()
+ .reduce(0, (num1, num2) -> num1 + num2);
+System.out.println(sum);
+```
+
+- A) 49
+- B) 31
+- C) 34
+
+**Question 3:** How does the `reduce()` method work in the given code?
+
+- A) It adds all the numbers in the list.
+- B) It filters the even numbers in the list.
+- C) It applies a lambda expression to aggregate the numbers.
+
+## Step 06: Functional Programming v Structured Programming
+
+**Question 1:** What is the difference between Structured Programming (SP) and Functional Programming (FP) in terms of mutations?
+
+- A) SP involves mutations, while FP avoids mutations.
+- B) SP doesn't involve mutations, while FP allows mutations.
+- C) Both SP and FP involve mutations.
+
+**Question 2:** How does SP differ from FP in terms of specifying the computation?
+
+- A) SP specifies both what to do and how to do it.
+- B) FP specifies what to do, but not how to do it.
+- C) Both SP and FP specify what to do and how to do it.
+
+**Question 3:** Which method in the given code follows the Functional Programming (FP) approach?
+
+- A) `basicSum()`
+- B) `fpSum()`
+- C) Both `basicSum()` and `fpSum()`
+
+## Step 07: Some FP Terminology
+
+**Question 1:** What is a lambda expression in functional programming?
+
+- A) A method that performs a specific computation.
+- B) A sequence of elements in a stream.
+- C) A concise way to represent a function or behavior.
+
+**Question 2:** How is a lambda expression different from a regular method?
+
+- A) A lambda expression cannot have multiple lines of code.
+- B) A lambda expression cannot take any parameters.
+- C) A lambda expression is a more concise representation of a method.
+
+**Question 3:** What are intermediate operations and terminal operations in streams?
+
+- A) Intermediate operations produce a single result, while terminal operations produce another stream of elements.
+- B) Intermediate operations take a stream and return a single result, while terminal operations take a stream and produce another stream of elements.
+- C) Intermediate operations modify the stream, while terminal operations produce a single result or a collection of objects.
+
+
+
+## Step 08: Intermediate Stream Operations
+
+**Question 1:** What is the purpose of the `sorted()` method in stream operations?
+
+- A) To filter the stream elements based on some logic.
+- B) To preserve the elements in natural sorted order.
+- C) To compute new results from the input stream elements.
+
+**Question 2:** What is the purpose of the `distinct()` method in stream operations?
+
+- A) To sort the stream elements in ascending order.
+- B) To return only the unique elements of the input stream.
+- C) To compute the square of each element in the input stream.
+
+**Question 3:** What is the output of the following code?
+
+```java
+List numbers = List.of(3, 5, 3, 213, 45, 5, 7);
+numbers.stream().distinct().sorted().forEach(elem -> System.out.println(elem));
+```
+
+- A) 3, 5, 7, 45, 213
+- B) 3, 5, 213, 45, 7
+- C) 3, 3, 5, 5, 7, 45, 213
+
+## Step 09: Programming Exercise FP-PE-01
+
+**Question 1:** What is the purpose of the `map()` method in the `printFPSquares()` method?
+
+- A) To filter the stream elements based on some logic.
+- B) To preserve the elements in natural sorted order.
+- C) To compute the square of each element in the input stream.
+
+**Question 2:** How would you modify the `printLowerCases()` method to print all the strings in lowercase?
+
+- A) Use the `map()` method with a lambda expression to convert each string to lowercase.
+- B) Use the `filter()` method with a lambda expression to filter out lowercase strings.
+- C) Use the `sorted()` method with a lambda expression to sort the strings in lowercase order.
+
+**Question 3:** How does the `printLengths()` method calculate the length of each string?
+
+- A) It uses the `filter()` method with a lambda expression to filter out strings based on their length.
+- B) It uses the `sorted()` method with a lambda expression to sort the strings based on their length.
+- C) It uses the `map()` method with a lambda expression to transform each string into its length.
+
+## Step 10: Terminal Operations
+
+**Question 1:** What does the `reduce()` method do in terminal operations?
+
+- A) It sorts the stream elements in ascending order.
+- B) It returns a single result by combining the elements of the stream.
+- C) It returns only the unique elements of the input stream.
+
+**Question 2:** How does the `max()` method differ from `reduce()` in the given code?
+
+- A) `max()` returns the maximum element from the stream, while `reduce()` combines all the elements into a single result.
+- B) `max()` sorts the stream elements in ascending order, while `reduce()` sorts them in descending order.
+- C) `max()` applies a lambda expression to compute a single result, while `reduce()` applies a different lambda expression.
+
+**Question 3:** What is the purpose of the `Optional` type in stream operations?
+
+- A) To provide an alternative result when the stream is empty.
+- B) To handle null values in the stream elements.
+- C) To convert the stream into a collection.
+
+
+## Step 11: More Stream Operations
+
+**Question 1:** What is the output of the following code?
+
+```java
+List numbers = List.of(23, 12, 34, 53);
+List evens = numbers.stream()
+ .filter(n -> n%2==0)
+ .collect(Collectors.toList());
+System.out.println(evens);
+```
+
+- A) [23, 12, 34, 53]
+- B) [12, 34]
+- C) [23, 53]
+
+**Question 2:** How would you modify the code to create a list of the odd numbers from the `numbers` list?
+
+- A) Change the condition in the lambda expression to `n%2==1`.
+- B) Replace `filter()` with `sorted()` method.
+- C) Use `map()` instead of `filter()`.
+
+**Question 3:** What is the purpose of the `collect()` method in stream operations?
+
+- A) To compute a single result by combining the elements of the stream.
+- B) To convert the stream into a collection or other data structure.
+- C) To filter the stream elements based on some logic.
+
+## Step 12: The Optional class
+
+**Question 1:** What does the `Optional` class represent in stream operations?
+
+- A) It represents a nullable result from a terminal stream operation.
+- B) It represents an intermediate stream operation.
+- C) It represents a lambda expression in functional programming.
+
+**Question 2:** How can you check if an `Optional` object contains a valid result?
+
+- A) By calling the `get()` method on the object.
+- B) By invoking the `isPresent()` method on the object.
+- C) By using the `orElse()` method with a default value.
+
+**Question 3:** What does the `orElse()` method do in the context of `Optional`?
+
+- A) It returns the maximum element from the stream.
+- B) It handles exceptions during stream operations.
+- C) It provides a default value if the result is empty.
+
+## Step 13: Functional Interfaces: Predicate
+
+**Question 1:** What is a functional interface in Java?
+
+- A) An interface that contains only one abstract method.
+- B) An interface that can be used to define lambda expressions.
+- C) An interface that represents a logical condition or test.
+
+**Question 2:** What is the purpose of the `Predicate` interface in stream operations?
+
+- A) It is used to collect the elements of a stream into a list.
+- B) It is used to filter elements based on a logical condition.
+- C) It is used to calculate a single result from a stream.
+
+**Question 3:** How can you use a lambda expression to implement a `Predicate`?
+
+- A) By overriding the `test()` method in the `Predicate` interface.
+- B) By implementing the `Predicate` interface directly in a class.
+- C) By calling the `filter()` method with a lambda expression as an argument.
+
+
+
+## Step 14: Functional Interfaces: Consumer
+
+**Question 1:** What is the purpose of the `Consumer` interface in stream operations?
+
+- A) It is used to filter elements based on a logical condition.
+- B) It is used to perform an action on each element of the stream.
+- C) It is used to transform the elements of the stream.
+
+**Question 2:** How can you implement a custom `Consumer` interface?
+
+- A) By overriding the `test()` method in the `Consumer` interface.
+- B) By implementing the `Consumer` interface directly in a class.
+- C) By using a lambda expression as an argument to the `forEach()` method.
+
+**Question 3:** What does the `accept()` method of the `Consumer` interface do?
+
+- A) It applies a transformation to the input element.
+- B) It performs an action on the input element.
+- C) It filters the input element based on a condition.
+
+## Step 15: More Functional Interfaces
+
+**Question 1:** What is the purpose of the `map()` operation in stream operations?
+
+- A) It is used to filter the elements of a stream based on a condition.
+- B) It is used to transform the elements of a stream using a lambda expression.
+- C) It is used to combine the elements of a stream into a single result.
+
+**Question 2:** What is the signature of the `map()` operation in the `Stream` interface?
+
+- A) ` Stream map(Function super T, ? extends R> mapper)`
+- B) ` Stream map(Predicate predicate)`
+- C) ` Stream map(Consumer super S> action)`
+
+**Question 3:** What is the purpose of the `apply()` method in the `Function` interface?
+
+- A) It performs an action on the input element.
+- B) It filters the input element based on a condition.
+- C) It applies a transformation to the input element.
+
+## Step 16: Introducing Method References
+
+**Question 1:** What is a method reference in Java?
+
+- A) It is a reference to a static method or an instance method.
+- B) It is a reference to a lambda expression.
+- C) It is a reference to a functional interface.
+
+**Question 2:** How can you use a method reference to replace a lambda expression?
+
+- A) By using the `apply()` method of a functional interface.
+- B) By overriding the `accept()` method of a functional interface.
+- C) By referring to the method directly using the `::` operator.
+
+**Question 3:** How can you use a method reference to call an instance method?
+
+- A) By specifying the class name followed by the method name.
+- B) By using the `apply()` method of a functional interface.
+- C) By using the `::` operator followed by the method name.
+
+
From 45d32ebba35ba660606fd482214582756b789f6e Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Thu, 25 May 2023 11:39:16 +0530
Subject: [PATCH 169/178] Create Q15-ThreadsAndConcurrency.md
---
01-Quiz/Q15-ThreadsAndConcurrency.md | 425 +++++++++++++++++++++++++++
1 file changed, 425 insertions(+)
create mode 100644 01-Quiz/Q15-ThreadsAndConcurrency.md
diff --git a/01-Quiz/Q15-ThreadsAndConcurrency.md b/01-Quiz/Q15-ThreadsAndConcurrency.md
new file mode 100644
index 00000000..924f3b31
--- /dev/null
+++ b/01-Quiz/Q15-ThreadsAndConcurrency.md
@@ -0,0 +1,425 @@
+## Step 01: Concurrent Tasks: Extending Thread
+
+### Question 1
+What is the output of the following code snippet?
+
+```java
+public class ThreadBasicsRunner {
+ public static void main(String[] args) {
+ //Task1
+ for(int i=101; i<=199; i++) {
+ System.out.print(i + " ");
+ }
+ System.out.println("\nTask1 Done");
+
+ //Task2
+ for(int i=201; i<=299; i++) {
+ System.out.print(i + " ");
+ }
+
+ System.out.println("\nTask2 Done");
+
+ //Task3
+ for(int i=301; i<=399; i++) {
+ System.out.print(i + " ");
+ }
+ System.out.println("\nTask3 Done");
+
+ System.out.println("Main Done");
+ }
+}
+```
+
+A) 101 102 103 ... 199
+ Task1 Done
+ 201 202 203 ... 299
+ Task2 Done
+ 301 302 303 ... 399
+ Task3 Done
+ Main Done
+
+B) Task1 Done
+ Task2 Done
+ Task3 Done
+ 101 102 103 ... 199
+ 201 202 203 ... 299
+ 301 302 303 ... 399
+ Main Done
+
+C) 101 102 103 ... 199
+ 201 202 203 ... 299
+ 301 302 303 ... 399
+ Task1 Done
+ Task2 Done
+ Task3 Done
+ Main Done
+
+D) Main Done
+ 101 102 103 ... 199
+ Task1 Done
+ 201 202 203 ... 299
+ Task2 Done
+ 301 302 303 ... 399
+ Task3 Done
+
+### Question 2
+What is the purpose of the following code snippet?
+
+```java
+class Task1 extends Thread {
+ public void run() {
+ System.out.println("Task1 Started ");
+ for(int i=101; i<=199; i++) {
+ System.out.print(i + " ");
+ }
+ System.out.println("\nTask1 Done");
+ }
+}
+```
+
+A) It creates a new thread called `Task1` and defines its execution logic within the `run` method.
+
+B) It creates a new task called `Task1` that can be executed in parallel with other tasks.
+
+C) It extends the `Thread` class and overrides the `start` method to perform the tasks defined in the `run` method.
+
+D) It defines a separate class called `Task1` for organizing the code related to the task.
+
+### Question 3
+What is the difference between running a thread using `
+
+start()` and directly calling the `run()` method?
+
+A) There is no difference, both methods execute the thread's logic.
+
+B) The `start()` method creates a new thread and invokes the `run()` method, while calling `run()` directly executes the method in the current thread.
+
+C) The `start()` method is used for threads implemented with `Runnable`, while calling `run()` directly is used for threads extended from `Thread`.
+
+D) The `start()` method allows passing arguments to the thread, while calling `run()` directly does not support passing arguments.
+
+## Step 02: Concurrent Tasks - Implementing Runnable
+
+### Question 1
+What is the purpose of implementing the `Runnable` interface in Java?
+
+A) It allows a class to be treated as a thread by extending the `Thread` class.
+
+B) It provides a way to create multiple threads by implementing the `run()` method.
+
+C) It allows a class to define its own execution logic without extending the `Thread` class.
+
+D) It enables concurrent execution of tasks by implementing the `start()` method.
+
+### Question 2
+What is the difference between extending the `Thread` class and implementing the `Runnable` interface for creating threads?
+
+A) There is no significant difference between the two approaches; both can be used interchangeably.
+
+B) Extending the `Thread` class allows for simpler thread creation and execution compared to implementing `Runnable`.
+
+C) Implementing the `Runnable` interface allows for better object-oriented design and code reusability compared to extending `Thread`.
+
+D) Extending the `Thread` class provides better control over thread execution compared to implementing `Runnable`.
+
+### Question 3
+In the given code snippet, what is the purpose of the `Task2` class?
+
+```java
+class Task2 implements Runnable {
+ @Override
+ public void run() {
+ System.out.println("Task2 Started ");
+ for(int i=201; i<=299; i++) {
+ System.out.print(i + " ");
+ }
+ System.out.println("\nTask2 Done");
+ }
+}
+```
+
+A) It defines a new thread class that can be directly launched using the `start()` method.
+
+B) It represents a sub-task that can be executed concurrently by implementing the `run()` method.
+
+C) It extends the `Thread` class and overrides the `start()` method for task execution.
+
+D) It encapsulates the logic for task execution and allows it to be executed by a separate thread.
+
+
+## Step 03: The Thread Life-cycle
+
+### Question 1
+What is the initial state of a thread when it is created but its `start()` method hasn't been invoked?
+
+A) RUNNING
+
+B) RUNNABLE
+
+C) BLOCKED/WAITING
+
+D) NEW
+
+### Question 2
+When does a thread enter the TERMINATED/DEAD state?
+
+A) After the execution of the `run()` method is completed.
+
+B) After the `start()` method is invoked.
+
+C) After the `join()` method is called on the thread.
+
+D) After the thread is created using the `new` keyword.
+
+### Question 3
+Which of the following states is a thread in when it is ready to be executed but not currently running?
+
+A) RUNNING
+
+B) RUNNABLE
+
+C) BLOCKED/WAITING
+
+D) NEW
+
+## Step 04: Thread Priorities
+
+### Question 1
+What is the range of thread priorities in Java?
+
+A) 1 to 100
+
+B) 1 to 1000
+
+C) 1 to 10
+
+D) 0 to 10
+
+### Question 2
+What is the default priority assigned to a thread in Java?
+
+A) 1
+
+B) 5
+
+C) 10
+
+D) 0
+
+### Question 3
+What method is used to change the priority of a thread in Java?
+
+A) `setPriority(int)`
+
+B) `changePriority(int)`
+
+C) `updatePriority(int)`
+
+D) `modifyPriority(int)`
+
+## Step 05: Communicating Threads
+
+### Question 1
+What is the purpose of the `join()` method in Java?
+
+A) It pauses the execution of a thread until it is explicitly resumed.
+
+B) It sets the priority of a thread to the highest level.
+
+C) It allows one thread to wait for the completion of another thread.
+
+D) It terminates a thread and frees up system resources.
+
+### Question 2
+In the given code snippet, when will the execution of Task3 begin?
+
+```java
+task1.join();
+task2Thread.join();
+
+System.out.print("\nTask3 Kicked Off\n");
+for(int i=301; i<=399; i++) {
+ System.out.print(i + " ");
+}
+```
+
+A) After Task1 starts
+
+B) After Task2 starts
+
+C) After Task1 and Task2 complete
+
+D) Before Task1 and Task2 start
+
+### Question 3
+What is the purpose of using the `join()` method on threads?
+
+A) To synchronize the execution of multiple threads.
+
+B) To pause the execution of a thread temporarily.
+
+C) To terminate a thread.
+
+D) To change the priority of a thread.
+
+
+## Step 07: Thread Utilities
+
+### Question 1
+What is the purpose of the `sleep()` method in Java?
+
+A) It pauses the execution of a thread for a specified number of milliseconds.
+
+B) It terminates a thread and frees up system resources.
+
+C) It changes the priority of a thread.
+
+D) It allows one thread to wait for the completion of another thread.
+
+### Question 2
+Which method is used to request the thread scheduler to execute some other thread?
+
+A) `wait()`
+
+B) `join()`
+
+C) `sleep()`
+
+D) `yield()`
+
+## Step 08: Drawbacks of earlier approaches
+
+### Question 1
+What is a drawback of using the Thread class or Runnable interface for managing threads?
+
+A) No fine-grained control over thread execution.
+
+B) Difficult to maintain when managing multiple threads.
+
+C) No way to get the result from a sub-task.
+
+D) All of the above.
+
+### Question 2
+Which of the following methods is NOT a part of the Thread class for synchronization?
+
+A) `start()`
+
+B) `join()`
+
+C) `sleep()`
+
+D) `wait()`
+
+## Step 09: Introducing ExecutorService
+
+### Question 1
+What is the ExecutorService used for in Java?
+
+A) To synchronize the execution of multiple threads.
+
+B) To pause the execution of a thread temporarily.
+
+C) To manage and control the execution of threads.
+
+D) To terminate a thread and free up system resources.
+
+### Question 2
+Which method is used to create a single-threaded ExecutorService?
+
+A) `newSingleThreadExecutor()`
+
+B) `newFixedThreadPool()`
+
+C) `newCachedThreadPool()`
+
+D) `newScheduledThreadPool()`
+
+
+
+## Step 10: Executor - Customizing Number Of Threads
+
+### Question 1
+Which method is used to create a fixed-size thread pool with a specified number of threads?
+
+A) `newSingleThreadExecutor()`
+
+B) `newFixedThreadPool()`
+
+C) `newCachedThreadPool()`
+
+D) `newScheduledThreadPool()`
+
+### Question 2
+What happens if more tasks are submitted to an ExecutorService than the number of threads in the thread pool?
+
+A) The additional tasks are queued and executed when a thread becomes available.
+
+B) The additional tasks are discarded and not executed.
+
+C) The ExecutorService automatically adds more threads to the thread pool to accommodate the tasks.
+
+D) The additional tasks cause an exception to be thrown.
+
+### Question 3
+Which of the following statements is true about the ExecutorService?
+
+A) It allows for fine-grained control over the execution of threads.
+
+B) It is used to pause the execution of a thread temporarily.
+
+C) It is used to manage and control the execution of threads.
+
+D) It is used to terminate a thread and free up system resources.
+
+
+## Step 11: ExecutorService: Returning Values From Tasks
+
+### Question 1
+Which interface is used to create sub-tasks that return a result?
+
+A) `Thread`
+
+B) `Runnable`
+
+C) `Callable`
+
+D) `ExecutorService`
+
+### Question 2
+What method is used to submit a `Callable` task to an `ExecutorService` and obtain a `Future` object representing the task's result?
+
+A) `execute()`
+
+B) `submit()`
+
+C) `invokeAll()`
+
+D) `invokeAny()`
+
+### Question 3
+How can you retrieve the result of a `Callable` task from a `Future` object?
+
+A) Using the `get()` method of the `Future` object
+
+B) Using the `run()` method of the `Callable` task
+
+C) Using the `call()` method of the `Callable` task
+
+D) Using the `result()` method of the `Future` object
+
+## Step 12: Executor - Wait Only For The Fastest Task
+
+### Question 1
+What method of `ExecutorService` can be used to wait for the result of the fastest completed task from a collection of `Callable` tasks?
+
+A) `execute()`
+
+B) `submit()`
+
+C) `invokeAll()`
+
+D) `invokeAny()`
+
+
+
From 5abd8a337d5ddfb700ad7ac500b763ab41962526 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Thu, 25 May 2023 11:46:42 +0530
Subject: [PATCH 170/178] Create Q16-ExceptionHandling.md
---
01-Quiz/Q16-ExceptionHandling.md | 263 +++++++++++++++++++++++++++++++
1 file changed, 263 insertions(+)
create mode 100644 01-Quiz/Q16-ExceptionHandling.md
diff --git a/01-Quiz/Q16-ExceptionHandling.md b/01-Quiz/Q16-ExceptionHandling.md
new file mode 100644
index 00000000..2f0eaea9
--- /dev/null
+++ b/01-Quiz/Q16-ExceptionHandling.md
@@ -0,0 +1,263 @@
+## Step 1: Introducing Exceptions
+
+**Question 1:** What is an exception in Java?
+
+- A) An error that occurs during the execution of a program.
+- B) A condition that indicates the successful completion of a program.
+- C) A statement that is used to handle errors in a program.
+
+**Question 2:** Which of the following is an example of an exception?
+
+- A) A program running out of memory.
+- B) A division by zero error.
+- C) Both A and B.
+
+**Question 3:** What happens if an exception is not handled in a program?
+
+- A) The program continues running normally.
+- B) The program terminates abruptly and an error message is displayed.
+- C) The program enters a loop until the exception is resolved.
+
+## Step 2: Handling An Exception
+
+**Question 1:** How can you handle an exception in Java?
+
+- A) By using the `try-catch` block.
+- B) By using the `if-else` statement.
+- C) By using the `throw` keyword.
+
+**Question 2:** What is the purpose of the `catch` block in a `try-catch` block?
+
+- A) To define the code that may throw an exception.
+- B) To handle the exception and provide an alternative code path.
+- C) To specify the type of exception to be caught.
+
+**Question 3:** What happens if an exception is caught in a `catch` block?
+
+- A) The program continues running normally after the `catch` block.
+- B) The program terminates abruptly and an error message is displayed.
+- C) The program enters a loop until the exception is resolved.
+
+
+
+## Step 3: The Exception Hierarchy
+
+**Question 1:** What is the root class of the Java exception hierarchy?
+
+- A) `RuntimeException`
+- B) `Exception`
+- C) `Throwable`
+
+**Question 2:** Which of the following is true about the exception hierarchy in Java?
+
+- A) All exceptions in Java are subclasses of `Exception`.
+- B) `NullPointerException` is a subclass of `RuntimeException`.
+- C) Both A and B.
+
+**Question 3:** Why is it important to understand the exception hierarchy in Java?
+
+- A) It helps in determining the type of exception to catch.
+- B) It provides a way to handle different types of exceptions in a program.
+- C) Both A and B.
+
+## Step 4: The Need For `finally`
+
+**Question 1:** What happens if a resource is not properly released in a program?
+
+- A) The program continues running normally.
+- B) The program terminates abruptly and an error message is displayed.
+- C) The resource remains in use and may cause issues in the program.
+
+**Question 2:** How can you ensure that a resource is always released, even if an exception occurs?
+
+- A) By using the `try-catch` block.
+- B) By using the `finally` block.
+- C) By using the `throw` keyword.
+
+**Question 3:** When is the code inside the `finally` block executed?
+
+- A) Only when an exception occurs.
+- B) Only when there is no exception.
+- C) Whether an exception occurs or not.
+
+
+## Step 5: Programming Puzzles - PP-01
+
+**Puzzle-01:** Would the `finally` clause be executed if the statement `//str = "Hello";` remains as-is?
+
+- A) Yes
+- B) No
+
+**Puzzle-02:** When will code in a `finally` clause not get executed?
+
+- A) When an exception occurs in the `try` block.
+- B) When an exception occurs in the `catch` block.
+- C) When an exception occurs in preceding statements within the same `finally` clause.
+- D) When there is a JVM crash.
+
+**Puzzle-03:** Will the following code, a `try-finally` without a `catch`, compile?
+
+- A) Yes
+- B) No
+
+**Puzzle-04:** Will the following code, a `try` without a `catch` or a `finally`, compile?
+
+- A) Yes
+- B) No
+
+## Step 6: Handling Exceptions: Do We Have A Choice?
+
+**Question 1:** What is the purpose of the `throws` keyword in Java?
+
+- A) To handle an exception within a method using a `try-catch` block.
+- B) To declare that a method may throw a specific type of exception.
+- C) To indicate that an exception has occurred in a method.
+
+**Question 2:** What are the two ways to manage "Checked" exceptions in Java?
+
+- A) Handling with a `try-catch` block and using the `throws` specification.
+- B) Handling with a `try-finally` block and using the `throws` specification.
+- C) Handling with a `catch` block and using the `throws` specification.
+- D) Handling with a `try-catch-finally` block and using the `throws` specification.
+
+## Step 8: The Java Exception Hierarchy
+
+**Question 1:** Which exception class is at the root of the Java exception hierarchy?
+
+- A) `Error`
+- B) `Exception`
+- C) `InterruptedException`
+- D) `RuntimeException`
+
+**Question 2:** Which category of exceptions are unchecked exceptions?
+
+- A) `RuntimeException` and its sub-classes
+- B) All sub-classes of `Exception` excluding `RuntimeException`
+- C) `InterruptedException` and its sub-classes
+- D) All sub-classes of `Error`
+
+**Question 3:** Which category of exceptions are checked exceptions?
+
+- A) `RuntimeException` and its sub-classes
+- B) All sub-classes of `Exception` excluding `RuntimeException`
+- C) `InterruptedException` and its sub-classes
+- D) All sub-classes of `Error`
+
+## Step 9: Throwing an Exception
+
+**Question 1:** What is the purpose of throwing an exception in Java?
+
+- A) To handle an exceptional condition in the code.
+- B) To indicate that a method cannot be executed due to an exceptional condition.
+- C) To terminate the program abruptly.
+- D) To provide debugging information to the programmer.
+
+**Question 2:** Which keyword is used to throw an exception in Java?
+
+- A) `catch`
+- B) `throw`
+- C) `try`
+- D) `finally`
+
+**Question 3:** When should a checked exception be declared in a method signature?
+
+- A) When the method handles the checked exception using a `try-catch` block.
+- B) When the method may throw the checked exception during execution.
+- C) When the method does not handle the checked exception.
+- D) When the method is a sub-class of `RuntimeException`.
+
+## Step 10: Throwing A Custom Exception
+
+**Question 1:** What is the benefit of throwing a custom exception in Java?
+
+- A) It allows you to handle exceptional conditions specific to your code.
+- B) It provides a way to terminate the program abruptly.
+- C) It simplifies the exception handling process.
+- D) It improves the performance of the code.
+
+**Question 2:** Which type of exception will a custom exception become if it inherits from a checked exception class?
+
+- A) Checked exception
+- B) Unchecked exception
+- C) RuntimeException
+- D) Error
+
+**Question 3:** Which type of exception will a custom exception become if it inherits from an unchecked exception class?
+
+- A) Checked exception
+- B) Unchecked exception
+- C) RuntimeException
+- D) Error
+
+## Step 11: Introducing try-With-Resources
+
+**Question 1:** What is the purpose of the try-with-resources statement in Java?
+
+- A) To handle exceptions in a try-catch-finally block.
+- B) To automatically manage resources that implement the `AutoCloseable` interface.
+- C) To terminate the program abruptly.
+- D) To provide debugging information to the programmer.
+
+**Question 2:** Which interface must a resource implement to be compatible with try-with-resources?
+
+- A) `Closeable`
+- B) `AutoCloseable`
+- C) `Resource`
+- D) `Disposable`
+
+**Question 3:** What is the benefit of using try-with-resources over manually closing the resource?
+
+- A) It simplifies the exception handling process.
+- B) It ensures that the resource is always closed, even in case of exceptions.
+- C) It improves the performance of the code.
+- D) It allows the resource to be reused in multiple try-catch blocks.
+
+## Step 12: Programming Puzzle Set PP_02
+
+**Puzzle-01:**
+Does the following program handle the exception thrown?
+
+```java
+try {
+ AmountAdder.addAmounts(new Amount("RUPEE", 5), new Amount("RUPEE", 5));
+ String str = null;
+ str.toString();
+} catch (CurrenciesDoNotMatchException ex) {
+ ex.printStackTrace();
+}
+```
+
+- A) Yes
+- B) No
+
+**Puzzle-02:**
+Does the following code compile?
+
+```java
+try {
+ AmountAdder.addAmounts(new Amount("RUPEE", 5), new Amount("RUPEE", 5));
+ String str = null;
+ str.toString();
+} catch (Exception e) {
+ e.printStackTrace();
+} catch (CurrenciesDoNotMatchException ex) {
+ ex.printStackTrace();
+}
+```
+
+- A) Yes
+- B) No
+
+**Puzzle-03:**
+Does the following code compile?
+
+```java
+try {
+
+} catch (IOException | SQLException ex) {
+ ex.printStackTrace();
+}
+```
+
+- A) Yes
+- B) No
From 0dbc4dabf066144d1ed8406444b2f30983776e8b Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Thu, 25 May 2023 11:49:54 +0530
Subject: [PATCH 171/178] Create Q17-Files.md
---
01-Quiz/Q17-Files.md | 108 +++++++++++++++++++++++++++++++++++++++++++
1 file changed, 108 insertions(+)
create mode 100644 01-Quiz/Q17-Files.md
diff --git a/01-Quiz/Q17-Files.md b/01-Quiz/Q17-Files.md
new file mode 100644
index 00000000..e7bb7828
--- /dev/null
+++ b/01-Quiz/Q17-Files.md
@@ -0,0 +1,108 @@
+## File Operations Quiz
+
+**Question 1:**
+
+Which package provides utility classes and interfaces to interact with the native file system in Java?
+
+A) `java.io`
+B) `java.nio.file`
+C) `java.util`
+D) `java.lang`
+
+**Question 2:**
+
+What does the following code do?
+
+```java
+Files.list(Paths.get(".")).forEach(System.out::println);
+```
+
+A) Lists all the files and directories in the current directory
+B) Prints the contents of a specific file
+C) Lists the contents of a specified directory
+D) Throws an exception
+
+**Question 3:**
+
+What does the `Paths.get()` method return?
+
+A) The absolute path of a file or directory
+B) The name of a file or directory
+C) The path of a file or directory relative to the current directory
+D) The parent directory of a file or directory
+
+**Question 4:**
+
+What is the difference between `Files.list()` and `Files.walk()`?
+
+A) `Files.list()` lists only regular files, while `Files.walk()` recursively traverses directories
+B) `Files.list()` traverses directories up to a specified depth, while `Files.walk()` lists all files and directories
+C) `Files.list()` is used to list files, while `Files.walk()` is used to walk through directories
+D) There is no difference, they can be used interchangeably
+
+**Question 5:**
+
+What does the following code do?
+
+```java
+Files.walk(currentDirectory, 4).filter(path -> String.valueOf(path).contains(".java")).forEach(System.out::println);
+```
+
+A) Lists all files and directories up to a depth of 4, filtering only Java files
+B) Lists all Java files in the current directory and its subdirectories up to a depth of 4
+C) Throws an exception
+D) Filters all files and directories with names containing ".java"
+
+**Question 6:**
+
+What is the purpose of the `Files.readAllLines()` method?
+
+A) It reads the content of a file as a single string
+B) It reads the content of a file line by line and returns a list of strings
+C) It reads the content of a file as bytes
+D) It reads the content of a file character by character
+
+**Question 7:**
+
+What does the following code do?
+
+```java
+Files.lines(pathFileToRead).map(String::toLowerCase).forEach(System.out::println);
+```
+
+A) Converts the content of a file to lowercase and prints it
+B) Prints the content of a file as lowercase characters
+C) Throws an exception
+D) Converts the content of a file to lowercase and returns it as a list of strings
+
+**Question 8:**
+
+What is the purpose of the `Files.write()` method?
+
+A) It reads the content of a file
+B) It appends new content to a file
+C) It writes data to a file
+D) It deletes a file
+
+**Question 9:**
+
+What does the following code do?
+
+```java
+List list = List.of("Apple", "Boy", "Cat", "Dog", "Elephant");
+Files.write(pathFileToWrite, list);
+```
+
+A) Creates a new file with the specified list of strings as its content
+B) Writes the list of strings to an existing file
+C) Deletes the file specified by `pathFileToWrite`
+D) Prints the list of strings to the console
+
+**Question 10:**
+
+Which class provides methods for reading and writing files in Java?
+
+A) `Path`
+B) `File`
+C) `Files`
+D) `Scanner`
From 1390869300db0eaab86966edf00a3e1b22c2c5ca Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Thu, 25 May 2023 11:57:45 +0530
Subject: [PATCH 172/178] Create Q17-Files.md
---
00-Quiz-Explanation/Q17-Files.md | 116 +++++++++++++++++++++++++++++++
1 file changed, 116 insertions(+)
create mode 100644 00-Quiz-Explanation/Q17-Files.md
diff --git a/00-Quiz-Explanation/Q17-Files.md b/00-Quiz-Explanation/Q17-Files.md
new file mode 100644
index 00000000..547d1016
--- /dev/null
+++ b/00-Quiz-Explanation/Q17-Files.md
@@ -0,0 +1,116 @@
+**Question 89: Which package provides utility classes and interfaces to interact with the native file system in Java?**
+- A) java.io
+ - `Incorrect: While the java.io package does provide classes for file handling, it does not directly interact with the native file system.`
+- B) java.nio.file
+ - `Correct: The java.nio.file package provides classes that offer a comprehensive model for file I/O and for accessing the default file system.`
+- C) java.util
+ - `Incorrect: The java.util package does not provide classes for file handling. It mainly contains the collections framework, date and time facilities, random-number generator, and other utility classes.`
+- D) java.lang
+ - `Incorrect: The java.lang package does not provide classes for file handling. It provides classes that are fundamental to the design of the Java programming language.`
+
+**Question 90: What does the following code do?**
+```java
+Files.list(Paths.get(".")).forEach(System.out::println);
+```
+- A) Lists all the files and directories in the current directory
+ - `Correct: This line of code uses the java.nio.file API to list all the files and directories in the current directory and print them to the console.`
+- B) Prints the contents of a specific file
+ - `Incorrect: This code does not print the contents of any file, it prints the paths of the files and directories in the current directory.`
+- C) Lists the contents of a specified directory
+ - `Incorrect: The specified directory is ".", which means the current directory.`
+- D) Throws an exception
+ - `Incorrect: This code won't necessarily throw an exception unless there's a problem accessing the file system.`
+
+**Question 91: What does the Paths.get() method return?**
+- A) The absolute path of a file or directory
+ - `Incorrect: Paths.get() can return either a relative path or an absolute path, depending on the argument passed to it.`
+- B) The name of a file or directory
+ - `Incorrect: Paths.get() returns a Path object, which represents a path in the file system, not just the name of a file or directory.`
+- C) The path of a file or directory relative to the current directory
+ - `Incorrect: Paths.get() can return either a relative path or an absolute path, depending on the argument passed to it.`
+- D) The parent directory of a file or directory
+ - `Incorrect: Paths.get() returns a Path object, which represents a path in the file system. It does not specifically return the parent directory of a file or directory.`
+
+**Question 92: What is the difference between Files.list() and Files.walk()?**
+- A) Files.list() lists only regular files, while Files.walk() recursively traverses directories
+ - `Correct: Files.list() lists all the files and directories in a directory but does not recurse into subdirectories. Files.walk() does the same, but it also recursively traverses directories.`
+- B) Files.list() traverses directories up to a specified depth, while Files.walk() lists all files and directories
+ - `Incorrect: Files.list() does not traverse directories at all, it only lists the files and directories in the specified directory. Files.walk() is the method that can traverse directories up to a specified depth.`
+- C) Files.list() is used to list files, while Files.walk() is used to walk through directories
+ - `Incorrect: Both Files.list() and Files.walk() can be used to list files and directories. The difference is that Files.walk() also recursively traverses directories.`
+- D) There is no difference, they
+
+ can be used interchangeably
+ - `Incorrect: There is a significant difference between Files.list() and Files.walk(), as explained in the answer to option (A).`
+
+**Question 93: What does the following code do?**
+```java
+Files.walk(currentDirectory, 4).filter(path -> String.valueOf(path).contains(".java")).forEach(System.out::println);
+```
+- A) Lists all files and directories up to a depth of 4, filtering only Java files
+ - `Incorrect: This code does not list all files and directories up to a depth of 4. It only lists those files that have ".java" in their path.`
+- B) Lists all Java files in the current directory and its subdirectories up to a depth of 4
+ - `Correct: This code lists all files in the current directory and its subdirectories up to a depth of 4, but only those that have ".java" in their path are printed to the console.`
+- C) Throws an exception
+ - `Incorrect: This code won't necessarily throw an exception unless there's a problem accessing the file system.`
+- D) Filters all files and directories with names containing ".java"
+ - `Incorrect: The code filters and lists files with names containing ".java" only up to a depth of 4 in the directory hierarchy.`
+
+**Question 94: What is the purpose of the Files.readAllLines() method?**
+- A) It reads the content of a file as a single string
+ - `Incorrect: Files.readAllLines() reads all lines from a file and returns a List of strings, with each string being one line in the file.`
+- B) It reads the content of a file line by line and returns a list of strings
+ - `Correct: This method reads all lines from a file and returns a List of strings, with each string being one line in the file.`
+- C) It reads the content of a file as bytes
+ - `Incorrect: This method reads the content of a file as lines of text, not as bytes.`
+- D) It reads the content of a file character by character
+ - `Incorrect: This method reads the content of a file as lines of text, not character by character.`
+
+**Question 95: What does the following code do?**
+```java
+Files.lines(pathFileToRead).map(String::toLowerCase).forEach(System.out::println);
+```
+- A) Converts the content of a file to lowercase and prints it
+ - `Correct: This line of code reads all lines from the file specified by pathFileToRead, converts each line to lowercase, and then prints each line to the console.`
+- B) Prints the content of a file as lowercase characters
+ - `Incorrect: The code does not print the content as individual lowercase characters, but it does print the lines after converting them to lowercase.`
+- C) Throws an exception
+ - `Incorrect: This code won't necessarily throw an exception unless there's a problem accessing the file system.`
+- D) Converts the content of a file to lowercase and returns it as a list of strings
+ - `Incorrect: The code does not return anything. It prints the lines after converting them to lowercase.`
+
+**Question 96: What is the purpose of the Files.write() method?**
+- A) It reads the content of a file
+ - `Incorrect: The Files.write() method is used to write to a file, not to read its content.`
+- B) It appends new content to a file
+ - `Incorrect: The Files.write() method overwrites the existing content of a file by default. If you want to
+
+ append content to a file, you need to pass an additional argument to the method.`
+- C) It writes data to a file
+ - `Correct: The Files.write() method is used to write byte or character data to a file.`
+- D) It deletes a file
+ - `Incorrect: The Files.write() method is not used to delete files. There is a separate method, Files.delete(), for that purpose.`
+
+**Question 97: What does the following code do?**
+```java
+List list = List.of("Apple", "Boy", "Cat", "Dog", "Elephant");
+Files.write(pathFileToWrite, list);
+```
+- A) Creates a new file with the specified list of strings as its content
+ - `Correct: If the file specified by pathFileToWrite does not exist, this code will create a new file with the contents of the list. If the file already exists, this code will overwrite the existing content of the file with the contents of the list.`
+- B) Writes the list of strings to an existing file
+ - `Incorrect: While the code does write the list of strings to the file specified by pathFileToWrite, it does not require the file to exist beforehand. If the file does not exist, the code will create it.`
+- C) Deletes the file specified by pathFileToWrite
+ - `Incorrect: This code does not delete any files.`
+- D) Prints the list of strings to the console
+ - `Incorrect: This code writes the list of strings to a file, not to the console.`
+
+**Question 98: Which class provides methods for reading and writing files in Java?**
+- A) Path
+ - `Incorrect: The Path interface in the java.nio.file package represents a path in the file system, but it does not provide methods for reading and writing files.`
+- B) File
+ - `Incorrect: The File class in the java.io package provides methods for working with files and directories, but the methods for reading and writing files are provided by the java.nio.file.Files class in modern Java.`
+- C) Files
+ - `Correct: The java.nio.file.Files class provides static methods for reading and writing files.`
+- D) Scanner
+ - `Incorrect: The Scanner class in the java.util package is used for parsing text from various sources including files, but it is not the primary class for reading and writing files in Java.`
From 4529da942d1f1f5cb56ce742a5bfd1596cbce800 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Thu, 25 May 2023 12:16:31 +0530
Subject: [PATCH 173/178] Create Q16-ExceptionHandling.md
---
00-Quiz-Explanation/Q16-ExceptionHandling.md | 412 +++++++++++++++++++
1 file changed, 412 insertions(+)
create mode 100644 00-Quiz-Explanation/Q16-ExceptionHandling.md
diff --git a/00-Quiz-Explanation/Q16-ExceptionHandling.md b/00-Quiz-Explanation/Q16-ExceptionHandling.md
new file mode 100644
index 00000000..879c5741
--- /dev/null
+++ b/00-Quiz-Explanation/Q16-ExceptionHandling.md
@@ -0,0 +1,412 @@
+**Step 1: Introducing Exceptions**
+
+**Question 1: What is an exception in Java?**
+- A) An error that occurs during the execution of a program.
+ - `Correct: An exception in Java is an event that occurs during the execution of a program that disrupts the normal flow of instructions.`
+
+- B) A condition that indicates the successful completion of a program.
+ - `Incorrect: An exception doesn't indicate the successful completion of a program. Instead, it represents an error or unusual condition.`
+
+- C) A statement that is used to handle errors in a program.
+ - `Incorrect: An exception itself is not a statement used to handle errors. It's an event that occurs during the execution of a program.`
+
+**Question 2: Which of the following is an example of an exception?**
+- A) A program running out of memory.
+- B) A division by zero error.
+- C) Both A and B.
+ - `Correct: Both running out of memory and division by zero can cause exceptions in Java.`
+
+**Question 3: What happens if an exception is not handled in a program?**
+- A) The program continues running normally.
+ - `Incorrect: If an exception is not handled, it will cause the program to terminate abruptly, not continue running normally.`
+
+- B) The program terminates abruptly and an error message is displayed.
+ - `Correct: If an exception is not handled in a program, it will cause the program to terminate abruptly and an error message will be displayed.`
+
+- C) The program enters a loop until the exception is resolved.
+ - `Incorrect: An unhandled exception causes the program to terminate abruptly, not enter a loop.`
+
+**Step 2: Handling An Exception**
+
+**Question 1: How can you handle an exception in Java?**
+- A) By using the try-catch block.
+ - `Correct: In Java, exceptions can be handled using try-catch blocks.`
+
+- B) By using the if-else statement.
+ - `Incorrect: if-else statements are used for decision making, not exception handling.`
+
+- C) By using the throw keyword.
+ - `Incorrect: The throw keyword is used to manually throw an exception, not to handle it.`
+
+**Question 2: What is the purpose of the catch block in a try-catch block?**
+- A) To define the code that may throw an exception.
+ - `Incorrect: The code that may throw an exception is placed in the try block, not the catch block.`
+
+- B) To handle the exception and provide an alternative code path.
+ - `Correct: The catch block is used to handle the exception and provide an alternative code path when an exception occurs.`
+
+- C) To specify the type of exception to be caught.
+ - `Correct: In the declaration of a catch block, you specify the type of exception it can catch.`
+
+**Question 3: What happens if an exception is caught in a catch block?**
+- A) The program continues running normally after the catch block.
+ - `Correct: If an exception is caught in a catch block, the program will continue running normally after the catch block.`
+
+- B) The program terminates abruptly and an error message is displayed.
+ - `Incorrect: If an exception is caught in a catch block, the program doesn't terminate abruptly.`
+
+- C) The program enters a loop until the exception is resolved.
+ - `Incorrect: The program doesn't enter a loop when an exception is caught.`
+
+**Step 3: The Exception Hierarchy**
+
+**Question 1: What is the root class of the Java exception hierarchy?**
+- A) RuntimeException
+
+
+ - `Incorrect: RuntimeException is a subclass of Exception, not the root class of the exception hierarchy.`
+
+- B) Exception
+ - `Incorrect: Exception is a subclass of Throwable, not the root class of the exception hierarchy.`
+
+- C) Throwable
+ - `Correct: The Throwable class is the superclass of all errors and exceptions in Java. It's the root of the exception hierarchy.`
+
+**Question 2: Which of the following is true about the exception hierarchy in Java?**
+- A) All exceptions in Java are subclasses of Exception.
+ - `Incorrect: Not all exceptions in Java are subclasses of Exception. Error is a direct subclass of Throwable.`
+
+- B) NullPointerException is a subclass of RuntimeException.
+ - `Correct: NullPointerException is a subclass of RuntimeException.`
+
+- C) Both A and B.
+ - `Incorrect: Only B is correct.`
+
+**Question 3: Why is it important to understand the exception hierarchy in Java?**
+- A) It helps in determining the type of exception to catch.
+ - `Correct: Understanding the exception hierarchy can help in determining which exceptions can be caught by a specific catch block.`
+
+- B) It provides a way to handle different types of exceptions in a program.
+ - `Correct: Understanding the exception hierarchy can help in handling different types of exceptions in a program.`
+
+- C) Both A and B.
+ - `Correct: Both A and B are valid reasons for understanding the exception hierarchy.`
+
+**Step 4: The Need For finally**
+
+**Question 1: What happens if a resource is not properly released in a program?**
+- A) The program continues running normally.
+ - `Incorrect: If a resource is not properly released, it may cause resource leaks and other issues in the program.`
+
+- B) The program terminates abruptly and an error message is displayed.
+ - `Incorrect: A program does not necessarily terminate abruptly if a resource isn't properly released, though it could lead to problems.`
+
+- C) The resource remains in use and may cause issues in the program.
+ - `Correct: If a resource is not properly released, it remains in use and can cause issues like resource leaks.`
+
+**Question 2: How can you ensure that a resource is always released, even if an exception occurs?**
+- A) By using the try-catch block.
+ - `Incorrect: While a try-catch block can be used to handle exceptions, it doesn't ensure that resources are always released.`
+
+- B) By using the finally block.
+ - `Correct: The finally block is used to place important code that must be processed regardless of whether an exception is thrown or not. It's typically used for cleanup tasks such as closing database connections, I/O streams, etc.`
+
+- C) By using the throw keyword.
+ - `Incorrect: The throw keyword is used to manually throw an exception, not to ensure that resources are always released.`
+
+**Question 3: When is the code inside the finally block executed?**
+- A) Only when an exception occurs.
+ - `Incorrect: The finally block is executed regardless of whether an exception occurs.`
+
+- B) Only when there is no exception.
+ - `Incorrect: The finally block is executed regardless of whether an exception occurs.`
+
+- C) Whether an exception occurs or not.
+ - `Correct: The finally block is always executed, whether an exception occurs or not.`
+
+**Step 5: Programming Puzzles - PP-01**
+
+*Puzzle-01: Would the finally clause be executed if the statement //str = "Hello"; remains as-is?*
+- A) Yes
+ - `Correct: The finally block is always executed, regardless of what code
+
+ is commented out.`
+
+- B) No
+ - `Incorrect: The finally block is always executed, whether there's an exception or not.`
+
+*Puzzle-02: When will code in a finally clause not get executed?*
+- A) When an exception occurs in the try block.
+ - `Incorrect: Even if an exception occurs in the try block, the finally block will still be executed.`
+
+- B) When an exception occurs in the catch block.
+ - `Incorrect: Even if an exception occurs in the catch block, the finally block will still be executed.`
+
+- C) When an exception occurs in preceding statements within the same finally clause.
+ - `Incorrect: If an exception occurs in the finally block, the rest of the block may not be executed, but this depends on the specific scenario and is not generally true.`
+
+- D) When there is a JVM crash.
+ - `Correct: If the JVM crashes or if the system exits (either by calling System.exit or by a system-wide issue), the finally block may not execute.`
+
+*Puzzle-03: Will the following code, a try-finally without a catch, compile?*
+- A) Yes
+ - `Correct: In Java, you can use a try block without a catch block as long as you include a finally block.`
+
+- B) No
+ - `Incorrect: A try-finally block without a catch block will compile in Java.`
+
+*Puzzle-04: Will the following code, a try without a catch or a finally, compile?*
+- A) Yes
+ - `Incorrect: A try block must be followed by either a catch block, a finally block, or both.`
+
+- B) No
+ - `Correct: In Java, a try block must be followed by either a catch block, a finally block, or both.`
+
+**Step 6: Handling Exceptions: Do We Have A Choice?**
+
+**Question 1: What is the purpose of the throws keyword in Java?**
+- A) To handle an exception within a method using a try-catch block.
+ - `Incorrect: The throws keyword does not handle exceptions; it declares that a method might throw exceptions.`
+
+- B) To declare that a method may throw a specific type of exception.
+ - `Correct: The throws keyword is used in method signatures to declare that the method may throw the specified exceptions.`
+
+- C) To indicate that an exception has occurred in a method.
+ - `Incorrect: The throw keyword is used to indicate that an exception has occurred, not the throws keyword.`
+
+**Question 2: What are the two ways to manage "Checked" exceptions in Java?**
+- A) Handling with a try-catch block and using the throws specification.
+ - `Correct: Checked exceptions in Java can be managed either by handling them with a try-catch block or by using the throws specification in the method declaration.`
+
+- B) Handling with a try-finally block and using the throws specification.
+ - `Incorrect: While a try-finally block can ensure a block of code is always executed, it does not handle exceptions.`
+
+- C) Handling with a catch block and using the throws specification.
+ - `Incorrect: A catch block is part of a try-catch structure for handling exceptions, but it does not stand alone.`
+
+- D) Handling with a try-catch-finally block and using the throws specification.
+ - `Correct: Checked exceptions in Java can be managed either by handling them with a try-catch-finally block or by using the throws specification in the method declaration.`
+
+ **Step 8: The Java Exception Hierarchy**
+
+**Question 1: Which exception class is at the root of the Java exception hierarchy?**
+- A) Error
+ - `Incorrect: While Error is a subclass of Throwable, it is not the root of the Java exception hierarchy.`
+
+- B) Exception
+ - `Incorrect: While Exception is a subclass of Throwable, it is not the root of the Java exception hierarchy.`
+
+- C) InterruptedException
+ - `Incorrect: InterruptedException is a subclass of Exception, and it is not the root of the Java exception hierarchy.`
+
+- D) RuntimeException
+ - `Incorrect: RuntimeException is a subclass of Exception, and it is not the root of the Java exception hierarchy.`
+
+The correct answer is `Throwable`. This is the superclass of all errors and exceptions in the Java language.
+
+**Question 2: Which category of exceptions are unchecked exceptions?**
+- A) RuntimeException and its sub-classes
+ - `Correct: RuntimeException and its subclasses are unchecked exceptions in Java.`
+
+- B) All sub-classes of Exception excluding RuntimeException
+ - `Incorrect: This category includes checked exceptions, not unchecked exceptions.`
+
+- C) InterruptedException and its sub-classes
+ - `Incorrect: InterruptedException is a checked exception, not an unchecked exception.`
+
+- D) All sub-classes of Error
+ - `Correct: All subclasses of Error are also considered unchecked exceptions.`
+
+**Question 3: Which category of exceptions are checked exceptions?**
+- A) RuntimeException and its sub-classes
+ - `Incorrect: RuntimeException and its subclasses are unchecked exceptions, not checked exceptions.`
+
+- B) All sub-classes of Exception excluding RuntimeException
+ - `Correct: All subclasses of Exception excluding RuntimeException are checked exceptions.`
+
+- C) InterruptedException and its sub-classes
+ - `Correct: InterruptedException is a checked exception.`
+
+- D) All sub-classes of Error
+ - `Incorrect: All subclasses of Error are unchecked exceptions, not checked exceptions.`
+
+**Step 9: Throwing an Exception**
+
+**Question 1: What is the purpose of throwing an exception in Java?**
+- A) To handle an exceptional condition in the code.
+ - `Incorrect: Throwing an exception is a way of indicating an exceptional condition, not handling it.`
+
+- B) To indicate that a method cannot be executed due to an exceptional condition.
+ - `Correct: Exceptions are thrown to indicate that a method cannot continue execution due to an exceptional condition.`
+
+- C) To terminate the program abruptly.
+ - `Incorrect: While an unhandled exception can cause a program to terminate abruptly, the primary purpose of throwing an exception is to indicate an exceptional condition.`
+
+- D) To provide debugging information to the programmer.
+ - `Correct: When an exception is thrown, it can carry information about the error, which can aid in debugging.`
+
+**Question 2: Which keyword is used to throw an exception in Java?**
+- A) catch
+ - `Incorrect: The catch keyword is used to handle exceptions, not to throw them.`
+
+- B) throw
+ - `Correct: The throw keyword is used to throw an exception.`
+
+- C) try
+ - `Incorrect: The try keyword is used to enclose a block of code in which an exception might occur.`
+
+- D) finally
+ - `Incorrect: The finally keyword is used to enclose a block of code that must be executed regardless of whether an exception occurs.`
+
+**Question 3: When should a checked exception be declared in a method signature?**
+- A) When the method handles the checked exception using a try-catch block.
+ - `Incorrect: If the method handles the checked exception
+
+, it doesn't need to declare it.`
+
+- B) When the method may throw the checked exception during execution.
+ - `Correct: If a method might throw a checked exception, it should declare that in its method signature.`
+
+- C) When the method does not handle the checked exception.
+ - `Correct: If a method does not handle a checked exception, it must declare it in its method signature.`
+
+- D) When the method is a sub-class of RuntimeException.
+ - `Incorrect: The RuntimeException and its subclasses are unchecked exceptions, so they do not need to be declared in a method signature.`
+
+
+ **Step 10: Throwing A Custom Exception**
+
+**Question 1: What is the benefit of throwing a custom exception in Java?**
+- A) It allows you to handle exceptional conditions specific to your code.
+ - `Correct: Custom exceptions can be used to handle specific conditions that aren't covered by the standard Java exceptions.`
+
+- B) It provides a way to terminate the program abruptly.
+ - `Incorrect: The primary purpose of throwing a custom exception isn't to terminate the program abruptly, but to signal specific exceptional conditions in your code.`
+
+- C) It simplifies the exception handling process.
+ - `Correct: Custom exceptions can help simplify exception handling by providing more specific exceptions that are easier to handle in a meaningful way.`
+
+- D) It improves the performance of the code.
+ - `Incorrect: The creation of custom exceptions doesn't generally improve the performance of the code.`
+
+**Question 2: Which type of exception will a custom exception become if it inherits from a checked exception class?**
+- A) Checked exception
+ - `Correct: If a custom exception inherits from a checked exception, it will be a checked exception.`
+
+- B) Unchecked exception
+ - `Incorrect: Inheriting from a checked exception will not make the custom exception unchecked.`
+
+- C) RuntimeException
+ - `Incorrect: RuntimeException is a type of unchecked exception.`
+
+- D) Error
+ - `Incorrect: Error is not a type of exception.`
+
+**Question 3: Which type of exception will a custom exception become if it inherits from an unchecked exception class?**
+- A) Checked exception
+ - `Incorrect: If a custom exception inherits from an unchecked exception, it will be an unchecked exception.`
+
+- B) Unchecked exception
+ - `Correct: If a custom exception inherits from an unchecked exception, it will be an unchecked exception.`
+
+- C) RuntimeException
+ - `Correct: If a custom exception inherits from RuntimeException, it will be an unchecked exception as RuntimeException is a type of unchecked exception.`
+
+- D) Error
+ - `Incorrect: Error is not a type of exception.`
+
+**Step 11: Introducing try-With-Resources**
+
+**Question 1: What is the purpose of the try-with-resources statement in Java?**
+- A) To handle exceptions in a try-catch-finally block.
+ - `Incorrect: While try-with-resources can be used with a try-catch-finally block, its primary purpose is to automatically manage resources.`
+
+- B) To automatically manage resources that implement the AutoCloseable interface.
+ - `Correct: The primary purpose of try-with-resources is to automatically close resources that implement the AutoCloseable interface.`
+
+- C) To terminate the program abruptly.
+ - `Incorrect: The purpose of try-with-resources is not to terminate the program abruptly.`
+
+- D) To provide debugging information to the programmer.
+ - `Incorrect: The purpose of try-with-resources is not to provide debugging information, but to automatically manage resources.`
+
+**Question 2: Which interface must a resource implement to be compatible with try-with-resources?**
+- A) Closeable
+ - `Correct: Resources that implement the Closeable interface, which extends AutoCloseable, can be used with try-with-resources.`
+
+- B) AutoCloseable
+ - `Correct: Resources that implement the AutoCloseable interface can be used with try-with-resources.`
+
+- C) Resource
+ - `Incorrect: There is no Resource interface in Java.`
+
+- D) Disposable
+ - `Incorrect: There is no Disposable interface in Java.`
+
+**Question 3: What is the benefit of using try-with-resources over manually closing the resource?**
+- A
+
+) It simplifies the exception handling process.
+ - `Correct: Using try-with-resources can simplify exception handling by automatically closing resources, thus avoiding potential resource leaks.`
+
+- B) It ensures that the resource is always closed, even in case of exceptions.
+ - `Correct: The try-with-resources statement ensures that each resource is closed at the end of the statement, even if an exception is thrown.`
+
+- C) It improves the performance of the code.
+ - `Incorrect: Using try-with-resources doesn't directly improve the performance of the code.`
+
+- D) It allows the resource to be reused in multiple try-catch blocks.
+ - `Incorrect: The primary benefit of try-with-resources is automatic resource management, not reusability in multiple try-catch blocks.`
+
+
+**Step 12: Programming Puzzle Set PP_02**
+
+**Puzzle-01: Does the following program handle the exception thrown?**
+```java
+try {
+ AmountAdder.addAmounts(new Amount("RUPEE", 5), new Amount("RUPEE", 5));
+ String str = null;
+ str.toString();
+} catch (CurrenciesDoNotMatchException ex) {
+ ex.printStackTrace();
+}
+```
+- A) Yes
+ - `Incorrect: This program can handle `CurrenciesDoNotMatchException` but it doesn't handle `NullPointerException` which will be thrown when attempting to invoke `toString()` on a null string.`
+
+- B) No
+ - `Correct: Although `CurrenciesDoNotMatchException` is handled, the code will throw a `NullPointerException` when `str.toString();` is executed, and that exception isn't handled.`
+
+**Puzzle-02: Does the following code compile?**
+```java
+try {
+ AmountAdder.addAmounts(new Amount("RUPEE", 5), new Amount("RUPEE", 5));
+ String str = null;
+ str.toString();
+} catch (Exception e) {
+ e.printStackTrace();
+} catch (CurrenciesDoNotMatchException ex) {
+ ex.printStackTrace();
+}
+```
+- A) Yes
+ - `Incorrect: This code will not compile because the catch block for the superclass Exception is before the catch block for the subclass CurrenciesDoNotMatchException. In Java, catch blocks for more specific exception types must come before those for more general types.`
+
+- B) No
+ - `Correct: The code doesn't compile because the catch blocks are in the wrong order. The catch block for Exception (which is a superclass of all exceptions) should come after all other more specific exception catch blocks.`
+
+**Puzzle-03: Does the following code compile?**
+```java
+try {
+
+} catch (IOException | SQLException ex) {
+ ex.printStackTrace();
+}
+```
+- A) Yes
+ - `Correct: The code does compile. Since Java 7, you can catch multiple exception types in a single catch block using this syntax.`
+
+- B) No
+ - `Incorrect: The code does compile. The `IOException` and `SQLException` are being caught in a single catch block, which is a valid syntax in Java.`
+
+
From 80e60f6b73152fbfbc6d2910ec0664a1557604de Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Thu, 25 May 2023 12:29:00 +0530
Subject: [PATCH 174/178] Create Q15-ThreadsAndConcurrency.md
---
.../Q15-ThreadsAndConcurrency.md | 390 ++++++++++++++++++
1 file changed, 390 insertions(+)
create mode 100644 00-Quiz-Explanation/Q15-ThreadsAndConcurrency.md
diff --git a/00-Quiz-Explanation/Q15-ThreadsAndConcurrency.md b/00-Quiz-Explanation/Q15-ThreadsAndConcurrency.md
new file mode 100644
index 00000000..9a6f1736
--- /dev/null
+++ b/00-Quiz-Explanation/Q15-ThreadsAndConcurrency.md
@@ -0,0 +1,390 @@
+**Step 01: Concurrent Tasks: Extending Thread**
+
+**Question 1: What is the output of the following code snippet?**
+```java
+public class ThreadBasicsRunner {
+ public static void main(String[] args) {
+ //Task1
+ for(int i=101; i<=199; i++) {
+ System.out.print(i + " ");
+ }
+ System.out.println("\nTask1 Done");
+
+ //Task2
+ for(int i=201; i<=299; i++) {
+ System.out.print(i + " ");
+ }
+
+ System.out.println("\nTask2 Done");
+
+ //Task3
+ for(int i=301; i<=399; i++) {
+ System.out.print(i + " ");
+ }
+ System.out.println("\nTask3 Done");
+
+ System.out.println("Main Done");
+ }
+}
+```
+- A) 101 102 103 ... 199
+ Task1 Done
+ 201 202 203 ... 299
+ Task2 Done
+ 301 302 303 ... 399
+ Task3 Done
+ Main Done
+ - `Correct: The code runs in sequence, executing each task one after the other.`
+
+- B) Task1 Done
+ Task2 Done
+ Task3 Done
+ 101 102 103 ... 199
+ 201 202 203 ... 299
+ 301 302 303 ... 399
+ Main Done
+ - `Incorrect: The code first executes the tasks and then prints "Task Done" statements.`
+
+- C) 101 102 103 ... 199
+ 201 202 203 ... 299
+ 301 302 303 ... 399
+ Task1 Done
+ Task2 Done
+ Task3 Done
+ Main Done
+ - `Incorrect: The code prints "Task Done" after each task is completed.`
+
+- D) Main Done
+ 101 102 103 ... 199
+ Task1 Done
+ 201 202 203 ... 299
+ Task2 Done
+ 301 302 303 ... 399
+ Task3 Done
+ - `Incorrect: The code does not print "Main Done" until all tasks have completed.`
+
+**Question 2: What is the purpose of the following code snippet?**
+```java
+class Task1 extends Thread {
+ public void run() {
+ System.out.println("Task1 Started ");
+ for(int i=101; i<=199; i++) {
+ System.out.print(i + " ");
+ }
+ System.out.println("\nTask1 Done");
+ }
+}
+```
+- A) It creates a new thread called Task1 and defines its execution logic within the run method.
+ - `Correct: The Task1 class extends Thread, which means it is a new thread. The run method contains the logic to be executed when the thread starts.`
+
+- B) It creates a new task called Task1 that can be executed in parallel with other tasks.
+ - `Correct: Since Task1 is a thread, it can be executed in parallel with other tasks or threads.`
+
+- C) It extends the Thread class and overrides the start method to perform the tasks defined in the run method.
+ - `Incorrect: It doesn't override the start method but the run method.`
+
+- D) It defines a separate class called Task1 for organizing the code related to the task.
+ - `Incorrect: While it does create a separate class for the task, the main purpose is not just to organize code but to define a separate thread of execution.`
+
+**Question 3: What is the difference between running a thread using `start()` and directly calling the `run()` method?**
+
+- A) There is no difference, both methods execute the thread's logic.
+ - `Incorrect: While both execute the thread's logic, start() creates a new thread of control, whereas run() doesn't.`
+
+- B) The start() method creates a new thread and invokes the run() method, while calling run() directly executes the method in the current thread.
+ - `Correct: Calling start() launches a new thread and then invokes run(), whereas calling run() directly just executes in the current thread without creating a new one.`
+
+- C) The start() method is used for threads implemented with Runnable, while calling run() directly is used for threads extended from Thread.
+ - `Incorrect: Both Runnable and Thread classes can use the start() method to start a new thread.`
+
+- D) The start() method allows passing arguments to the thread, while calling run() directly does not support passing arguments.
+ - `Incorrect: Neither start() nor run() support passing arguments directly. If needed, arguments should be passed via the constructor.`
+
+**Step 02: Concurrent Tasks - Implementing Runnable**
+
+**Question 1: What is the purpose of implementing the Runnable interface in Java?**
+
+- A) It allows a class to be treated as a thread by extending the Thread class.
+ - `Incorrect: The Runnable interface does not extend the Thread class.`
+
+- B) It provides a way to create multiple threads by implementing the run() method.
+ - `Incorrect: Implementing the run() method in Runnable does not directly create multiple threads, it only provides the task that can be assigned to a thread.`
+
+- C) It allows a class to define its own execution logic without extending the Thread class.
+ - `Correct: The Runnable interface enables a class to define the code to be executed in a thread (defined in the run() method) without requiring the class to extend the Thread class.`
+
+- D) It enables concurrent execution of tasks by implementing the start() method.
+ - `Incorrect: The Runnable interface only includes the run() method, not the start() method.`
+
+**Question 2: What is the difference between extending the Thread class and implementing the Runnable interface for creating threads?**
+
+- A) There is no significant difference between the two approaches; both can be used interchangeably.
+ - `Incorrect: There are differences between the two approaches. Extending the Thread class might limit code reuse since Java doesn't support multiple inheritance. Implementing the Runnable interface is usually preferable.`
+
+- B) Extending the Thread class allows for simpler thread creation and execution compared to implementing Runnable.
+ - `Incorrect: While extending Thread may look simpler initially, implementing Runnable is often more flexible and promotes better design practices.`
+
+- C) Implementing the Runnable interface allows for better object-oriented design and code reusability compared to extending Thread.
+ - `Correct: Implementing Runnable is generally preferable as it doesn't require your class to inherit from Thread (allowing it to inherit from some other class if needed), and it allows the task (the Runnable) to be passed around and executed by different threads.`
+
+- D) Extending the Thread class provides better control over thread execution compared to implementing Runnable.
+ - `Incorrect: Both methods provide similar control over thread execution. Neither method inherently provides more control.`
+
+**Question 3: In the given code snippet, what is the purpose of the Task2 class?**
+```java
+class Task2 implements Runnable {
+ @Override
+ public void run() {
+ System.out.println("Task2 Started ");
+ for(int i=201; i<=299; i++) {
+ System.out.print(i + "
+
+ ");
+ }
+ System.out.println("\nTask2 Done");
+ }
+}
+```
+- A) It defines a new thread class that can be directly launched using the start() method.
+ - `Incorrect: The Task2 class is not a Thread but a task that needs to be executed by a Thread. You can't call start() directly on a Runnable object.`
+
+- B) It represents a sub-task that can be executed concurrently by implementing the run() method.
+ - `Correct: The Task2 class implements Runnable and can be passed to a Thread to execute concurrently.`
+
+- C) It extends the Thread class and overrides the start() method for task execution.
+ - `Incorrect: Task2 implements Runnable, it does not extend Thread and does not override the start() method.`
+
+- D) It encapsulates the logic for task execution and allows it to be executed by a separate thread.
+ - `Correct: The Task2 class encapsulates a task that can be run by a separate thread.`
+
+
+**Step 03: The Thread Life-cycle**
+
+**Question 1: What is the initial state of a thread when it is created but its start() method hasn't been invoked?**
+
+- A) RUNNING
+ - `Incorrect: A new thread is not in the RUNNING state until the start() method has been invoked.`
+
+- B) RUNNABLE
+ - `Incorrect: A new thread is not in the RUNNABLE state until the start() method has been invoked.`
+
+- C) BLOCKED/WAITING
+ - `Incorrect: A new thread is not in the BLOCKED/WAITING state initially. It can only enter this state during its execution when it is waiting for a resource.`
+
+- D) NEW
+ - `Correct: A new thread is in the NEW state when it is created and before its start() method is invoked.`
+
+**Question 2: When does a thread enter the TERMINATED/DEAD state?**
+
+- A) After the execution of the run() method is completed.
+ - `Correct: A thread enters the TERMINATED state after its run() method has completed.`
+
+- B) After the start() method is invoked.
+ - `Incorrect: Invoking the start() method initiates the thread execution, it does not terminate it.`
+
+- C) After the join() method is called on the thread.
+ - `Incorrect: The join() method makes the current thread to wait until the thread on which join() is called finishes its execution. It does not terminate the thread.`
+
+- D) After the thread is created using the new keyword.
+ - `Incorrect: Creating a thread using the new keyword puts the thread in the NEW state, not the TERMINATED state.`
+
+**Question 3: Which of the following states is a thread in when it is ready to be executed but not currently running?**
+
+- A) RUNNING
+ - `Incorrect: If a thread is in the RUNNING state, it is currently being executed.`
+
+- B) RUNNABLE
+ - `Correct: A thread is in the RUNNABLE state when it is ready to run and is awaiting the CPU's attention.`
+
+- C) BLOCKED/WAITING
+ - `Incorrect: A thread is in the BLOCKED/WAITING state when it is waiting for a resource (like a lock) to become available. It is not ready to run.`
+
+- D) NEW
+ - `Incorrect: A thread is in the NEW state after it is created but before it is started. It is not yet ready to run.`
+
+**Step 04: Thread Priorities**
+
+**Question 1: What is the range of thread priorities in Java?**
+
+- A) 1 to 100
+ - `Incorrect: In Java, the range of thread priorities is 1 to 10, not 1 to 100.`
+
+- B) 1 to 1000
+ - `Incorrect: In Java, the range of thread priorities is 1 to 10, not 1 to 1000.`
+
+- C) 1 to 10
+ - `Correct: In Java, thread priorities range from 1 to 10.`
+
+- D) 0 to 10
+ - `Incorrect: In Java, the minimum thread priority is 1, not 0.`
+
+**Question 2: What is the default priority assigned to a thread in Java?**
+
+- A) 1
+ - `Incorrect: The default priority assigned to a thread in Java is 5, not 1.`
+
+- B) 5
+ - `Correct: The default priority assigned to a thread in Java is 5.`
+
+- C) 10
+ - `Incorrect: The maximum priority that can be assigned to a thread in Java is 10, but it's not the default priority.`
+
+- D) 0
+ - `Incorrect: The minimum priority that can be assigned to a thread in Java is 1, not 0.`
+
+**Question 3: What method is used to change the priority of a thread in Java?**
+
+- A) setPriority(int)
+ - `Correct: The setPriority(int) method is used to set the priority of a thread in Java.`
+
+- B) changePriority(int)
+ - `Incorrect: There's no method called changePriority(int) in Java's Thread class.`
+
+- C) updatePriority(int)
+ - `Incorrect: There's no method called updatePriority(int) in Java's Thread class.`
+
+- D) modifyPriority(int)
+ - `Incorrect: There's no method called modifyPriority(int) in Java's Thread class.`
+
+
+
+**Step 05: Communicating Threads**
+
+**Question 1: What is the purpose of the join() method in Java?**
+
+- A) It pauses the execution of a thread until it is explicitly resumed.
+ - `Incorrect: The join() method doesn't pause the thread on which it is invoked. It makes the calling thread to wait until the thread on which join() is called finishes its execution.`
+
+- B) It sets the priority of a thread to the highest level.
+ - `Incorrect: The join() method doesn't affect thread priorities.`
+
+- C) It allows one thread to wait for the completion of another thread.
+ - `Correct: The join() method allows a thread to wait until the thread on which join() is called completes its execution.`
+
+- D) It terminates a thread and frees up system resources.
+ - `Incorrect: The join() method doesn't terminate threads.`
+
+**Question 2: In the given code snippet, when will the execution of Task3 begin?**
+
+- A) After Task1 starts
+ - `Incorrect: Task3 doesn't start just after Task1 starts. It starts after Task1 and Task2 both complete, because of the join() methods.`
+
+- B) After Task2 starts
+ - `Incorrect: Task3 doesn't start just after Task2 starts. It starts after Task1 and Task2 both complete, because of the join() methods.`
+
+- C) After Task1 and Task2 complete
+ - `Correct: The join() methods on task1 and task2Thread make the main thread (which is executing Task3) to wait until both Task1 and Task2 complete.`
+
+- D) Before Task1 and Task2 start
+ - `Incorrect: Task3 starts after Task1 and Task2 both complete.`
+
+**Question 3: What is the purpose of using the join() method on threads?**
+
+- A) To synchronize the execution of multiple threads.
+ - `Correct: The join() method is used to synchronize the execution of threads by making one thread wait until another thread completes its execution.`
+
+- B) To pause the execution of a thread temporarily.
+ - `Incorrect: The join() method doesn't pause the thread on which it is invoked. It makes the calling thread to wait until the thread on which join() is called finishes its execution.`
+
+- C) To terminate a thread.
+ - `Incorrect: The join() method doesn't terminate threads.`
+
+- D) To change the priority of a thread.
+ - `Incorrect: The join() method doesn't affect thread priorities.`
+
+**Step 07: Thread Utilities**
+
+**Question 1: What is the purpose of the sleep() method in Java?**
+
+- A) It pauses the execution of a thread for a specified number of milliseconds.
+ - `Correct: The sleep() method pauses the execution of the current thread for a specified number of milliseconds.`
+
+- B) It terminates a thread and frees up system resources.
+ - `Incorrect: The sleep() method doesn't terminate threads.`
+
+- C) It changes the priority of a thread.
+ - `Incorrect: The sleep() method doesn't affect thread priorities.`
+
+- D) It allows one thread to wait for the completion of another thread.
+ - `Incorrect: The sleep() method doesn't make the current thread wait for another thread to complete.`
+
+**Question 2: Which method is used to request the thread scheduler to execute some other thread?**
+
+- A) wait()
+ - `Incorrect: The wait() method causes the current thread to wait until another thread invokes the notify() or notifyAll() method for this object.`
+
+- B) join()
+ - `Incorrect: The join
+
+() method makes the current thread to wait until the thread on which it is called completes its execution.`
+
+- C) sleep()
+ - `Incorrect: The sleep() method causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds.`
+
+- D) yield()
+ - `Correct: The yield() method gives a hint to the thread scheduler that the current thread is willing to yield its current use of a processor. The scheduler is free to ignore this hint.`
+
+
+
+**Step 08: Drawbacks of earlier approaches**
+
+**Question 1: What is a drawback of using the Thread class or Runnable interface for managing threads?**
+
+- A) No fine-grained control over thread execution.
+ - `Partially Correct: The Thread class and Runnable interface do not provide advanced features for managing threads, like thread pooling, scheduling, etc.`
+
+- B) Difficult to maintain when managing multiple threads.
+ - `Partially Correct: Managing a large number of threads using only Thread class and Runnable interface can become complex.`
+
+- C) No way to get the result from a sub-task.
+ - `Partially Correct: Thread class and Runnable interface do not provide an easy mechanism to return results from threads.`
+
+- D) All of the above.
+ - `Correct: All the options describe limitations of using the Thread class or Runnable interface for managing threads.`
+
+**Question 2: Which of the following methods is NOT a part of the Thread class for synchronization?**
+
+- A) start()
+ - `Incorrect: The start() method is part of the Thread class.`
+
+- B) join()
+ - `Incorrect: The join() method is part of the Thread class.`
+
+- C) sleep()
+ - `Incorrect: The sleep() method is part of the Thread class.`
+
+- D) wait()
+ - `Correct: The wait() method is part of the Object class, not the Thread class. It is used for inter-thread communication, not specifically for synchronization.`
+
+**Step 09: Introducing ExecutorService**
+
+**Question 1: What is the ExecutorService used for in Java?**
+
+- A) To synchronize the execution of multiple threads.
+ - `Incorrect: While ExecutorService can be used in scenarios where you need to synchronize tasks, its primary purpose is not synchronization.`
+
+- B) To pause the execution of a thread temporarily.
+ - `Incorrect: The ExecutorService interface does not provide methods to pause a thread.`
+
+- C) To manage and control the execution of threads.
+ - `Correct: ExecutorService is used to manage and control thread execution. It provides methods to manage end-of-life scenarios for threads and also provides methods for producing future results, and so on.`
+
+- D) To terminate a thread and free up system resources.
+ - `Partially Correct: ExecutorService provides methods to shut down the executor and thus terminate threads. However, its main purpose is to control and manage thread execution, not only to terminate threads.`
+
+**Question 2: Which method is used to create a single-threaded ExecutorService?**
+
+- A) newSingleThreadExecutor()
+ - `Correct: The newSingleThreadExecutor() method creates an ExecutorService that uses a single worker thread operating off an unbounded queue.`
+
+- B) newFixedThreadPool()
+ - `Incorrect: The newFixedThreadPool() method creates a thread pool that reuses a fixed number of threads.`
+
+- C) newCachedThreadPool()
+ - `Incorrect: The newCachedThreadPool() method creates a thread pool that creates new threads as needed, but will reuse previously constructed threads when they are available.`
+
+- D) newScheduledThreadPool()
+ - `Incorrect: The newScheduledThreadPool() method creates a thread pool that can schedule commands to run after a given delay, or to execute periodically.`
+
+
From 908ad54d314106203c4bfec059a9b1650796ac59 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Thu, 25 May 2023 14:05:49 +0530
Subject: [PATCH 175/178] Update Q15-ThreadsAndConcurrency.md
---
.../Q15-ThreadsAndConcurrency.md | 104 ++++++++++++++++++
1 file changed, 104 insertions(+)
diff --git a/00-Quiz-Explanation/Q15-ThreadsAndConcurrency.md b/00-Quiz-Explanation/Q15-ThreadsAndConcurrency.md
index 9a6f1736..9c832b7c 100644
--- a/00-Quiz-Explanation/Q15-ThreadsAndConcurrency.md
+++ b/00-Quiz-Explanation/Q15-ThreadsAndConcurrency.md
@@ -388,3 +388,107 @@ class Task2 implements Runnable {
- `Incorrect: The newScheduledThreadPool() method creates a thread pool that can schedule commands to run after a given delay, or to execute periodically.`
+**Step 10: Executor - Customizing Number Of Threads**
+
+**Question 1: Which method is used to create a fixed-size thread pool with a specified number of threads?**
+
+- A) newSingleThreadExecutor()
+ - `Incorrect: The newSingleThreadExecutor() method creates an ExecutorService that uses a single worker thread. It does not allow specifying the number of threads.`
+
+- B) newFixedThreadPool()
+ - `Correct: The newFixedThreadPool() method creates a thread pool that reuses a fixed number of threads. You can specify the number of threads when calling this method.`
+
+- C) newCachedThreadPool()
+ - `Incorrect: The newCachedThreadPool() method creates a thread pool that creates new threads as needed but will reuse previously constructed threads when they are available. It does not allow specifying the number of threads.`
+
+- D) newScheduledThreadPool()
+ - `Incorrect: The newScheduledThreadPool() method creates a thread pool that can schedule commands to run after a given delay or to execute periodically. It does allow specifying the number of threads, but it is used for different purposes than a fixed thread pool.`
+
+**Question 2: What happens if more tasks are submitted to an ExecutorService than the number of threads in the thread pool?**
+
+- A) The additional tasks are queued and executed when a thread becomes available.
+ - `Correct: If more tasks are submitted than the number of threads in the thread pool, the additional tasks are added to a task queue. When a thread in the pool finishes a task, it takes another from the queue.`
+
+- B) The additional tasks are discarded and not executed.
+ - `Incorrect: The ExecutorService does not discard tasks. If more tasks are submitted than there are threads available, the additional tasks are queued for execution when a thread becomes available.`
+
+- C) The ExecutorService automatically adds more threads to the thread pool to accommodate the tasks.
+ - `Incorrect: For a fixed thread pool, the ExecutorService does not add more threads than the fixed number specified. Any additional tasks are queued.`
+
+- D) The additional tasks cause an exception to be thrown.
+ - `Incorrect: Additional tasks do not cause an exception. They are queued for execution when a thread becomes available.`
+
+**Question 3: Which of the following statements is true about the ExecutorService?**
+
+- A) It allows for fine-grained control over the execution of threads.
+ - `Correct: ExecutorService provides methods for managing thread execution, shutting down threads, producing future results, and so on, allowing for fine-grained control over the execution of threads.`
+
+- B) It is used to pause the execution of a thread temporarily.
+ - `Incorrect: ExecutorService does not provide methods to pause a thread.`
+
+- C) It is used to manage and control the execution of threads.
+ - `Correct: The primary purpose of the ExecutorService is to manage and control the execution of threads.`
+
+- D) It is used to terminate a thread and free up system resources.
+ - `Partially Correct: ExecutorService provides methods to shut down the executor and thus terminate threads. However, its main purpose is to control and manage thread execution, not only to terminate threads.`
+
+
+**Step 11: ExecutorService: Returning Values From Tasks**
+
+**Question 1: Which interface is used to create sub-tasks that return a result?**
+
+- A) Thread
+ - `Incorrect: Thread does not return a result. It simply executes the logic defined in the run() method.`
+
+- B) Runnable
+ - `Incorrect: Runnable does not return a result. Its run() method does not have a return value.`
+
+- C) Callable
+ - `Correct: Callable is used to create tasks that return a result. The call() method of Callable returns a value.`
+
+- D) ExecutorService
+ - `Incorrect: ExecutorService is a higher-level replacement for working with threads directly. It manages and controls task execution but isn't used to directly create tasks.`
+
+**Question 2: What method is used to submit a Callable task to an ExecutorService and obtain a Future object representing the task's result?**
+
+- A) execute()
+ - `Incorrect: The execute() method is used for tasks of type Runnable, and it doesn't return a result.`
+
+- B) submit()
+ - `Correct: The submit() method is used to submit tasks of type Callable. It returns a Future object, which can be used to retrieve the result once the task is completed.`
+
+- C) invokeAll()
+ - `Incorrect: The invokeAll() method is used to execute a collection of tasks and returns a list of Future objects, but it isn't used to submit a single Callable task.`
+
+- D) invokeAny()
+ - `Incorrect: The invokeAny() method is used to execute a collection of tasks and returns the result of one of the successfully completed tasks (if any), but it isn't used to submit a single Callable task.`
+
+**Question 3: How can you retrieve the result of a Callable task from a Future object?**
+
+- A) Using the get() method of the Future object
+ - `Correct: The get() method is used to retrieve the result from a Future object. This method blocks until the computation is complete.`
+
+- B) Using the run() method of the Callable task
+ - `Incorrect: Callable does not have a run() method. Instead, it has a call() method. Moreover, calling this method directly doesn't involve a Future object.`
+
+- C) Using the call() method of the Callable task
+ - `Incorrect: While it's true that the call() method of the Callable task computes the result, it's not used to retrieve the result from a Future object.`
+
+- D) Using the result() method of the Future object
+ - `Incorrect: There's no result() method in the Future interface.`
+
+**Step 12: Executor - Wait Only For The Fastest Task**
+
+**Question 1: What method of ExecutorService can be used to wait for the result of the fastest completed task from a collection of Callable tasks?**
+
+- A) execute()
+ - `Incorrect: The execute() method is used for executing Runnable tasks and does not return a result.`
+
+- B) submit()
+ - `Incorrect: The submit() method is used to submit individual Callable or Runnable tasks and isn't used for executing a collection of tasks and waiting for the fastest one.`
+
+- C) invokeAll()
+ - `Incorrect: The invokeAll() method executes a collection of tasks but it waits for all tasks to complete and doesn't return the result of the fastest one.`
+
+- D) invokeAny()
+ - `Correct: The invokeAny() method executes a collection of Callable tasks and returns the result of the fastest one that completes.`
From 4644ee29d89f04dfda68a0efaa3a8d58f2507274 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Thu, 25 May 2023 14:29:13 +0530
Subject: [PATCH 176/178] Create Q14-FunctionalProgramming.md
---
.../Q14-FunctionalProgramming.md | 540 ++++++++++++++++++
1 file changed, 540 insertions(+)
create mode 100644 00-Quiz-Explanation/Q14-FunctionalProgramming.md
diff --git a/00-Quiz-Explanation/Q14-FunctionalProgramming.md b/00-Quiz-Explanation/Q14-FunctionalProgramming.md
new file mode 100644
index 00000000..252ac0e2
--- /dev/null
+++ b/00-Quiz-Explanation/Q14-FunctionalProgramming.md
@@ -0,0 +1,540 @@
+**Step 01: Introducing Functional Programming**
+
+**Question 1: What is the purpose of functional programming?**
+
+- A) To loop around a list and print its content.
+ - `Incorrect: While functional programming can certainly accomplish this task, it isn't the purpose of functional programming.`
+
+- B) To focus on the "how" of programming.
+ - `Incorrect: Functional programming focuses more on the "what" rather than the "how" of programming.`
+
+- C) To focus on the "what" of programming.
+ - `Correct: Functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data. It is a declarative type of programming style that focuses on "what" to solve rather than "how" to solve.`
+
+**Question 2: What is the output of the following code?**
+
+- A) Apple, Banana, Cat, Dog
+ - `Correct: The for-each loop iterates over each element in the list, and prints each element to the console. Therefore, all the elements in the list are printed.`
+
+- B) Apple
+ - `Incorrect: Although "Apple" is the first element in the list, the loop iterates over the entire list, not just the first element.`
+
+- C) Banana, Cat, Dog
+ - `Incorrect: The loop iterates over the entire list, so "Apple" will be printed as well.`
+
+**Question 3: How does functional programming differ from the approach shown in Snippet-01?**
+
+- A) It allows us to loop around a list.
+ - `Incorrect: Both functional programming and the traditional approach can loop around a list.`
+
+- B) It focuses on the "what" of programming.
+ - `Correct: Functional programming is a declarative style of programming that emphasizes the "what" of programming (what you want to achieve) instead of the "how" (how the computer should do it). The traditional approach shown in Snippet-01, on the other hand, focuses more on the "how".`
+
+- C) It accesses individual elements of a list.
+ - `Incorrect: Both functional programming and the traditional approach can access individual elements of a list.`
+
+**Step 02: Looping Through A List**
+
+**Question 1: What does the following code do?**
+
+- A) Prints the list of numbers.
+ - `Correct: The forEach() method is applied to each element in the stream, and for each element, System.out.println(elem) is executed, which prints the element.`
+
+- B) Filters the stream based on some logic.
+ - `Incorrect: The code doesn't apply any filter to the stream. If there were a filter() method call, it would filter the stream.`
+
+- C) Passes a function as a method argument.
+ - `Correct: The lambda expression (elem -> System.out.println(elem)) is essentially a function that is passed as an argument to the forEach() method. Therefore, this statement is also correct.`
+
+**Question 2: What is the purpose of using a lambda expression in the code?**
+
+- A) To iterate over the list.
+ - `Incorrect: While it's true that the lambda expression is used in the context of iteration, it's not used to perform the iteration itself.`
+
+- B) To filter the stream elements.
+ - `Incorrect: The lambda expression in this case doesn't perform any filtering. It's used to execute a function (printing) for each element.`
+
+- C) To execute a function for each element.
+ - `Correct: The lambda expression represents a function that is executed for each element in the stream.`
+
+**Question
+
+ 3: What is the output of the following code?**
+
+- A) 1, 7, 9
+ - `Correct: The filter() method filters the stream so that only the numbers that are odd (num % 2 == 1) remain. Therefore, 1, 7, and 9 are printed.`
+
+- B) 4
+ - `Incorrect: The number 4 is even and is filtered out by the filter() method.`
+
+- C) 1, 4, 7, 9
+ - `Incorrect: The filter() method filters out the even number (4), so it's not printed.`
+
+
+**Step 03: Filtering Results**
+
+**Question 1: What is the purpose of the filter() method?**
+
+- A) To loop around a list and print its content.
+ - `Incorrect: The filter() method does not print its content nor iterate over the list, it applies a Predicate (a function returning a boolean) on each element and filters those which return true.`
+
+- B) To filter the stream elements based on some logic.
+ - `Correct: The filter() method applies a Predicate to each element of the stream and filters (keeps) those for which the Predicate returns true.`
+
+- C) To focus on the "what" of programming.
+ - `Incorrect: While functional programming as a whole focuses on the "what", the filter() method specifically applies a condition to filter elements from a stream.`
+
+**Question 2: What is the output of the following code?**
+
+- A) Apple, Bat, Cat, Dog
+ - `Incorrect: The filter() method is used to keep only the elements that end with "at", so "Apple" and "Dog" are not printed.`
+
+- B) Bat, Cat
+ - `Correct: The filter() method is used to keep only the elements that end with "at", so "Bat" and "Cat" are printed.`
+
+- C) Cat
+ - `Incorrect: Both "Bat" and "Cat" end with "at", so both are printed.`
+
+**Question 3: How would you filter the list of numbers to print only the even numbers?**
+
+- A) list.stream().filter(num -> num%2 == 0)
+ - `Correct: This lambda expression checks if a number is even (the remainder of the division by 2 is 0), so it filters the even numbers.`
+
+- B) list.stream().filter(num -> num%2 == 1)
+ - `Incorrect: This lambda expression checks if a number is odd (the remainder of the division by 2 is 1), so it filters the odd numbers.`
+
+- C) list.stream().filter(num -> num%2 == 2)
+ - `Incorrect: The remainder of the division of any number by 2 can only be 0 or 1, never 2, so this filter would not match any number.`
+
+**Step 05: Streams - Aggregated Results**
+
+**Question 1: What is the purpose of the reduce() method in functional programming?**
+
+- A) To loop around a list and print its content.
+ - `Incorrect: The reduce() method is not for printing content or looping around a list, but for aggregating the elements of a stream into a single result.`
+
+- B) To filter the stream elements based on some logic.
+ - `Incorrect: The reduce() method is not for filtering elements, but for aggregating them into a single result.`
+
+- C) To aggregate data into a single result.
+ - `Correct: The reduce() method is used to perform an operation that combines all elements of a stream into a single result.`
+
+**Question 2: What is the output of the following code?**
+
+- A) 49
+ - `Correct: The reduce() method applies a lambda expression that adds together all numbers in the list, and their sum is 49.`
+
+- B) 31
+ - `Incorrect: The sum of the numbers in the list is 49, not 31.`
+
+- C) 34
+ - `Incorrect: The sum of the numbers in the list is 49, not 34.`
+
+**Question 3: How does the reduce() method work in the given code?**
+
+- A) It adds all
+
+ the numbers in the list.
+ - `Correct: The reduce() method applies a lambda expression that sums the numbers. It starts with the initial value (0), then adds each element of the stream.`
+
+- B) It filters the even numbers in the list.
+ - `Incorrect: The reduce() method does not filter elements, it aggregates them into a single result.`
+
+- C) It applies a lambda expression to aggregate the numbers.
+ - `Correct: The reduce() method indeed uses a lambda expression (num1, num2) -> num1 + num2, which sums the numbers, to aggregate the elements of the stream.`
+
+
+
+**Step 06: Functional Programming v Structured Programming**
+
+**Question 1: What is the difference between Structured Programming (SP) and Functional Programming (FP) in terms of mutations?**
+
+- A) SP involves mutations, while FP avoids mutations.
+ - `Correct: Structured programming often involves changing the state or mutating variables, while functional programming tends to avoid mutations and promotes immutability.`
+
+- B) SP doesn't involve mutations, while FP allows mutations.
+ - `Incorrect: Structured programming often involves mutating variables, while functional programming promotes immutability and avoids mutation.`
+
+- C) Both SP and FP involve mutations.
+ - `Incorrect: Functional programming discourages mutation and promotes immutability, while structured programming may involve mutation.`
+
+**Question 2: How does SP differ from FP in terms of specifying the computation?**
+
+- A) SP specifies both what to do and how to do it.
+ - `Correct: Structured programming often focuses on the steps to achieve the result (the "how"), in addition to the result itself (the "what").`
+
+- B) FP specifies what to do, but not how to do it.
+ - `Correct: Functional programming focuses on the desired result (the "what"), and not on the steps to achieve it (the "how").`
+
+- C) Both SP and FP specify what to do and how to do it.
+ - `Incorrect: While structured programming often specifies both the "what" and the "how", functional programming typically focuses on the "what".`
+
+**Question 3: Which method in the given code follows the Functional Programming (FP) approach?**
+
+Without seeing the given code, I can't answer this question definitively. However, assuming that `basicSum()` follows a structured programming approach and `fpSum()` follows a functional programming approach, the correct answer would be:
+
+- B) fpSum()
+
+**Step 07: Some FP Terminology**
+
+**Question 1: What is a lambda expression in functional programming?**
+
+- A) A method that performs a specific computation.
+ - `Incorrect: While a lambda expression can represent a function that performs a specific computation, it's not the same as a method. Methods have a name and are defined inside classes, while lambda expressions are anonymous and can be passed as arguments.`
+
+- B) A sequence of elements in a stream.
+ - `Incorrect: A lambda expression is not a sequence of elements in a stream, it's a function or a piece of behavior that can be passed as an argument.`
+
+- C) A concise way to represent a function or behavior.
+ - `Correct: A lambda expression is a concise representation of a function, which can be used where a function is expected as an argument.`
+
+**Question 2: How is a lambda expression different from a regular method?**
+
+- A) A lambda expression cannot have multiple lines of code.
+ - `Incorrect: Lambda expressions can indeed have multiple lines of code, if enclosed in braces. However, they are usually used for short, concise pieces of functionality.`
+
+- B) A lambda expression cannot take any parameters.
+ - `Incorrect: Lambda expressions can take parameters, just like regular methods.`
+
+- C) A lambda expression is a more concise representation of a method.
+ - `Correct: A lambda expression is indeed a more concise representation of a function or method, often used for passing behaviors as arguments.`
+
+**Question 3: What are intermediate operations and terminal operations in streams?**
+
+- A) Intermediate operations produce a single result, while terminal operations produce another stream of elements.
+ - `Incorrect: Intermediate operations produce another stream, while terminal operations produce a single result or a collection.`
+
+- B) Intermediate operations
+
+ take a stream and return a single result, while terminal operations take a stream and produce another stream of elements.
+ - `Incorrect: This is reversed. Intermediate operations produce another stream, while terminal operations produce a single result or a collection.`
+
+- C) Intermediate operations modify the stream, while terminal operations produce a single result or a collection of objects.
+ - `Correct: Intermediate operations like filter() and map() transform the stream, while terminal operations like collect(), reduce(), or forEach() produce a single result or a collection, or have a side effect like printing to the console.`
+
+**Step 08: Intermediate Stream Operations**
+
+**Question 1: What is the purpose of the sorted() method in stream operations?**
+
+- A) To filter the stream elements based on some logic.
+ - `Incorrect: The sorted() method does not filter elements. It sorts them in natural order.`
+
+- B) To preserve the elements in natural sorted order.
+ - `Correct: The sorted() method returns a stream consisting of the elements of the original stream, sorted in their natural order.`
+
+- C) To compute new results from the input stream elements.
+ - `Incorrect: The sorted() method does not compute new results, it sorts the elements in their natural order.`
+
+**Question 2: What is the purpose of the distinct() method in stream operations?**
+
+- A) To sort the stream elements in ascending order.
+ - `Incorrect: The distinct() method does not sort elements, it eliminates duplicates.`
+
+- B) To return only the unique elements of the input stream.
+ - `Correct: The distinct() method returns a stream consisting of the unique elements of the original stream.`
+
+- C) To compute the square of each element in the input stream.
+ - `Incorrect: The distinct() method does not compute squares, it eliminates duplicates.`
+
+**Question 3: What is the output of the following code?**
+
+- A) 3, 5, 7, 45, 213
+ - `Correct: This is the output of the code. The distinct() method removes duplicates, and sorted() orders the unique numbers.`
+
+- B) 3, 5, 213, 45, 7
+ - `Incorrect: The numbers are not correctly sorted in this option.`
+
+- C) 3, 3, 5, 5, 7, 45, 213
+ - `Incorrect: This option does not remove duplicates as distinct() would.`
+
+
+
+**Step 09: Programming Exercise FP-PE-01**
+
+**Question 1: What is the purpose of the map() method in the printFPSquares() method?**
+
+- A) To filter the stream elements based on some logic.
+ - `Incorrect: The map() method doesn't filter elements, it transforms them. It takes a function as an argument and applies it to each element of the stream, producing a new stream.`
+
+- B) To preserve the elements in natural sorted order.
+ - `Incorrect: The map() method doesn't sort elements. It transforms each element in the stream according to a function.`
+
+- C) To compute the square of each element in the input stream.
+ - `Correct: In this context, the map() method is being used to transform each number in the stream to its square.`
+
+**Question 2: How would you modify the printLowerCases() method to print all the strings in lowercase?**
+
+- A) Use the map() method with a lambda expression to convert each string to lowercase.
+ - `Correct: This is the right approach. By using map() method with a lambda expression String::toLowerCase, we can transform each string in the stream to its lowercase equivalent.`
+
+- B) Use the filter() method with a lambda expression to filter out lowercase strings.
+ - `Incorrect: The filter() method is used to select elements from the stream that satisfy a certain condition, not to transform elements.`
+
+- C) Use the sorted() method with a lambda expression to sort the strings in lowercase order.
+ - `Incorrect: The sorted() method is used to sort elements in the stream, not to transform them.`
+
+**Question 3: How does the printLengths() method calculate the length of each string?**
+
+- A) It uses the filter() method with a lambda expression to filter out strings based on their length.
+ - `Incorrect: The filter() method is not involved in calculating the length of the strings. It is used for selecting elements from a stream that satisfy a certain condition.`
+
+- B) It uses the sorted() method with a lambda expression to sort the strings based on their length.
+ - `Incorrect: The sorted() method is not involved in calculating the length of the strings. It's used to sort elements in a stream.`
+
+- C) It uses the map() method with a lambda expression to transform each string into its length.
+ - `Correct: The map() method is being used to transform each string in the stream to its length.`
+
+**Step 10: Terminal Operations**
+
+**Question 1: What does the reduce() method do in terminal operations?**
+
+- A) It sorts the stream elements in ascending order.
+ - `Incorrect: The reduce() method doesn't sort elements, it combines them into a single result according to a provided binary operator.`
+
+- B) It returns a single result by combining the elements of the stream.
+ - `Correct: The reduce() method takes a binary operator and uses it to combine the elements of the stream into a single result.`
+
+- C) It returns only the unique elements of the input stream.
+ - `Incorrect: The reduce() method doesn't filter out unique elements. It combines all elements of a stream into a single result.`
+
+**Question 2: How does the max() method differ from reduce() in the given code?**
+
+- A) max() returns the maximum element from the stream, while reduce() combines all the elements into a single result.
+ - `Correct: The max() method returns the maximum element according to a provided comparator, while the reduce() method combines all elements into a single result using a provided binary operator.`
+
+- B) max() sorts the stream
+
+ elements in ascending order, while reduce() sorts them in descending order.
+ - `Incorrect: Neither max() nor reduce() sort elements. max() finds the maximum element, and reduce() combines all elements into a single result.`
+
+- C) max() applies a lambda expression to compute a single result, while reduce() applies a different lambda expression.
+ - `Partly Correct: Both methods can work with lambda expressions, but they serve different purposes. max() finds the maximum element, and reduce() combines elements.`
+
+**Question 3: What is the purpose of the Optional type in stream operations?**
+
+- A) To provide an alternative result when the stream is empty.
+ - `Correct: Optional is a container that can contain a non-null value or be empty. It's used in stream operations to avoid NullPointerException and to express that a result may not exist (for example, finding a maximum in an empty list).`
+
+- B) To handle null values in the stream elements.
+ - `Incorrect: Optional is not designed to handle null values within the stream elements. It's more about expressing the absence of a result.`
+
+- C) To convert the stream into a collection.
+ - `Incorrect: Optional is not used for converting streams into collections. It's used to represent a value that might be null.`
+
+**Step 11: More Stream Operations**
+
+**Question 1: What is the output of the following code?**
+
+- A) [23, 12, 34, 53]
+ - `Incorrect: This option includes all numbers, not just the even ones.`
+
+- B) [12, 34]
+ - `Correct: The code filters out the even numbers (12 and 34) from the input list.`
+
+- C) [23, 53]
+ - `Incorrect: This option includes the odd numbers from the list, not the even ones.`
+
+**Question 2: How would you modify the code to create a list of the odd numbers from the numbers list?**
+
+- A) Change the condition in the lambda expression to n%2==1.
+ - `Correct: Changing the condition in the filter method to n%2==1 will select the odd numbers.`
+
+- B) Replace filter() with sorted() method.
+ - `Incorrect: The sorted() method sorts elements but doesn't filter them.`
+
+- C) Use map() instead of filter().
+ - `Incorrect: The map() method transforms elements but doesn't filter them.`
+
+**Question 3: What is the purpose of the collect() method in stream operations?**
+
+- A) To compute a single result by combining the elements of the stream.
+ - `Incorrect: While collect() can be used to produce a single result (such as counting elements), its primary purpose is to transform the stream into a different form, often a collection.`
+
+- B) To convert the stream into a collection or other data structure.
+ - `Correct: The collect() method is a terminal operation that transforms the elements of the stream into a different form, often a collection (like a List, Set, or Map).`
+
+- C) To filter the stream elements based on some logic.
+ - `Incorrect: The collect() method doesn't filter elements. It's a terminal operation used to collect the elements of a stream into a collection or other data structure. Filtering is usually done before the collect() method, using the filter() method.`
+
+
+
+**Step 12: The Optional class**
+
+**Question 1: What does the Optional class represent in stream operations?**
+
+- A) It represents a nullable result from a terminal stream operation.
+ - `Correct: Optional is a container object which may or may not contain a non-null value. It is used to represent the result of a computation that might return a value or might not (like when you're looking for the maximum of an empty list).`
+
+- B) It represents an intermediate stream operation.
+ - `Incorrect: Optional doesn't represent an operation, it's a class used to represent the result of a computation that may or may not produce a result.`
+
+- C) It represents a lambda expression in functional programming.
+ - `Incorrect: Optional doesn't represent a lambda expression, it's a class used to encapsulate a result that might be present or not.`
+
+**Question 2: How can you check if an Optional object contains a valid result?**
+
+- A) By calling the get() method on the object.
+ - `Incorrect: While the get() method can be used to obtain the value contained within an Optional, it's not a safe way to check for a value because it will throw a NoSuchElementException if the Optional is empty.`
+
+- B) By invoking the isPresent() method on the object.
+ - `Correct: The isPresent() method can be used to check if an Optional contains a value.`
+
+- C) By using the orElse() method with a default value.
+ - `Incorrect: The orElse() method is used to provide a default value when the Optional is empty, but it's not used to check if an Optional contains a value.`
+
+**Question 3: What does the orElse() method do in the context of Optional?**
+
+- A) It returns the maximum element from the stream.
+ - `Incorrect: The orElse() method provides a default value to return when the Optional is empty. It has nothing to do with finding the maximum value.`
+
+- B) It handles exceptions during stream operations.
+ - `Incorrect: While it does prevent a NoSuchElementException from being thrown when the Optional is empty, the orElse() method primarily serves to provide a default value.`
+
+- C) It provides a default value if the result is empty.
+ - `Correct: The orElse() method returns the value in the Optional if it's present, otherwise it returns a default value that is provided as an argument.`
+
+
+**Step 13: Functional Interfaces: Predicate**
+
+**Question 1: What is a functional interface in Java?**
+
+- A) An interface that contains only one abstract method.
+ - `Correct: A functional interface in Java is an interface that contains exactly one abstract method.`
+
+- B) An interface that can be used to define lambda expressions.
+ - `Correct: Functional interfaces can be used as targets for lambda expressions and method references.`
+
+- C) An interface that represents a logical condition or test.
+ - `Incorrect: This describes the Predicate functional interface specifically, but not functional interfaces in general.`
+
+**Question 2: What is the purpose of the Predicate interface in stream operations?**
+
+- A) It is used to collect the elements of a stream into a list.
+ - `Incorrect: Predicate is used in operations like filter(), which select elements based on a condition, not to collect elements.`
+
+- B) It is used to filter elements based on a logical condition.
+ - `Correct: Predicate is used to create a condition that returns true or false. In the context of stream operations, it is used for methods like filter().`
+
+- C) It is used to
+
+ calculate a single result from a stream.
+ - `Incorrect: Predicate is used to evaluate conditions, not to combine or calculate results.`
+
+**Question 3: How can you use a lambda expression to implement a Predicate?**
+
+- A) By overriding the test() method in the Predicate interface.
+ - `Incorrect: In a sense, using a lambda expression does implicitly "override" the test() method, but you do not explicitly override methods when using lambda expressions.`
+
+- B) By implementing the Predicate interface directly in a class.
+ - `Incorrect: While you can do this, it's not an example of using a lambda expression.`
+
+- C) By calling the filter() method with a lambda expression as an argument.
+ - `Correct: The filter() method takes a Predicate as an argument. This is often supplied as a lambda expression.`
+
+**Step 14: Functional Interfaces: Consumer**
+
+**Question 1: What is the purpose of the Consumer interface in stream operations?**
+
+- A) It is used to filter elements based on a logical condition.
+ - `Incorrect: The Consumer interface is not used for filtering elements, it is used for performing an action on each element of a stream.`
+
+- B) It is used to perform an action on each element of the stream.
+ - `Correct: The Consumer interface is used to define an operation that takes one input argument and returns no result. It is used in the context of stream operations to perform an action on each element.`
+
+- C) It is used to transform the elements of the stream.
+ - `Incorrect: The Consumer interface is not used for transforming elements, it is used for performing an action on each element.`
+
+**Question 2: How can you implement a custom Consumer interface?**
+
+- A) By overriding the test() method in the Consumer interface.
+ - `Incorrect: The Consumer interface does not have a test() method to override. It has an accept() method.`
+
+- B) By implementing the Consumer interface directly in a class.
+ - `Correct: You can create a class that implements the Consumer interface and overrides the accept() method. However, it is often easier and more concise to use a lambda expression.`
+
+- C) By using a lambda expression as an argument to the forEach() method.
+ - `Correct: The forEach() method in the Stream interface takes a Consumer as an argument. This is often supplied as a lambda expression, which defines the action to be performed on each element.`
+
+**Question 3: What does the accept() method of the Consumer interface do?**
+
+- A) It applies a transformation to the input element.
+ - `Incorrect: The accept() method performs an action on its input. It does not return a value, so it cannot transform the input.`
+
+- B) It performs an action on the input element.
+ - `Correct: The accept() method of the Consumer interface takes an argument and performs an operation on it. It doesn't return a result.`
+
+- C) It filters the input element based on a condition.
+ - `Incorrect: The accept() method performs an action on its input. It doesn't return a boolean value, so it can't filter based on a condition.`
+
+
+ **Step 15: More Functional Interfaces**
+
+**Question 1: What is the purpose of the map() operation in stream operations?**
+
+- A) It is used to filter the elements of a stream based on a condition.
+ - `Incorrect: The map() operation is used to transform elements in a stream, not to filter them.`
+
+- B) It is used to transform the elements of a stream using a lambda expression.
+ - `Correct: The map() operation applies a function to each element in a stream and produces a new stream with the transformed elements.`
+
+- C) It is used to combine the elements of a stream into a single result.
+ - `Incorrect: The map() operation transforms elements but doesn't combine them into a single result. That role is fulfilled by operations like reduce().`
+
+**Question 2: What is the signature of the map() operation in the Stream interface?**
+
+- A) Stream map(Function super T, ? extends R> mapper)
+ - `Correct: The map() method in the Stream interface takes a Function as a parameter, which is applied to each element in the stream, and it returns a new Stream with the results.`
+
+- B) Stream map(Predicate predicate)
+ - `Incorrect: The map() method doesn't take a Predicate as a parameter. It takes a Function.`
+
+- C) Stream map(Consumer super S> action)
+ - `Incorrect: The map() method doesn't take a Consumer as a parameter. It takes a Function.`
+
+**Question 3: What is the purpose of the apply() method in the Function interface?**
+
+- A) It performs an action on the input element.
+ - `Incorrect: The apply() method applies a transformation to the input element, but it doesn't just perform an action on it; it produces a result.`
+
+- B) It filters the input element based on a condition.
+ - `Incorrect: The apply() method doesn't filter elements based on a condition. It applies a transformation to its input.`
+
+- C) It applies a transformation to the input element.
+ - `Correct: The apply() method of the Function interface takes an argument and applies a function to it, producing a result.`
+
+**Step 16: Introducing Method References**
+
+**Question 1: What is a method reference in Java?**
+
+- A) It is a reference to a static method or an instance method.
+ - `Correct: A method reference can refer to a static method, an instance method of a particular object, an instance method of an arbitrary object of a particular type, or a constructor.`
+
+- B) It is a reference to a lambda expression.
+ - `Incorrect: A method reference is an alternative syntax to a lambda expression for expressing instances of functional interfaces, but it's not a reference to a lambda expression.`
+
+- C) It is a reference to a functional interface.
+ - `Incorrect: A method reference isn't a reference to a functional interface. It's a shorthand notation for a lambda expression that calls a specific method.`
+
+**Question 2: How can you use a method reference to replace a lambda expression?**
+
+- A) By using the apply() method of a functional interface.
+ - `Incorrect: The apply() method is a method of the Function interface, not a means to use a method reference.`
+
+- B) By overriding the accept() method of a functional interface.
+ - `Incorrect: Overriding the accept() method is a way to implement the Consumer interface, not to use a method reference.`
+
+- C) By referring to the method directly using the :: operator.
+ - `
+
+Correct: The :: operator is used to create a method reference. This can be used to replace a lambda expression that calls a specific method.`
+
+**Question 3: How can you use a method reference to call an instance method?**
+
+- A) By specifying the class name followed by the method name.
+ - `Incorrect: To reference an instance method, you generally need to use the :: operator and the name of the method, without the class name.`
+
+- B) By using the apply() method of a functional interface.
+ - `Incorrect: The apply() method is part of the Function interface, not a way to use a method reference.`
+
+- C) By using the :: operator followed by the method name.
+ - `Correct: To reference an instance method, you can use the :: operator followed by the method name.`
From 85b2180044208eec9c8b1d1eadf9a86872b2a223 Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Thu, 25 May 2023 14:34:05 +0530
Subject: [PATCH 177/178] Update Q14-FunctionalProgramming.md
---
00-Quiz-Explanation/Q14-FunctionalProgramming.md | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/00-Quiz-Explanation/Q14-FunctionalProgramming.md b/00-Quiz-Explanation/Q14-FunctionalProgramming.md
index 252ac0e2..3b3478fd 100644
--- a/00-Quiz-Explanation/Q14-FunctionalProgramming.md
+++ b/00-Quiz-Explanation/Q14-FunctionalProgramming.md
@@ -433,7 +433,7 @@ Without seeing the given code, I can't answer this question definitively. Howeve
**Step 14: Functional Interfaces: Consumer**
-**Question 1: What is the purpose of the Consumer interface in stream operations?**
+**Question 1: What is the purpose of the `Consumer` interface in stream operations?**
- A) It is used to filter elements based on a logical condition.
- `Incorrect: The Consumer interface is not used for filtering elements, it is used for performing an action on each element of a stream.`
@@ -488,7 +488,7 @@ Without seeing the given code, I can't answer this question definitively. Howeve
- B) Stream map(Predicate predicate)
- `Incorrect: The map() method doesn't take a Predicate as a parameter. It takes a Function.`
-- C) Stream map(Consumer super S> action)
+- C) ` Stream map(Consumer super S> action)`
- `Incorrect: The map() method doesn't take a Consumer as a parameter. It takes a Function.`
**Question 3: What is the purpose of the apply() method in the Function interface?**
From a32cc91237438353cf4647a861a07eb2e02d88dc Mon Sep 17 00:00:00 2001
From: amideb <57451228+amideb@users.noreply.github.com>
Date: Thu, 25 May 2023 14:35:08 +0530
Subject: [PATCH 178/178] .
---
...troductionToMethods-MultiplicationTable.md | 238 -------------
.../Q06-PrimitiveDataTypesAndAlternatives.md | 331 ------------------
2 files changed, 569 deletions(-)
delete mode 100644 00-Quiz-Explanation/Archive/Q02-IntroductionToMethods-MultiplicationTable.md
delete mode 100644 00-Quiz-Explanation/Archive/Q06-PrimitiveDataTypesAndAlternatives.md
diff --git a/00-Quiz-Explanation/Archive/Q02-IntroductionToMethods-MultiplicationTable.md b/00-Quiz-Explanation/Archive/Q02-IntroductionToMethods-MultiplicationTable.md
deleted file mode 100644
index 2eea244b..00000000
--- a/00-Quiz-Explanation/Archive/Q02-IntroductionToMethods-MultiplicationTable.md
+++ /dev/null
@@ -1,238 +0,0 @@
-# 1
-
-In Java, `void` is a keyword used in method signatures. It indicates that the method does not return any value.
-
-When you define a method in Java, you typically specify the type of value the method will return. For example, if a method returns an integer, you would write `int` before the method's name. However, some methods don't need to return a value; they just perform an action. For these methods, you would use the `void` keyword to indicate that no value is returned.
-
-So, for option B) "The method does not return any value", this is the correct usage of the `void` keyword in Java. It's not associated with returning an integer (option A) or a boolean (option C), or any other type of value. That's why B) is the correct answer.
-# 2
-
-The correct answer is C) `sayHelloWorldTwice();`.
-
-Here's why:
-
-When calling a method in Java, you need to use the method name followed by parentheses. If the method accepts any arguments, they would go inside the parentheses. If it doesn't, the parentheses would be empty. So, `sayHelloWorldTwice()` is the correct syntax to call the method.
-
-However, in Java, you typically follow a statement with a semicolon (`;`). This is a kind of "period" that signifies the end of a complete instruction. So to properly call the method in a Java program, you would write `sayHelloWorldTwice();`.
-
-So, option A) `sayHelloWorldTwice` is incorrect because it is missing the parentheses and the semicolon. Option B) `sayHelloWorldTwice()` is partially correct because it includes the parentheses, but it is missing the semicolon. Option C) `sayHelloWorldTwice();` is the correct way to call a method in a Java program because it includes both the parentheses and the semicolon.
-
-# 3
-
-The correct answer is C) Defining and invoking methods are two different steps.
-
-Here's why:
-
-A) Defining a method automatically executes its statement body: This statement is incorrect. When you define a method in your Java code, it doesn't automatically get executed. It's only when you call or invoke this method in your code that the statements inside the method body get executed.
-
-B) Defining a method and invoking it are the same thing: This statement is also incorrect. Defining a method means you are writing down the method's code, specifying its name, return type, parameters, and the statements it will execute. Invoking or calling a method means you are telling your program to execute the statements inside a method that has already been defined. So, these are two distinct steps in the process of using methods in Java.
-
-C) Defining and invoking methods are two different steps: This statement is correct. As explained above, defining a method involves writing out the method's code and properties, while invoking a method involves executing the statements in the method. These are two separate actions that you perform at different times in your code. Therefore, option C is the correct answer.
-
-# 4
-
-The correct answer is A) `void printHelloWorld() { System.out.println("Hello World"); }`.
-
-Here's why:
-
-A) `void printHelloWorld() { System.out.println("Hello World"); }`: This is the correct syntax for defining a method in Java. The `void` keyword indicates that the method doesn't return any value. `printHelloWorld()` is the method name with no parameters, followed by the method body enclosed in curly braces `{}`. Inside the method body, `System.out.println("Hello World");` is a statement that prints the string "Hello World" to the console.
-
-B) `printHelloWorld() { System.out.println("Hello World"); }`: This syntax is incorrect because it's missing the return type of the method. In Java, you must specify the return type before the method name. In this case, it should be `void` since the method doesn't return any value.
-
-C) `void printHelloWorld { System.out.println("Hello World"); }`: This syntax is incorrect because it's missing the parentheses `()` after the method name. In Java, you must use parentheses after the method name, even if the method doesn't take any parameters. So, it should be `printHelloWorld()`.
-
-Therefore, option A is the correct answer.
-
-# 5
-
-
-The correct answer is B) `method_one`.
-
-In Java, both variables and method names:
-
-- Must begin with a letter, an underscore (`_`), or a dollar sign (`$`). They cannot start with a digit, so option A) `1stMethod` is not valid.
-- Can contain letters, digits, underscores, or dollar signs. However, they cannot contain hyphens or other special characters, so option C) `first-Method` is not valid.
-- Are case-sensitive. This means `myMethod`, `mymethod`, and `MYMETHOD` would be considered different method names.
-- Should not be Java reserved words. There are certain keywords like `int`, `void`, `class`, etc., which have a special meaning in Java and therefore cannot be used as method or variable names.
-
-So, option B) `method_one` is a valid method name because it starts with a letter and contains only letters and an underscore. This makes `method_one` the correct answer.
-
-# 6
-
-The correct answer is A) `/methods`.
-
-Here's why:
-
-A) `/methods`: This command lists all the methods that are currently defined in the JShell session. Therefore, this is the correct answer.
-
-B) `/list`: This command lists all the snippets of code you've entered in the current JShell session, not just the methods. So, while this command will show the methods along with other types of code snippets (like variable definitions, statements, etc.), it's not the best answer because it doesn't list just the methods.
-
-C) `/edit`: This command opens an editor where you can write or modify your code. It doesn't list the methods that are currently defined in the JShell session.
-
-So, option A) `/methods` is the correct answer because it's the command that specifically lists all the methods in the current JShell session.
-
-
-# 7
-
-The correct answer is B) Allows you to modify the method definition in a separate editor window.
-
-Here's why:
-
-A) Lists the code of the specified method: This statement is incorrect. The `/edit` command doesn't list the code of the specified method. For that, you'd typically use the `/list` command in JShell.
-
-B) Allows you to modify the method definition in a separate editor window: This statement is correct. The `/edit` command in JShell opens a text editor window where you can write or modify your code, including method definitions.
-
-C) Saves the session method definitions to a file: This statement is incorrect. The `/edit` command doesn't save the session method definitions to a file. For saving the session, you would use the `/save` command in JShell.
-
-Therefore, option B is the correct answer.
-
-# 8
-
-The correct answer is A) `void methodName(ArgType argName) { method-body }`.
-
-Here's why:
-
-A) `void methodName(ArgType argName) { method-body }`: This is the correct syntax for defining a method with an argument in Java. It starts with the `void` keyword to specify that the method doesn't return any value. `methodName` is the name of the method, and `(ArgType argName)` are the argument type and name. The method body, which contains the statements to be executed, is enclosed in curly braces `{}`.
-
-B) `methodName(ArgType argName) { method-body }`: This syntax is incorrect because it's missing the return type of the method. In Java, you must specify the return type before the method name, even if the return type is `void` (meaning the method doesn't return any value).
-
-C) `methodName(ArgType argName) { method-body; }`: This syntax is incorrect for two reasons. Firstly, it's missing the return type of the method, which should be specified before the method name. Secondly, the semicolon after `method-body` is unnecessary. In Java, a semicolon is used to end a statement, but it's not used after the closing brace of a method, class, or control structure.
-
-Therefore, option A is the correct answer.
-
-# 9
-
-The correct answer is A)
-
-```
-void printNumbers(int n) {
- for (int i = 1; i <= n; i++) {
- System.out.println(i);
- }
-}
-```
-
-Here's why:
-
-A) This method is correct. It starts from 1 (`int i = 1`), and the loop continues as long as `i` is less than or equal to `n` (`i <= n`). So it includes `n` in the output, and all numbers are printed from 1 to `n` (inclusive).
-
-B) This method is almost correct, but it doesn't print the number `n`. The condition `i < n` means the loop will stop when `i` is equal to `n`, so `n` is not included in the output.
-
-C) This method starts from 0 (`int i = 0`), so it doesn't start from 1 as the question specifies. Also, similar to option B, it doesn't print the number `n` because of the condition `i < n`.
-
-Therefore, option A is the correct answer. It correctly prints all integers from 1 to `n` (inclusive).
-
-# 10
-
-The correct answer is C) The program will fail to compile due to incompatible types.
-
-Here's why:
-
-A) The program will compile and run without any errors: This statement is incorrect. If a method is defined to accept an integer argument, you can't call it with a string argument. This would be a type mismatch, and the Java compiler would not allow it.
-
-B) The program will throw a runtime error: This statement is incorrect. This situation wouldn't result in a runtime error, but a compile-time error. Java is a statically typed language, which means type checking is done at compile time. If you try to pass a string argument to a method that expects an integer, the Java compiler will catch this error and fail to compile the program.
-
-C) The program will fail to compile due to incompatible types: This statement is correct. If you try to call a method with an argument of a type that the method isn't defined to accept, the Java compiler will throw an error about incompatible types, and the program will fail to compile. So, option C is the correct answer.
-
-# 11
-
-The correct answer is A) The ability to have multiple methods with the same name in a class, but with different types of arguments.
-
-Here's why:
-
-A) The ability to have multiple methods with the same name in a class, but with different types of arguments: This statement is correct. This is known as method overloading in Java. Method overloading allows you to define multiple methods with the same name but with different parameter lists (which can vary in number, types, or order of arguments). The compiler uses these differences to determine which version of the method to call.
-
-B) The ability to have multiple methods with the same name and the same types of arguments in a class: This statement is incorrect. In Java, it's not possible to have multiple methods with the exact same name and parameter list within the same class. This would cause a compilation error because the compiler wouldn't be able to distinguish between the methods.
-
-C) The ability to have a single method with an arbitrary number of arguments: This statement is incorrect. This describes varargs (variable arguments) in Java, not method overloading. A varargs parameter allows a method to accept zero or multiple arguments of the same type, but it's not related to method overloading.
-
-Therefore, option A is the correct answer.
-
-# 12
-
-The correct answers are A) The two methods are overloaded methods, B) The two methods have the same name and different number of arguments, and C) The two methods have the same name and the same types of arguments.
-
-Here's why:
-
-A) The two methods are overloaded methods: This statement is correct. Method overloading in Java is the ability to create multiple methods of the same name, but with different parameters. These two methods have the same name (`printName`), but different parameters, so they are examples of overloaded methods.
-
-B) The two methods have the same name and different number of arguments: This statement is correct. Both methods have the name `printName`, but the first method takes two arguments (a first name and a last name), while the second method takes three arguments (a first name, a middle name, and a last name).
-
-C) The two methods have the same name and the same types of arguments: This statement is correct. Both methods have the same name (`printName`), and both accept only `String` arguments. The fact that they take a different number of arguments doesn't change the fact that the types of their arguments are the same.
-
-Therefore, all options A, B, and C are correct.
-
-# 13
-
-The correct answer is A) The output will be 3 and 6.
-
-Here's why:
-
-The method `sum(int a, int b)` is called with arguments 1 and 2, so it will print the sum of these two numbers, which is 3.
-
-The method `sum(int a, int b, int c)` is called with arguments 1, 2, and 3, so it will print the sum of these three numbers, which is 6.
-
-Therefore, the output of this code will be:
-
-Copy code
-
-`3
-6`
-
-B) The output will be 3 and 5: This is incorrect because the second method call will sum 1, 2, and 3, which equals 6, not 5.
-
-C) The code will not compile due to method overloading: This is incorrect. Method overloading (having multiple methods with the same name but different parameters) is a valid feature of Java, so this code will compile and run correctly. Therefore, option A is the correct answer.
-
-# 14
-
-The correct answer is C) A method can accept any number of arguments, and they can be of different types.
-
-Here's why:
-
-A) A method can only accept up to 2 arguments: This statement is incorrect. A method in Java can accept more than two arguments. The number of arguments is only limited by the maximum size of a method's parameter list, which is well beyond practical usage scenarios.
-
-B) A method can accept any number of arguments, but they must be of the same type: This statement is partially correct but not fully. It's true in the context of varargs (variable arguments), where a method can accept any number of arguments, but they must be of the same type. However, in general, a method can accept arguments of different types.
-
-C) A method can accept any number of arguments, and they can be of different types: This statement is correct. A method in Java can accept multiple arguments, and these arguments can be of different types. Each argument must have a type and a name. Therefore, option C is the correct answer.
-
-# 15
-
-The correct answer is A) To reduce code duplication by allowing methods with the same name but different arguments.
-
-Here's why:
-
-A) To reduce code duplication by allowing methods with the same name but different arguments: This statement is correct. Method overloading is a way to create methods that perform similar tasks but with different parameters. This enables more readable and maintainable code and reduces the need for different method names for similar tasks.
-
-B) To allow a method to return different types of values based on the input arguments: This statement is incorrect. The return type of a method in Java is not influenced by method overloading. The return type of a method is determined at the time of defining the method and does not change based on the arguments passed during the method call.
-
-C) To create multiple methods with the same name and the same number of arguments, but with different implementation: This statement is incorrect. While method overloading does involve creating multiple methods with the same name, these methods must differ in their parameter lists (either in the number, type, or order of parameters). If two methods have the same name and the same parameter list, Java would not be able to distinguish between them, leading to a compile-time error.
-
-Therefore, option A is the correct answer.
-
-# 16
-
-The correct answers are A) To end the execution of the method and B) To return the result of a computation to the calling code.
-
-Here's why:
-
-A) To end the execution of the method: This statement is correct. When a return statement is executed, the method execution is stopped, and control is returned back to the caller.
-
-B) To return the result of a computation to the calling code: This statement is correct. The primary purpose of the return statement is to return the result of a computation or an operation to the caller. The returned value can then be used in the calling code.
-
-C) To print the output of the method: This statement is incorrect. The return statement does not print anything. Printing is usually done using System.out.println() or similar methods in Java. The return statement is used to return values back to the caller, not to output them.
-
-Therefore, options A and B are the correct answers.
-
-# 17
-
-The correct answer is B) It enables sharing computed results with other code and methods, and improves breaking down a problem into sub-problems.
-
-Here's why:
-
-A) It allows the method to print the result of the computation: This statement is incorrect. The return mechanism in a method does not provide any printing capabilities. To print something, you would typically use System.out.println() or similar methods in Java. The return statement is used to return values from a method back to the calling code.
-
-B) It enables sharing computed results with other code and methods, and improves breaking down a problem into sub-problems: This statement is correct. Using return statements in methods allows for the results of computations to be used elsewhere in the program, such as in other methods or as part of further computations. This helps in breaking down complex problems into smaller, more manageable sub-problems by allowing different parts of the code to handle different sub-tasks and share their results.
-
-C) It simplifies the syntax of the method: This statement is incorrect. The return statement doesn't necessarily simplify the syntax of a method. It's a tool to pass results back to the caller, not to simplify the syntax.
-
-Therefore, option B is the correct answer.
\ No newline at end of file
diff --git a/00-Quiz-Explanation/Archive/Q06-PrimitiveDataTypesAndAlternatives.md b/00-Quiz-Explanation/Archive/Q06-PrimitiveDataTypesAndAlternatives.md
deleted file mode 100644
index 879dd81e..00000000
--- a/00-Quiz-Explanation/Archive/Q06-PrimitiveDataTypesAndAlternatives.md
+++ /dev/null
@@ -1,331 +0,0 @@
-Step 01: The Integer Types
-
-Question 1: Which of the following wrapper classes corresponds to the int primitive type in Java?
-
-- A) Byte (Incorrect: The `Byte` class corresponds to the byte primitive type, not int.)
-- B) Integer (Correct: The `Integer` class is the wrapper class for the `int` primitive type. It provides methods to work with int values.)
-- C) Short (Incorrect: The `Short` class corresponds to the short primitive type, not int.)
-
-Explanation:
-
-- Option A is incorrect because the `Byte` class corresponds to the byte primitive type, not int.
-- Option B is correct because the `Integer` class is the wrapper class specifically designed to work with int values.
-- Option C is incorrect because the `Short` class corresponds to the short primitive type, not int.
-
-Question 2: What is the maximum value of a short data type in Java?
-
-- A) 127
-- B) 32767 (Correct: The maximum value of a `short` is 32767)
-- C) 2147483647 (Incorrect: The value 2147483647 is the maximum value for the `int` data type, not short.)
-
-Explanation:
-
-- Option A is incorrect because 127 is the maximum value for the `byte` data type, not short.
-- Option B is correct because 32767 is the maximum value for the `short` data type in Java.
-- Option C is incorrect because 2147483647 is the maximum value for the `int` data type, not short.
-
-Question 3: What type of cast is used to store a smaller data value in a larger data type variable?
-
-- A) Implicit cast (Correct: Implicit casting is used to automatically convert a smaller data type to a larger data type)
-- B) Explicit cast
-
-Explanation:
-
-- Option A is correct because implicit casting is used to automatically convert a smaller data type to a larger data type without any loss of data.
-- Option B is incorrect because explicit casting is used when converting a larger data type to a smaller data type and requires explicit specification.
-
-
-
-Step 02: Integer Representations, And Other Puzzles
-
-Question 1: What are the three number systems supported by Java for integers?
-
-- A) Decimal, Octal, and Binary
-- B) Decimal, Octal, and Hexadecimal (Correct: The three number systems supported by Java for integers are decimal, octal, and hexadecimal)
-- C) Decimal, Binary, and Hexadecimal (Incorrect: Binary is also a number system supported by Java for integers)
-
-Explanation:
-
-- Option A is incorrect because it doesn't include hexadecimal, which is one of the number systems supported by Java for integers.
-- Option B is correct because decimal, octal, and hexadecimal are the three number systems supported by Java for integers.
-- Option C is incorrect because it includes binary, but it doesn't include octal.
-
-Question 2: Which of the following is the correct representation for the value 16 in a hexadecimal system?
-
-- A) 0x10 (Correct: In a hexadecimal system, 16 is represented as 0x10)
-- B) 010 (Incorrect: This represents the value 10 in an octal system)
-- C) 0x16 (Incorrect: This represents the value 22 in a hexadecimal system)
-
-Explanation:
-
-- Option A is correct because in a hexadecimal system, the prefix "0x" is used, followed by the digits representing the value. Therefore, 16 is represented as 0x10.
-- Option B is incorrect because "010" represents the value 10 in an octal system, not hexadecimal.
-- Option C is incorrect because "0x16" represents the value 22 in a hexadecimal system, not 16.
-
-Question 3: What is the difference between prefix and post-fix increment operators in Java?
-
-- A) Prefix increment takes place before the assignment, and post-fix increment takes place after the assignment. (Correct: Prefix increment happens before the assignment, while postfix increment happens after the assignment.)
-- B) Prefix increment takes place after the assignment, and post-fix increment takes place before the assignment. (Incorrect: The order of increment is reversed in the explanation)
-- C) There is no difference between prefix and post-fix increment operators in Java. (Incorrect: There is a difference in the order of increment)
-
-Explanation:
-
-- Option A is correct because prefix increment (++variable) happens before the assignment, meaning the variable is incremented and then used in the expression.
-- Option B is incorrect because the explanation states that postfix increment happens before the assignment, which is incorrect.
-- Option C is incorrect because there is indeed a difference between prefix and postfix increment operators in Java.
-
-
-
-Step 03: Classroom Exercise CE-01 (With Solutions)
-
-Question 1: What is the purpose of the BiNumber class?
-
-- A) To store a single integer and perform basic arithmetic operations
-- B) To store a pair of integers and perform basic arithmetic operations (Correct: The purpose of the BiNumber class is to store a pair of integers and perform basic arithmetic operations)
-- C) To store a list of integers and perform basic arithmetic operations
-
-Explanation:
-
-- Option A is incorrect because it mentions storing a single integer, while the BiNumber class is specifically designed to store a pair of integers.
-- Option B is correct because the BiNumber class is used to store a pair of integers and provides methods to perform basic arithmetic operations on those numbers.
-- Option C is incorrect because it mentions storing a list of integers, which is not the purpose of the BiNumber class.
-
-Question 2: Which method is used to double the values of both numbers in a BiNumber object?
-
-- A) double()
-- B) doubleNumbers() (Correct: The `doubleNumbers()` method is used to double the values of both numbers in a BiNumber object)
-- C) doubleValue()
-
-Explanation:
-
-- Option A is incorrect because `double()` is not a valid method for doubling the values of both numbers in a BiNumber object.
-- Option B is correct because the `doubleNumbers()` method specifically performs the operation of doubling the values of both numbers in a BiNumber object.
-- Option C is incorrect because `doubleValue()` is not the method responsible for doubling both numbers in a BiNumber object.
-
-Question 3: What will be the output of the following code snippet?
-
-```java
-BiNumber numbers = new BiNumber(4, 5);
-System.out.println(numbers.add());
-numbers.doubleValue();
-System.out.println(numbers.getNumber1());
-System.out.println(numbers.getNumber2());
-```
-
-- A) 9, 8, 10
-- B) 9, 8, 5
-- C) 9, 4, 5 (Correct: The output will be 9, 4, 5 after adding the numbers and doubling the value of the BiNumber object)
-
-Explanation:
-
-- The first line creates a BiNumber object with values 4 and 5.
-- The second line prints the result of adding the two numbers, which is 9.
-- The third line calls the `doubleValue()` method on the BiNumber object, doubling both numbers internally.
-- The fourth line prints the first number of the BiNumber object, which is now 4.
-- The fifth line prints the second number of the BiNumber object, which remains 5.
-- Therefore, the output will be 9, 4, 5.
-
-
-
-Step 05: Floating-Point Types
-
-Question 1: What is the default type for floating-point literals in Java?
-
-- A) float
-- B) double (Correct: The default type for floating-point literals in Java is `double`)
-
-Explanation:
-
-- Option A is incorrect because the default type for floating-point literals in Java is `double`.
-- Option B is correct because `double` is the default type for floating-point literals in Java.
-
-Question 2: How can you create a float literal?
-
-- A) float f = 34.5
-- B) float f = 34.5f; (Correct: To create a float literal, you need to append the suffix `f` to the value)
-- C) float f = (float)34.5
-
-Explanation:
-
-- Option A is incorrect because 34.5 without the `f` suffix is considered a `double` literal, not a `float` literal.
-- Option B is correct because adding the `f` suffix to the value makes it a `float` literal.
-- Option C is incorrect because explicitly casting the value to a `float` is another way to create a `float` literal, but it is not necessary when assigning a literal value directly.
-
-Question 3: Which type of casting is needed to convert a double value to a float value?
-
-- A) Implicit casting
-- B) Explicit casting (Correct: Explicit casting is required to convert a `double` value to a `float` value)
-
-Explanation:
-
-- Option A is incorrect because implicit casting is not sufficient to convert a `double` value to a `float` value. It could result in a loss of precision.
-- Option B is correct because explicit casting, specifically `(float)`, is needed to convert a `double` value to a `float` value. It explicitly tells the compiler to perform the conversion, even though there may be potential loss of precision.
-
-
-
-Step 06: Introducing BigDecimal
-
-Question 1: What is the main reason for using the BigDecimal data type in Java?
-
-- To represent floating-point numbers with higher precision (Correct: The main reason for using the BigDecimal data type is to represent floating-point numbers with higher precision)
-- To perform faster calculations
-- To store large integer values
-
-Explanation:
-
-- Option A is correct because the BigDecimal data type is used to represent floating-point numbers with higher precision, avoiding issues with rounding errors that can occur with other floating-point types.
-- Option B is incorrect because the primary purpose of BigDecimal is precision, not performance.
-- Option C is incorrect because BigDecimal is not specifically designed for storing large integer values; it is more focused on decimal numbers with high precision.
-
-Question 2: What is the best way to construct a BigDecimal object to achieve high precision?
-
-- Using integer literals
-- Using double literals
-- Using string literals (Correct: The best way to construct a BigDecimal object to achieve high precision is by using string literals)
-
-Explanation:
-
-- Option A is incorrect because using integer literals might result in the loss of precision when constructing a BigDecimal object.
-- Option B is incorrect because using double literals may introduce rounding errors when constructing a BigDecimal object.
-- Option C is correct because using string literals, such as "0.12345678901234567890", allows you to specify the exact precision and avoid any potential rounding errors.
-
-Question 3: What is the main characteristic of BigDecimal objects?
-
-- Mutable
-- Immutable (Correct: BigDecimal objects are immutable, meaning their values cannot be changed once created)
-- Synchronized
-
-Explanation:
-
-- Option A is incorrect because BigDecimal objects are immutable, meaning their values cannot be changed once created.
-- Option B is correct because BigDecimal objects have the characteristic of immutability, ensuring that their values remain unchanged.
-- Option C is incorrect because synchronization is not a characteristic specific to BigDecimal objects. It is related to thread safety.
-
-
-
-Step 06: BigDecimal Operations
-
-Question: Which of the following methods can be used for arithmetic operations on BigDecimal objects?
-
-- a. add()
-- b. multiply()
-- c. subtract()
-- d. All of the above (Correct: All of the mentioned methods can be used for arithmetic operations on BigDecimal objects)
-
-Explanation:
-
-- Option a is correct because the `add()` method is used for addition of BigDecimal objects.
-- Option b is correct because the `multiply()` method is used for multiplication of BigDecimal objects.
-- Option c is correct because the `subtract()` method is used for subtraction of BigDecimal objects.
-- Option d is correct because all of the mentioned methods (add(), multiply(), and subtract()) can be used for arithmetic operations on BigDecimal objects.
-
-Question: Can you perform arithmetic operations directly between a BigDecimal object and a primitive data type, like an int or a double?
-
-- a. Yes
-- b. No (Correct: No, arithmetic operations between BigDecimal objects and primitive data types require explicit conversion)
-
-Explanation:
-
-- Option a is incorrect because arithmetic operations between BigDecimal objects and primitive data types cannot be performed directly without explicit conversion.
-- Option b is correct because explicit conversion, using methods like `BigDecimal.valueOf()`, is required to perform arithmetic operations between BigDecimal objects and primitive data types.
-
-Question: How can you perform an arithmetic operation between a BigDecimal object and a primitive int value?
-
-- a. Convert the int to a BigDecimal using BigDecimal.valueOf() (Correct: To perform an arithmetic operation between a BigDecimal object and a primitive int value, you need to convert the int to a BigDecimal using BigDecimal.valueOf())
-
-Explanation:
-
-- Option a is correct because to perform an arithmetic operation between a BigDecimal object and a primitive int value, you need to convert the int to a BigDecimal using the `BigDecimal.valueOf()` method.
-- Using this method, you can create a BigDecimal object representing the int value and then perform arithmetic operations with other BigDecimal objects.
-
-
-
-Step 08: boolean, Relational and Logical Operators
-
-Question: Which of the following operators is a logical operator in Java?
-
-- a) >
-- b) &&
-- c) <= (Correct: The logical operator in Java is represented by the symbol &&)
-
-Explanation:
-
-- Option a is incorrect because the ">" operator is a relational operator used for comparison.
-- Option b is correct because the "&&" operator is the logical AND operator in Java, which combines two boolean expressions.
-- Option c is incorrect because the "<=" operator is a relational operator used for comparison, not a logical operator.
-
-Question: Given the following code snippet, what will be the value of result?
-
-```java
-int a = 10;
-int b = 5;
-boolean result = (a > b) && (a < 2 * b);
-```
-
-- a) true (Correct: The value of result will be true)
-- b) false
-
-Explanation:
-
-- In the given code snippet, the expression `(a > b) && (a < 2 * b)` is evaluated.
-- `(a > b)` evaluates to true because 10 is greater than 5.
-- `(a < 2 * b)` also evaluates to true because 10 is less than 2 times 5, which is 10.
-- The logical AND operator `&&` combines these two boolean expressions and returns true only if both expressions are true.
-- Since both expressions are true, the value of `result` will be true.
-
-Question: What will the following expression evaluate to?
-
-```java
-boolean x = true;
-boolean y = false;
-boolean z = !(x || y);
-```
-
-- a) true
-- b) false (Correct: The expression will evaluate to false)
-
-Explanation:
-
-- The expression `(x || y)` evaluates to true because at least one of the operands (x or y) is true.
-- The `!` operator negates the result, so `!(x || y)` evaluates to false.
-- Therefore, the value of `z` will be false.
-
-
-
-Step 10: Character Types
-
-Question 1: What is the Unicode representation of the double quotation mark?
-
-- \u0021
-- \u0022 (Correct: The Unicode representation of the double quotation mark is \u0022)
-- \u0023
-
-Explanation:
-
-- Option \u0021 represents the Unicode character for exclamation mark (!), not the double quotation mark.
-- Option \u0022 is correct because it represents the Unicode character for double quotation mark (").
-- Option \u0023 represents the Unicode character for hash or number sign (#), not the double quotation mark.
-
-Question 2: What data type in Java is used to store Unicode characters?
-
-- String
-- char (Correct: The `char` data type in Java is used to store Unicode characters)
-- int
-
-Explanation:
-
-- Option String is incorrect because `String` is a data type used to store sequences of characters, not a single Unicode character.
-- Option char is correct because the `char` data type is specifically designed to store a single Unicode character.
-- Option int is incorrect because `int` is used to store integer values, not Unicode characters.
-
-Question 3: What happens when you perform the following operation in Java: `char cn = 65;`?
-
-- A character with a Unicode value of 65 is stored in the variable cn. (Correct: The character with Unicode value 65, which is 'A', is stored in the variable cn)
-- An integer value of 65 is stored in the variable cn.
-- A compilation error occurs.
-
-Explanation:
-
-- Option A is correct because assigning the value 65 to a char variable `cn` will store the character 'A' in `cn`. In Java, characters are internally represented using Unicode values.
-- Option B is incorrect because 65 is the Unicode value of 'A', not an integer value.
-- Option C is incorrect because there is no compilation error in assigning a Unicode value to a char variable.