Lab Chapter 3 Quest
Lab Chapter 3 Quest
Lab Chapter 3 Quest
== equal to
!= not equal to
3.3 Can the following conversions involving casting be allowed? If so, find the converted result.
boolean b = true;
i = (int)b;
int i = 1;
boolean b = (boolean)i;
if (y > 0) {
x = 1;
// the if statement checks if the condition inside the parenthesis is true. If it is, then the code inside the curly braces will
be executed. In this case, if ‘y’ is greater than 0, then ‘x’ will be assigned the value of 1. If ‘y’ is not greater than 0, then
the code inside the curly braces will be skipped and ‘x’ will remain unchanged.
3.5 Write an if statement that increases pay by 3% if score is greater than 90.
pay *= 1.03;
Here, we are checking if the ‘score’ is greater than 90. If it is, we are multiplying the ‘pay’ by 1.03, which increases the
pay by 3%.
3.6 Write an if statement that increases pay by 3% if score is greater than 90, otherwise increases pay by 1%.
pay *= 1.03;
} else {
pay *=1.01;
3.7 What is the printout of the code in (a) and (b) if number is 30? What if number is 35?
(a)[ if number is 30 ]
if (number % 2 == 0)
(b) [ if number is 30 ]
if (number % 2 == 0)
3.8 Suppose x = 3 and y = 2; show the output, if any, of the following code. What is the output if x = 3andy = 4? What
is the output if x = 2andy = 2? Draw a flowchart of the code.
if (x > 2) {
if (y > 2) {
z = x + y;
} else
If x=3 and y=2, the output of the code will be “x is 3”. This is because the first if statement evaluates to true (since x is
greater than 2), but the second if statement evaluates to false (since y is not greater than 2), so the else block is
executed instead, which prints “x is 3”.
If x=3 and y=4, the output of the code will be “z is 7”. This is because both if statements evaluate to true, so the code
inside the if block is executed, which sets z to the sum of x and y and then prints out the value of z.
If x=2 and y=2, there will be no output because the first if statement evaluates to false, so the code inside the if block is
skipped entirely.
x>2
Here is the flowchart of the code:
y>2
No
print(“x is “ +
z=x+y
x)
Yes
print z
3.9 Suppose x = 2 and y = 3. Show the output, if any, of the following code. What is the output if x = 3 and y = 2? What
is the output if x = 3 and y = 3? (Hint: Indent the statement correctly first.)
if (x > 2)
if (y > 2) {
int z = x + y;
} else
If x=2 and y=3, the output of the code will be “x is 2”. This is because the first if statement evaluates to false (since x is
not greater than 2), but the second if statement evaluates to true (since y is greater than 2), so the else block is executed
instead, which prints “x is 2”.
If x=3 and y=3, the output of the code will be “z is 4”. This is because both if statements evaluate to true, so the code
inside the if block is executed, which sets z to the sum of x and y and then prints out the value of z.
grade = 'D';
grade = 'C';
grade = 'B';
grade = 'A';
else
grade = 'F';
The value of the input inside the if else statement is descending which can cause the program a logical error. It must be
start from 90 down to 60 in order to execute it properly.
Forgetting necessary braces, ending an if statement in the wrong place, mistaking == for =, and dangling else
clauses are common errors in selection statements.
3.11 Which of the following statements are equivalent? Which ones are correctly indented?
Letter b and letter d are both correctly indented and equivalent however letter b is the proper way because the
statement consume more than single statement so curly brackets is needed.
if (count % 10 == 0)
newLine = true;
else
newLine = false;
The both statement are correct and executes the program the way it was intended to. In terms of neatness and space
saving, the statement (b) is much better than statement (a).
3.14 What is the output of the following code if number is 14, 15, and 30?
On the box (a), the output if the number is 14 is “14 is even”, while if the number is 15 is “15 is multiple of 5” and the
output for 30 is “30 is even 30 is multiple of 5”. On the box (b), the output if the number is 14 is “14 is even”, while if the
number is 15 is “15 is multiple of 5” and the output for 30 is “30 is multiple of 5”.
You can use Math.random() to obtain a random double value between 0.0 and 1.0, excluding 1.0.
The previous programs generate random numbers using System.currentTimeMillis(). A better approach is to use
the random() method in the Math class. Thus, (int)(Math.random() * 10) returns a random single-digit integer
(i.e., a number between 0 and 9).
3.15 Which of the following is a possible output from invoking Math.random()? 323.4, 0.5, 34, 1.0, 0.0, 0.234
All of the options you are provided are possible outputs from invoking the ‘Math.random()’ method in Java. The
Math.random()’ method returns a double value between 0.0 and 1.0, so any value within that range, such as 0.5, 1.0,0.0,
and 0.234, is a possible output. Additionally, the value returned by ‘Math.random()’ can be multiplied or manipulated to
produce a wider range of values, such as 323.4 and 34.
3.16 A. How do you generate a random integer i such that 0 <= i < 20?
‘int i = (int) (Math.random() * 20)’ generates a random double between 0 (inclusive) and 20 (exclusive), which is then
cast to an integer to get a random integer between 0 and 19.
B. How do you generate a random integer i such that 10 <= i < 20?
‘int i = (int) (Math.random() * 10) + 10’ generates a random double between random double between 0 (inclusive) and
10 (exclusive), which is then cast to an integer to get a random integer between 0 and 9. Adding 10 to the result gives us
a random integer between 10 and 19.
C. How do you generate a random integer i such that 10 <= i < 50?
‘int i = (int) (Math.random() * 40) + 10’ generates a random double between random double between 0 (inclusive) and
40 (exclusive), which is then cast to an integer to get a random integer between 0 and39. Adding 10 to the result gives us
a random integer between 10 and 49.
The logical operators !, &&, ||, and ^ can be used to create a compound Boolean expression.
Logical operators, also known as Boolean operators, operate on Boolean values to create a new Boolean value.
|| or logical disjunction
3.18 Assuming that x is 1, show the result of the following Boolean expressions.
Since the first condition is ‘true’, the result of the expression will depend only on the second equation, which is ‘false’.
Therefore, the final result of the expression will be ‘false’.
The condition ‘x>0’ is ‘true’ because ‘x’ is equal to 1, so the second part of the expression is ‘true’. The first part is the
negation of ‘x>0’, which is ‘false’. Therefore, the final result of the expression will be ‘false’.
(x > 0) || (x < 0)
Since ‘x’ is greater than 0, the first condition is ‘true’ while the other is ‘false’. Therefore, the final answer of the
expression will be ‘true’.
(x != 0) || (x == 0)
The first condition ‘x!=0’ because ‘x’ is not equal to 0. Therefore, the final result of the expression will be ‘true’.
(x >= 0) || (x < 0)
Since ‘x’ is greater than or equal to 0, the first condition is ‘true’. Therefore, the final result of the expression will be
‘true’.
(x != 1) == !(x == 1)
the first condition ‘x !=1’ is ‘false’ because ‘x’ is equal to 1. The second condition ‘!(x==1)’ is false because ‘x is equal to 1.
Therefore, both sides of the equality are ‘false’, and the final result will be ‘true’.
Small amount of code and test it before moving on to add more code is called incremental development and testing.
This approach makes testing easier, because the errors are likely in the new code you just added.
De Morgan’s law, named after Indian-born British mathematician and logician Augustus De Morgan (1806–1871), can be
used to simplify Boolean expressions.
3.19 Write a Boolean expression that evaluates to true if a number stored in variable num is between 1 and 100.
3.20 Write a Boolean expression that evaluates to true if a number stored in variable num is between 1 and 100 or the
number is negative.
return true;
3.21 Assume that x and y are int type. Which of the following are legal Java expressions?
x>y>0
This is not legal expression because it does not evaluate the way one might expect. The comparison operators (‘>’) are
evaluated from left to right, so this expression is equivalent to ‘(x > y) > 0’, which is not valid because the result of the
first comparison (‘x > y’) is a Boolean value, not an integer.
x = y && y
This is also not legal expression because it is missing a second operand for the ‘y’ variable. It should be written as ‘x =y
&& (some other condition)’
x /= y
x or y
this is an not legal expression because it does not use the correct logical operator.
x and y
this is also not legal expression because it does not use the correct logical operator.
(x != 0) || (x = 0)
This is a legal expression, but it is not recommended to use because it contains an assignment (‘x = 0’) inside a
condition.
3.22 Suppose that x is 1. What is x after the evaluation of the following expression?
For the expression (x >= 1) && (x++ > 1), since x is initially 1, the first part of the expression (x >= 1) is true. However, the
second part of the expression (x++ > 1) is false because x is incremented to 2 after the expression is evaluated.
Therefore, the overall result of the expression is false, and x is incremented to 2.
For the expression (x >=1) && (x++ > 1), since x is now 2 from the previous expression, the first part of the expression (x
> 1) is true. The second part of the expression (x++ > 1) is also true because x is incremented to 2 after the expression is
evaluated and 3 is greater than 1. Therefore, the overall result of the expression is true, and x is incremented to 3.
3.23 What is the value of the expression ch >= 'A' && ch <= 'Z' if ch is 'A', 'p', 'E', or '5'?
for ch = ‘A’, the expression evaluates to true because ‘A’ is greater than or equal to ‘A’ and less than or equal to
‘Z’.
for ch = ‘P’, the expression evaluates to true because ‘P’ is greater than or equal to ‘A’ and less than or equal to
‘Z’.
for ch = ‘E’, the expression evaluates to true because ‘E’ is greater than or equal to ‘A’ and less than or equal to
‘Z’.
for ch = ‘5’, the expression evaluates to false because ‘5’ is not greater than or equal to ‘A’ and less than or equal
to ‘Z’.
3.24 Suppose, when you run the program, you enter input 2 3 6 from the console. What is the output?
double x = input.nextDouble();
double y = input.nextDouble();
double z = input.nextDouble();
Output: “(x < y && y < z) is true” because 2 is less than 3 and 3 is less than 6.
Output: "!(x < y) is false” because ! operator negates the result true
Output: "(x + y < z) is true" because the sum of 2 and 3 is 5 which is less than 6
3.25 Write a Boolean expression that evaluates true if age is greater than 13 and less than 18.
the first condition checks if age is greater than 13 and the second condition checks if age is less than 18. Both conditions
must be true for overall expression to evaluate to true.
3.26 Write a Boolean expression that evaluates true if weight is greater than 50 pounds or height is greater than 60
inches.
weight > 50 || height > 60
the first condition checks if weight is greater than 50 pounds, and the second condition checks if height is greater than
60 inches. If either condition is true, the overall expression will evaluate is true.
3.27 Write a Boolean expression that evaluates true if weight is greater than 50 pounds and height is greater than 60
inches.
the first condition checks if weight is greater than 50 pounds, and the second condition checks if height is greater than
60 inches. Both conditions must be true for the overall expression to evaluate to true.
3.28 Write a Boolean expression that evaluates true if either weight is greater than 50 pounds or height is greater
than 60 inches, but not both.
The overall expression will evaluate to true if either weight is greater than 50 pounds or height is greater than 60 inches,
but not both. If both conditions are true or false, then the expression will evaluate to false.
A year is a leap year if it is divisible by 4 but not by 100, or if it is divisible by 400. You can use the following Boolean
expressions to check whether a year is a leap year:
The lottery program involves generating random numbers, comparing digits, and using Boolean operators
Switch Statements
The switch-expression must yield a value of char, byte, short, int, or String type and must always be enclosed in
parentheses.
The value1, . . ., and valueN must have the same data type as the value of the switch-expression.( they cannot
contain variables, such as 1 + x.)
When the value in a case statement matches the value of the switch-expression, the statements starting from
this case are executed until either a break statement or the end of the switch statement is reached
The default case used to perform actions when none of the specified cases matches the switch-expression.
The break statement immediately ends the switch statement.
3.29 What data types are required for a switch variable? If the keyword break is not used after a case is processed,
what is the next statement to be executed? Can you convert a switch statement to an equivalent if statement, or vice
versa? What are the advantages of using a switch statement?
A switch variable can only be of the following datatypes: char, byte, short, int and String (must always enclosed
with parenthesis)
If the keyword break is not used after a case is processed, the next statement to be executed will be the first
statement after the switch block.
You can convert a switch statement to an equivalent if statement or vice versa, as long as the conditions and the
code are equivalent.
The advantages of using a switch statement include:
1. Readability: when you have multiple conditions that you want to check against a single variable, a switch
statement can make the code more readable and easier to understand.
2. Efficiency: in some cases, a switch statement can be more efficient than a series of if statements, especially if the
conditions are simple and the number of cases is relatively small.
3. Maintainability: using a switch statement can make the code more maintainable, especially if you need to add
or remove cases in the future. With a switch statement, you can easily add or remove cases without having to
change the structure of the code.
3.30 What is y after the following switch statement is executed? Rewrite the code using the if-else statement.
x = 3; y = 3;
switch (x + 3) {
case 6: y = 1;
default: y += 1;
if (x+3 == 6) {
y = 1;
} else {
y += 1;
3.31 What is x after the following if-else statement is executed? Use a switch statement to rewrite it and draw the
flowchart for the new switch statement.
int x = 1, a = 3;
if (a == 1) x += 5;
else if (a == 2) x += 10;
else if (a == 3) x += 16;
else if (a == 4) x += 34;
The original code is an if else statement that sets the value of ‘x’ based on the value of ‘a’. It first checks if ‘a’ is equal to
1, and if so, it increments ‘x’ by 5. If not, it checks if ‘a’ is equal to 2, and if so, it increments ‘x’ by 10. If ‘a’ is equal to 3, it
increments ‘x’ by 16. Finally, if ‘a’ is equal to 4, it increments ‘x’ by 34.
In this case, ‘a’ is equal to 3, so the third else-if statement will be executed, incrementing ‘x’ by 16. Therefore, ‘x’ will be
equal to 17 after the execution of the if-else statement.
switch (a) {
case 1: x+=5;
break;
case 2: x +=10;
break;
case 3: x +=16;
break;
case 4: x +=34;
break;
In the rewritten statement, the value of ‘a’ is evaluated and the corresponding ‘case’ block is executed. Since ‘a’ is equal
to 3, the third ‘case’ block will be executed, incrementing ‘x’ by 16. Therefore, the final value of ‘x’ will be 17 after the
execution of the switch statement.
3.32 Write a switch statement that assigns a String variable dayName with Sunday, Monday, Tuesday, Wednesday,
Thursday, Friday, Saturday, if day is 0, 1, 2, 3, 4, 5, 6, accordingly.
import java.util.Scanner;
String dayName;
switch (day) {
break;
break;
break;
break;
break;
break;
break;
System.out.println(dayName);
Conditional Expressions
A conditional expression evaluates an expression based on a condition. Conditional expressions are in a completely
different style, with no explicit if in the statement. The syntax is:
The symbols ? and : appear together in a conditional expression. They form a conditional operator called a ternary
operator because it uses three operands. It is the only ternary operator in Java.
3.33 Suppose that, when you run the following program, you enter input 2 3 6 from the console. What is the output?
double x = input.nextDouble();
double y = input.nextDouble();
double z = input.nextDouble();
The output of the program when the input values are 2, 3, and 6 will be “sorted”.
The next three lines of code use the ‘nextDouble()’ method of the ‘Scanner’ object to read three double values
from the console and assign them to variables ‘x’, ‘y’, and ‘z’, respectively.
The last line of the code uses a ternary operator to check if the values of ‘x’, ‘y’, and ‘z’ are sorted in increasing
order. If they are, the program outputs the string “sorted”. If they are not, the program outputs the string “not
sorted”
In this case, the input values are 2, 3, and 6, which are sorted in increasing order. Therefore, the ternary operator
evaluates to true and the program outputs the string “sorted”
(a) (b)
Code (a) sets the ‘ticketPrice’ to 20 if ‘ages’ is greater than or equal to 16, otherwise it sets ‘ticketPrice’ to 10. Code (b)
prints ‘count’ followed by newline character if ‘count’ is divisible by 10, otherwise it just prints ‘counts’.
score = 3 * scale;
}else {
Score = 4 * scale;
}else{
c. System.out.println((number % 3 == 0) ? i : j);
if(number % 3 == 0){
System.out.println(i);
}else{
System.out.println(j);
System.out.printf
format specifier
%c a character ‘a’
3.36 What are the format specifiers for outputting a Boolean value, a character, a decimal integer, a floating-point
number, and a string?
Boolean value %b, character %c, decimal integer %d, floating point number %f, and string %s.
The first printf statement has too many arguments. It specifies two format specifiers, “%5d” and “%d”, but provides
three arguments.
the second statement has two format specifier but provide only one argument.
the third statements uses two format specifiers that doesn’t match with its arguments. The second arguments must
have a floating point value since he uses %f.
false
d. System.out.printf("%6s\n", "Java");
Java
false Java
false Java
Determine the order in which operators are evaluated. The expression in the parentheses is evaluated first.
(Parentheses can be nested, in which case the expression in the inner parentheses is executed first.)
3.39 List the precedence order of the Boolean operators. Evaluate the following expressions:
Multiplication first then addition. In this case, the and operator will evaluate first. Therefore, the answer is true.
Multiplication first then addition. In this case, the and operator will evaluate first. Therefore, the answer is true.
3.40 True or false? All the binary operators except = are left associative.
True
2 * 2 - 3 > 2 || 4 – 2 > 5
Confirmation dialog
showMessageDialog to display a message dialog box and showInputDialog to display an input dialog box.
3.43 How do you display a confirmation dialog? What value is returned when invoking
JOptionPane.showConfirmDialog?
Debugging
The process of finding and fixing errors in a program. Logic errors are called bugs.