diff --git a/00-Quiz-Explanation/Q01-IntroductionToJavaProgrammingWithJShell-MultiplicationTable.md b/00-Quiz-Explanation/Q01-IntroductionToJavaProgrammingWithJShell-MultiplicationTable.md new file mode 100644 index 00000000..b1544c8a --- /dev/null +++ b/00-Quiz-Explanation/Q01-IntroductionToJavaProgrammingWithJShell-MultiplicationTable.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.` diff --git a/00-Quiz-Explanation/Q02-IntroductionToMethods-MultiplicationTable.md b/00-Quiz-Explanation/Q02-IntroductionToMethods-MultiplicationTable.md new file mode 100644 index 00000000..59406465 --- /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】. 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..5bde4bd7 --- /dev/null +++ b/00-Quiz-Explanation/Q06-PrimitiveDataTypesAndAlternatives.md @@ -0,0 +1,179 @@ +**Step 1: The Integer Types** + +**Question 1: Which of the following wrapper classes corresponds to the int primitive type in Java?** + +- 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.` + +**Question 2: What is the maximum value of a short data type in Java?** + +- 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 3: What type of cast is used to store a smaller data value in a larger data type variable?** + +- 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.` + +**Step 2: Integer Representations, And Other Puzzles** + +**Question 1: What are the three number systems supported by Java for integers?** + +- 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.` + +**Question 2: Which of the following is the correct representation for the value 16 in a hexadecimal system?** + +- 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.` + +**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)** + +**Question 1: What is the purpose of the BiNumber class?** + +- 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.` + +**Question 2: Which method is used to double the values of both numbers in a BiNumber object?** + +- A) + + 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 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 `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.` + +**Step 5: Floating-Point Types** + +**Question 1: What is the default type for floating-point literals in Java?** + +- 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.` + +**Question 2: How can you create a float literal?** + +- 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.` + +**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** + +**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.` + +**Question 2: What is the best way to construct a BigDecimal object to achieve high precision?** + +- 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.` + +**Question 3: What is the main characteristic of BigDecimal objects?** + +- A) Mutable `Incorrect: BigDecimal objects are immutable, which means their value + + 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.` + +**Step 6: BigDecimal Operations** + +**Question 1: Which of the following methods can be used for arithmetic operations on 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.` + +**Question 2: Can you perform arithmetic operations directly between a BigDecimal object and a primitive data type, like an int or a double?** + +- 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.` + +**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** + +**Question 1: Which of the following operators is a logical operator in Java?** + +- 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); +``` + +- 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.` + +**Question 3: What will the following expression evaluate to?** + +```java +boolean x = true; +boolean y = false; +boolean z = !(x || y); +``` + +- 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.` + +**Step 10: Character Types** + +**Question 1: What is the Unicode representation of the double quotation mark?** + +- 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 (#).` + +**Question 2: What data type in Java is used to store Unicode characters?** + +- 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.` +- + + 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.` + +**Question 3: What will the following code print out?** + +- 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.` 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/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 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 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.` 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.` diff --git a/00-Quiz-Explanation/Q14-FunctionalProgramming.md b/00-Quiz-Explanation/Q14-FunctionalProgramming.md new file mode 100644 index 00000000..3b3478fd --- /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 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 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.` diff --git a/00-Quiz-Explanation/Q15-ThreadsAndConcurrency.md b/00-Quiz-Explanation/Q15-ThreadsAndConcurrency.md new file mode 100644 index 00000000..9c832b7c --- /dev/null +++ b/00-Quiz-Explanation/Q15-ThreadsAndConcurrency.md @@ -0,0 +1,494 @@ +**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.` + + +**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.` 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.` + + 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.` diff --git a/01-Quiz/Q01-IntroductionToJavaProgrammingWithJShell-MultiplicationTable.md b/01-Quiz/Q01-IntroductionToJavaProgrammingWithJShell-MultiplicationTable.md new file mode 100644 index 00000000..b8a365f6 --- /dev/null +++ b/01-Quiz/Q01-IntroductionToJavaProgrammingWithJShell-MultiplicationTable.md @@ -0,0 +1,718 @@ +## Introduction to Programming with Print-Multiplication-Table - MCQ + +## Step 02: Introducing JShell + +---------- + +1. What does JShell stand for? + a. JavaShell + b. JavaScriptShell + c. JupyterShell + +**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? + a. To create graphical user interfaces + b. To evaluate and execute Java code and provide immediate results + 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? + a. /end + b. /exit + 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 + + +1. What is the problem solving technique used in this step? + + - a) Reverse Engineering + - 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 + - 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 + +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) * + - b) % + - 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) + +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 diff --git a/01-Quiz/Q02-IntroductionToMethods-MultiplicationTable.md b/01-Quiz/Q02-IntroductionToMethods-MultiplicationTable.md new file mode 100644 index 00000000..8be6910b --- /dev/null +++ b/01-Quiz/Q02-IntroductionToMethods-MultiplicationTable.md @@ -0,0 +1,253 @@ +## 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 + +## 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_ \ No newline at end of file diff --git a/01-Quiz/Q05-IntroductionToObjectOrientedProgrammin.md b/01-Quiz/Q05-IntroductionToObjectOrientedProgrammin.md new file mode 100644 index 00000000..ed60336c --- /dev/null +++ b/01-Quiz/Q05-IntroductionToObjectOrientedProgrammin.md @@ -0,0 +1,293 @@ +## 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 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 +- 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** + + + +## 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. 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 diff --git a/01-Quiz/Q07-Conditionals.md b/01-Quiz/Q07-Conditionals.md new file mode 100644 index 00000000..0ad20143 --- /dev/null +++ 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 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 diff --git a/01-Quiz/Q10-ArraysAndArrayList.md b/01-Quiz/Q10-ArraysAndArrayList.md new file mode 100644 index 00000000..ae95114c --- /dev/null +++ b/01-Quiz/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 diff --git a/01-Quiz/Q11-ObjectOrientedProgrammingAgain.md b/01-Quiz/Q11-ObjectOrientedProgrammingAgain.md new file mode 100644 index 00000000..21d5bf1e --- /dev/null +++ b/01-Quiz/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 diff --git a/01-Quiz/Q12-Collections.md b/01-Quiz/Q12-Collections.md new file mode 100644 index 00000000..a2434eb7 --- /dev/null +++ b/01-Quiz/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 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.` 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 mapper)` +- B) ` Stream map(Predicate predicate)` +- C) ` Stream map(Consumer 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. + + 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()` + + + 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 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` diff --git a/02-CodeChallenge/01-IntroductionToJavaProgrammingWithJShell-MultiplicationTable.md b/02-CodeChallenge/01-IntroductionToJavaProgrammingWithJShell-MultiplicationTable.md new file mode 100644 index 00000000..b37db216 --- /dev/null +++ b/02-CodeChallenge/01-IntroductionToJavaProgrammingWithJShell-MultiplicationTable.md @@ -0,0 +1,1676 @@ +## Introduction to Programming with Print-Multiplication-Table + + +### Step 02: Introducing JShell + + + +#### Exercise 1: Simple Calculation using JShell + +In this exercise, you will use JShell to perform a simple calculation. + +#### Problem + +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 + +##### Solution + +1. Launch JShell +2. Type `3 + 4` and press enter + +``` +jshell> 3 + 4 +$1 ==> 7 +``` + +3. Verify that the result is displayed as `7` +4. Exit JShell using `/exit` command + +``` +jshell> /exit +| Goodbye +``` + + +#### Exercise 2: Simple Calculation using JShell + +In this exercise, you will use JShell to perform a simple calculation. + +#### Problem + +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 + +1. Launch JShell +2. Type `8 - 3` and press enter + +``` +jshell> 8 - 3 +$1 ==> 5 +``` + +3. Verify that the result is displayed as `5` +4. Exit JShell using `/exit` command + +``` +jshell> /exit +| Goodbye +``` + + +### Step 03: Welcome to Problem Solving + + + +#### Exercise 1: Simple Multiplication using JShell + +In this exercise, you will use JShell to perform a simple multiplication. + +#### Problem + +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 +``` + +3. Verify that the result is displayed as `28` +4. Exit JShell using `/exit` command + +``` +jshell> /exit +| Goodbye +``` + +#### Exercise 2: Simple Multiplication using JShell + +In this exercise, you will use JShell to perform a simple multiplication. + +#### 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> 9 * 6 +$1 ==> 54 +``` + +3. Verify that the result is displayed as `54` +4. Exit JShell using `/exit` command + +``` +jshell> /exit +| Goodbye +``` + + + +### Step 04: Introducing Expressions + + + +#### Exercise 1: Simple Division using JShell + +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 + +##### Solution + +1. Launch JShell +2. Type `10 / 2` and press enter + +``` +jshell> 10 / 2 +$1 ==> 5 +``` + +3. Verify that the result is displayed as `5` +4. Exit JShell using `/exit` command + +``` +jshell> /exit +| Goodbye +``` + +#### Exercise 2: Simple Modulus using JShell + +In this exercise, you will use JShell to perform a simple modulus. + +#### Problem + +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 + +##### Solution + +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) + + +#### Exercise 1: Simple Expression using JShell + +In this exercise, you will use JShell to calculate an expression. + +#### 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> 10 * 5 +$1 ==> 50 +``` + +3. Verify that the result is displayed as `50` +4. Exit JShell using `/exit` command + +``` +jshell> /exit +| Goodbye +``` + + +#### 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> (30 * 9/5) + 32 +$1 ==> 86 +``` + +3. Verify that the result is displayed as `86` +4. Exit JShell using `/exit` command + +``` +jshell> /exit +| Goodbye +``` + + +### Step 06: Operators + + +#### Exercise 1: Simple Expression using JShell + +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 +``` + +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 +``` + +5. Verify that the result is displayed as `66` +6. Exit JShell using `/exit` command + +``` +jshell> /exit +| Goodbye +``` + +#### Exercise 2: Simple Expression using JShell + +In this exercise, you will use JShell to calculate an expression. + +#### 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 + +##### Solution + +1. Launch JShell +2. Write an expression to calculate the result of `(10 - 3) * 4`: `(10 - 3) * 4` + +``` +jshell> (10 - 3) * 4 +$1 ==> 28 +``` + +3. Verify that the result is displayed as `28` +4. Exit JShell using `/exit` command + +``` +jshell> /exit +| Goodbye +``` + + +### Step 07: Introducing Console Output + + + +#### Exercise 1: Simple Arithmetic with Printing using JShell 1 + +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 + +##### Solution 1 + +1. Launch JShell +2. Write an expression to calculate the result of `7 * 2`: `7 * 2` +3. Print the result using `System.out.println()` + +``` +jshell> System.out.println(7 * 2); +14 +``` + +4. Write an expression to calculate the result of `7 / 2`: `7 / 2` +5. Print the result using `System.out.println()` + +``` +jshell> System.out.println(7 / 2); +3 +``` + +6. Exit JShell using `/exit` command + +``` +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 + +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 +``` + +4. Write an expression to calculate the result of `7 - 2`: `7 - 2` +5. Print the result using `System.out.println()` + +``` +`jshell> System.out.println(7 - 2); +5 +``` + +6. Exit JShell using `/exit` command + +``` +jshell> /exit +| Goodbye +``` + + + +### Step 08: Programming Exercise PE-02 +### Step 09: Solutions to PE-02 + + + + +#### Exercise 1: Simple Arithmetic with Printing using JShell 1 + +1. Launch JShell +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 print "Welcome to Java 9!" using `System.out.println()` + +``` +jshell> System.out.println("Welcome to Java 9!"); +Welcome to Java 9! +``` + +3. Exit JShell using `/exit` command + +``` +jshell> /exit +| Goodbye +``` + +#### Exercise 2: Simple Arithmetic with Printing using JShell 2 + +1. Launch JShell +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 `20 % 3 + 5 - 2 * 4`: `20 % 3 + 5 - 2 * 4` +3. Print the result using `System.out.println()` + +``` +jshell> System.out.println(20 % 3 + 5 - 2 * 4); +1 +``` + +4. Exit JShell using `/exit` command + +``` +jshell> /exit +| Goodbye +``` + + +### Step 10: Whitespace, Case sensitiveness and Escape Characters + + +#### Exercise 1: Simple Arithmetic with Printing using JShell 1 + +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 + +##### Solution 1 + +1. Launch JShell +2. Write an expression to print the string "hello, world!" in all lowercase using `System.out.println()` + +``` +jshell> System.out.println("hello, world!"); +hello, world! +``` + +3. Exit JShell using `/exit` command + +``` +jshell> /exit +| Goodbye +``` + +#### Exercise 2: Simple Arithmetic with Printing using JShell 2 + +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()` + +``` +jshell> System.out.println("Hi there!"); +Hi there! +``` + +3. Write an expression to print the string "Good\tmorning" using `System.out.println()` + +``` +jshell> System.out.println("Good\tmorning"); +Good morning +``` + +4. Write an expression to print the string "See you\ntomorrow!" using `System.out.println()` + +``` +jshell> System.out.println("See you\ntomorrow!"); +See you +tomorrow! +``` + +5. Exit JShell using `/exit` command + +``` +jshell> /exit +| Goodbye +``` + +### Step 11: More On Method Calls + + + +#### Problem 1 + +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 1 + +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> System.out.println((int)(Math.random() * 100) + 1); +87 +``` + +3. Exit JShell using `/exit` command + +``` +jshell> /exit +| Goodbye +``` + +#### Problem 2 + +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 + +##### Solution 2 + +1. Launch JShell +2. Write an expression to print the minimum value between 100 and 199 using `Math.min()` and `System.out.println()` + +``` +jshell> System.out.println(Math.min(100, 199)); +100 +``` + +3. Write an expression to print the maximum value between 299 and 555 using `Math.max()` and `System.out.println()` + +``` +jshell> System.out.println(Math.max(299, 555)); +555 +``` + +4. Exit JShell using `/exit` command + +``` +jshell> /exit +| Goodbye +``` + + + +### Step 12: More Formatted Output + + + +#### Exercise 1: Simple Arithmetic with Formatted Output using JShell + + +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()` + +``` +jshell> System.out.printf("7 * 5 = %d%n", 7 * 5); +7 * 5 = 35 +``` + +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 + +``` +jshell> /exit +| Goodbye +``` + +#### Exercise 2: Simple Arithmetic with Formatted Output using JShell + +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 + +##### 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()` + +``` +jshell> System.out.printf("25 %% 7 = %d%n", 25 % 7); +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.printf()` + +``` +jshell> System.out.printf("(6 + 8) / 2 * 3 = %d%n", (6 + 8) / 2 * 3); +(6 + 8) / 2 * 3 = 18 +``` + +6. Exit JShell using `/exit` command + +### 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 5. + +##### 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 5. + +``` +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 +``` + + + + +### 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: Printing the Sum using Formatted Output in JShell + +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> int a = 3 +a ==> 3 + +jshell> int b = 6 +b ==> 6 + +jshell> int c = 9 +c ==> 9 +``` + +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 +``` + + + + +### 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 +``` + + + +### 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: Printing Primitive Types using Formatted Output in JShell + +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. + +##### Solution 1 + +1. Launch JShell + +2. Define a double variable `pi` and assign it the value `3.14159`. + + +``` +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 +``` + +Note that the `.2f` in the format string specifies the number of decimal places to be printed. + +4. Exit JShell using the `/exit` command. + +``` +jshell> /exit +| Goodbye +``` + +#### Exercise 2: Printing Primitive Types using Formatted Output in JShell + +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. + +##### Solution 2 + +1. Launch JShell + +2. Define a boolean variable `isRainy` and assign it the value `true`. + + +``` +jshell> boolean isRainy = true +isRainy ==> true +``` + +3. Print the value of `isRainy` using `System.out.printf()`. The output should be in the format `It is raining: true`. + +``` +jshell> System.out.printf("It is raining: %b%n", isRainy); +It is raining: true +``` + +Note that the `%b` in the format string specifies the boolean value to be printed. + +4. Exit JShell using the `/exit` command. + +``` +jshell> /exit +| Goodbye +``` + + +### Step 19: Choosing A Data Type + + +#### Exercise 1: Choosing A Data Type using JShell + +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. + +##### Solution 1 + +1. Launch JShell. + +2. Write a statement to store the number of seconds in a day. + + +``` +jshell> int secondsInDay = 86400; +secondsInDay ==> 86400 +``` + +3. Declare and initialize a variable to store the value of pi, accurate to 3 decimal places. + +``` +jshell> double pi = 3.141; +pi ==> 3.141 +``` + +4. Write a statement to store the temperature of the human body in degrees Celsius. + +``` +jshell> float bodyTemperature = 37.0f; +bodyTemperature ==> 37.0 +``` + +5. Declare and initialize a variable to store the average height of an adult male in meters. + +``` +jshell> double avgMaleHeight = 1.75; +avgMaleHeight ==> 1.75 +``` + +6. Exit JShell using the `/exit` command. + +``` +jshell> /exit +| Goodbye +``` + +#### Exercise 2: Choosing A Data Type using JShell + +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 +``` + +3. Declare and initialize a variable to store the mass of the earth in kilograms. + +``` +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 = + + + + + +#### 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 `count`. Follow these steps: + +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 + +``` +jshell> int count = 10; +count ==> 10 + +jshell> count++; +count ==> 11 + +jshell> count--; +count ==> 10 + +jshell> count += 5; +count ==> 15 + +jshell> count -= 2; +count ==> 13 + +jshell> count; +count ==> 13 +``` + +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. + +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. + +We print the value of `count` using the JShell prompt at the end, which confirms that the above operations were successful. + + +#### 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 num = 5; +num ==> 5 + +jshell> num *= 3; +num ==> 15 + +jshell> num /= 2; +num ==> 7 + +jshell> num %= 4; +num ==> 3 + +jshell> num; +num ==> 3 +``` + + + +### 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: Introducing Conditionals - the if + +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 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 +``` + +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: Introducing Conditionals - the if + +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 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`: + +``` +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`: + +``` +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 + +#### 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. +``` + + + + + + +### 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"); + ...> } +``` + + +### 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 +``` + + + +### 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); +``` + + +### Step 30: Puzzling You With `for` + + +#### Exercise 1 + +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 1 + +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 = 1, j = 5; i <= 5; i++, j--) { + ...> System.out.printf("i = %d, j = %d\n", i, j); + ...> } +``` + +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. + +**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 diff --git a/02-CodeChallenge/02-IntroductionToMethods-MultiplicationTable.md b/02-CodeChallenge/02-IntroductionToMethods-MultiplicationTable.md new file mode 100644 index 00000000..6d21eb42 --- /dev/null +++ b/02-CodeChallenge/02-IntroductionToMethods-MultiplicationTable.md @@ -0,0 +1,630 @@ +### 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 +``` + + + +### Step 03: Editing A Method Definition (Jshell Tips) + + + +#### 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. +3. Call the `greet` 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. + + +``` +jshell> void greet() { + ...> System.out.println("Welcome to JShell!"); + ...> } + ``` + +3. Call the `greet` method. + +``` +jshell> greet(); +Welcome to JShell! +``` + +4. Edit the `greet` method to print "Hello, JShell!" to the console instead. + +``` +jshell> /edit greet +``` + +This will open the method definition in an external editor. Replace the line that prints "Welcome to JShell!" with the following line: + +``` +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. + +``` +jshell> /exit +| Goodbye +``` + + + +### 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 + +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: + +1. Launch JShell. + +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: + +``` +void printMultiplicationTable(int number) { + for (int i = 1; i <= 15; i++) { + System.out.println(number + " x " + i + " = " + (number * i)); + } + } +``` + +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. + + +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 + +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 +``` + + +### 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 +``` + + + +### 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. + + + +### 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 diff --git a/02-CodeChallenge/03-IntroductionToJavaPlatform.md b/02-CodeChallenge/03-IntroductionToJavaPlatform.md new file mode 100644 index 00000000..2378027d --- /dev/null +++ b/02-CodeChallenge/03-IntroductionToJavaPlatform.md @@ -0,0 +1,179 @@ +### 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 com.udemy.ucp.IOHelper; + +public class Evaluate { + Exercise ex = new Exercise(); + IOHelper helper = new IOHelper(); + + @Test + public void testHelloWorld() { + helper.resetStdOut(); // clean stdout + Exercise.main(null); + assertEquals("Hello World\n", helper.getOutput(), "The output should be 'Hello World'"); + } +} + +``` + + \ No newline at end of file diff --git a/02-CodeChallenge/04-IntroductionToEclipse-FirstJavaProject.md b/02-CodeChallenge/04-IntroductionToEclipse-FirstJavaProject.md new file mode 100644 index 00000000..fb986beb --- /dev/null +++ b/02-CodeChallenge/04-IntroductionToEclipse-FirstJavaProject.md @@ -0,0 +1,656 @@ + +# 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."); + + } +} + +``` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/02-CodeChallenge/05-IntroductionToObjectOrientedProgrammin.md b/02-CodeChallenge/05-IntroductionToObjectOrientedProgrammin.md new file mode 100644 index 00000000..f84c05b8 --- /dev/null +++ b/02-CodeChallenge/05-IntroductionToObjectOrientedProgrammin.md @@ -0,0 +1,912 @@ + +## 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 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/02-CodeChallenge/06-PrimitiveDataTypesAndAlternatives.md b/02-CodeChallenge/06-PrimitiveDataTypesAndAlternatives.md new file mode 100644 index 00000000..e89f3810 --- /dev/null +++ b/02-CodeChallenge/06-PrimitiveDataTypesAndAlternatives.md @@ -0,0 +1,604 @@ + +# Exercise 1: Calculating Average Speed of Formula 1 Cars in a Race using Java + + + + + +## Instructions + +### Problem Statement + +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 + +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: + +**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 + +``` + + + +## Hints + +Here are some short hints in markdown format: + +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 + +#### Step 1: Define a method to calculate the average speed of the cars + +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: + +- `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 + +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`. + +Here's the code for the `calculateAverageSpeed` method: + +``` +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); +} +``` + +#### Step 2: Call the `calculateAverageSpeed` method in the `main` method + +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. + +Here's the code for the `main` method: + +``` +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"); +} +``` + +#### 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 + + + +**Formula1RaceRunner.java** + + + +``` +import java.math.BigDecimal; + +public class Formula1RaceRunner { + + // 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; + BigDecimal totalDistance = new BigDecimal("12000"); // in meters + BigDecimal totalTime = new BigDecimal("720.5"); // in seconds + + // TODO: Call the calculateAverageSpeed method and store the result in a variable named averageSpeed. + BigDecimal averageSpeed; + + System.out.println("Average speed for the Formula 1 cars: " + averageSpeed.setScale(1, BigDecimal.ROUND_HALF_UP) + " m/s"); + } +} + + +``` + + + + + +## Solution File + + + +**Formula1RaceRunner.java** + + + +``` +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"); + } +} + +``` + + + + +## Evaluation File + + +**Evaluate.java** + + + +``` +// Evaluate.java +import org.junit.jupiter.api.Test; +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 { + + Formula1RaceRunner runner = new Formula1RaceRunner(); + IOHelper helper = new IOHelper(); + + EvaluationHelper evaluationHelper = new EvaluationHelper(); + + + @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() { + int numberOfCars = 5; + BigDecimal totalDistance = new BigDecimal("12000"); + BigDecimal totalTime = new BigDecimal("720.5"); + + BigDecimal averageSpeed = runner.calculateAverageSpeed(numberOfCars, totalDistance, totalTime); + + assertEquals(new BigDecimal("16.7"), averageSpeed.setScale(1, BigDecimal.ROUND_HALF_UP), "Average speed calculation is incorrect."); + } + + @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."); + } + +} + +``` + + + + + + +# 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 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`. + +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 public 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); + } +} + + +``` diff --git a/02-CodeChallenge/07-Conditionals.md b/02-CodeChallenge/07-Conditionals.md new file mode 100644 index 00000000..7d5a1a1e --- /dev/null +++ b/02-CodeChallenge/07-Conditionals.md @@ -0,0 +1,652 @@ + + +# Exercise 1: 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 1:** + +``` +Enter the month number (1-12): +4 +``` + +**Output:** + +``` +The name of month number 4 is April. +``` + +**Input 2:** + +``` +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"); + } +} + + +``` + + + + +# 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"); + } +} + +``` +======= + diff --git a/02-CodeChallenge/08-Loops.md b/02-CodeChallenge/08-Loops.md new file mode 100644 index 00000000..4e8bf5fa --- /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); + } +} + + +``` + + + + diff --git a/02-CodeChallenge/09-ReferenceTypes.md b/02-CodeChallenge/09-ReferenceTypes.md new file mode 100644 index 00000000..e2421ded --- /dev/null +++ b/02-CodeChallenge/09-ReferenceTypes.md @@ -0,0 +1,621 @@ +## 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"); + } +} + + +``` + + + + + + +# 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 diff --git a/02-CodeChallenge/10-ArraysAndArrayList.md b/02-CodeChallenge/10-ArraysAndArrayList.md new file mode 100644 index 00000000..4f74aabe --- /dev/null +++ b/02-CodeChallenge/10-ArraysAndArrayList.md @@ -0,0 +1,596 @@ +# 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"); + } +} + + +``` + + + + + + +# 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 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 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 diff --git a/02-CodeChallenge/14-FunctionalProgramming.md b/02-CodeChallenge/14-FunctionalProgramming.md new file mode 100644 index 00000000..c9f08272 --- /dev/null +++ b/02-CodeChallenge/14-FunctionalProgramming.md @@ -0,0 +1,519 @@ +# 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"); + } +} +``` + + + + + + +# 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 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