Java
Java
3
5
7
9
1. The main difference between a while loop and a do-while loop is that a while loop
may not execute its block at all if the condition is false initially, while a do-while loop
will always execute its block at least once before checking the condition.
2. In Java, we cannot directly cast between a boolean and an integer. However, you can
use conditional expressions to achieve similar results.
boolean b = true;
int i = b ? 1 : 0; // Convert boolean to int using conditional expression
System.out.println(i); // Output: 1
Or
int i = 1;
boolean b = i != 0; // Convert int to boolean using conditional expression
System.out.println(b); // Output: true
3. Both loops will produce the same result in sum. The choice between using i++ or ++i
does not affect the outcome.
4. In Java, a for loop consists of three parts: the initialization, the condition, and the
increment/decrement.
1. Initialization: This part is executed only once at the beginning of the loop. It
initializes the loop control variable to a starting value.
2. Condition: This part is evaluated before each iteration of the loop. If the condition
is true, the loop body is executed. If the condition is false, the loop terminates.
3. Increment/Decrement: This part is executed after each iteration of the loop. It
updates the loop control variable to a new value.
a for loop that prints the numbers from 1 to 100.
6. In Java, the scope of a variable declared in the control section of a for loop is limited
to the loop itself. Once the loop exits, the variable is no longer accessible.
7. Yes, for loops can be converted in to while and do while loops.
for loops offer simplicity, controlled iteration, efficiency, and convenience when
working with arrays and collections in Java. They are a powerful tool for handling
repetitive tasks.
8. Converting the following for loop statement to a while loop and to a do-while loop:
long sum = 0;
for (int i =0; i <=1000; i++)
sum = sum + i;
while loop
long sum = 0;
int i = 0;
while (i <= 1000) {
sum += i;
i++;
}
do while loop
long sum = 0;
int i = 0;
do {
sum += i;
i++;
} while (i <= 1000);
9. The "break" keyword is used to terminate the execution of a loop or switch statement.
When encountered, it immediately exits the loop or switch statement and continues
with the next statement after the loop or switch.
The "continue" keyword is used to skip the rest of the current iteration of a loop and
move on to the next iteration. It allows you to bypass certain statements within a loop
based on a condition, without terminating the loop entirely.
And the same goes to the second with the continue statement!
11. the problem with the converted code it the “continue” statement and that cause the
incrementation(i++) code to not be reached which result infinite loop
int i = 0;
int sum = 0;
while (i < 4) {
if (i % 3 == 0) {
i++;
} else {
sum += i;
System.out.println(sum);
i++;
}
}
12. After the break outer; statement is executed in the inner loop, the next statement to be
executed would be the next: statement. This is because the break outer; statement
causes the program to exit both the inner and outer loops, and control will resume at the
statement following the outer loop, which is the next: statement.
13. After the continue outer; statement is executed in the inner loop, the next statement to
be executed would be the next: statement. This is because the continue outer; statement
causes the program to skip the rest of the inner loop and start the next iteration of the
outer loop, and control will resume at the statement following the outer loop, which is
the next: statement.
14. The fixed error code
if (i < j) {
System.out.println(i);
} else {
System.out.println(j);
}
do {
j++;
} while (j < 10);
}
}
15. A) the error is i is not initialized
B) there is no error.
16. A) 0 0 1 0 1 2 0 1 2 3
B)
*****
*****
2 *****
3 2 *****
4 3 2 *****
C)
1xxx2xxx4xxx8xxx16xxx
1xxx2xxx4xxx8xxx
1xxx2xxx4xxx
1xxx2xxx
1xxx
D)
1G
1G3G
1G3G5G
1G3G5G7G
1G3G5G7G9G
17. The Math.random() method in Java returns a double value greater than or equal to 0.0
and less than 1.0. Therefore, the possible outputs from invoking Math.random() are
within the range of 0.0 (inclusive) to 1.0 (exclusive).
323.4 and 34 are outside the range of values that Math.random() can return, so they are
not possible outputs.
18. The issue with the code is that the conditions for assigning grades are not in the correct
order. The conditions should be arranged in descending order, from highest to lowest,
to ensure that the correct grade is assigned based on the score.
19. To rewrite the statement using a Boolean expression, we can directly assign the result
of the comparison to the newLine variable.
newLine = (count % 10 == 0);
20.
(true) && (3 > 4)
Result: true && false
The result is false.
(x > 0) || (x < 0)
Result: (1 > 0) || (1 < 0)
This simplifies to: true || false
The result is true.
(x != 0) || (x == 0)
Result: (1 != 0) || (1 == 0)
This simplifies to: true || false
The result is true.
(x >= 0) || (x < 0)
Result: (1 >= 0) || (1 < 0)
This simplifies to: true || false
The result is true.
(x != 1) == !(x == 1)
Result: (1 != 1) == !(1 == 1)
This simplifies to: false == false
The result is true.
21.
(x < y && y < z) is true
(x < y || y < z) is true
!(x < y) is false
(x + y < z) is true
(x + y < z) is true
22. The value of y will be 2. Since there is no break statement the program goes to default .
23. Using switch statement
switch (a) {
case 1:
x += 5;
break;
case 2:
x += 10;
break;
case 3:
x += 16;
break;
case 4:
x += 34;
break;
}
String dayName;
switch (day) {
case 0:
dayName = "Sunday";
break;
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
default:
dayName = "Invalid day";
break;
}
26.
- Boolean value: %b
- Character: %c
- Decimal integer: %d
- Floating-point number: %f
- String: %s
27.
A) The number of arguments does not match the number of placeholders in the format
string.
B): The number of arguments does not match the number of placeholders in the format
string.
C) There is no error.
28. A) amount is 32.320000 3.232000e+01
B) amount is 32.3200 3.2320e+01
C) false
D) Java
E) false Java
F) falseJava
29.
In Java, the precedence order of Boolean operators is as follows:
1. Logical NOT (!)
2. Logical AND (&&)
3. Logical OR (||)
According to the precedence order, the && operator has higher precedence than ||. So,
the expression is evaluated as follows:
Both && and || operators have the same precedence. So, the expression is evaluated
from left to right:
The semicolon at the end of line 3 (for (int i = 0; i < 10; i++);) should be removed.
Otherwise, the loop will not execute any statements.
The variable sum is not declared or initialized before being used in line 4 (sum += i;).
You need to declare and initialize it before using it in the loop.
The semicolon at the end of line 6 (if (i < j);) should be removed. Otherwise, the if
statement will not execute any statements.
The semicolon at the end of line 11 (while (j < 10);) should be removed. Otherwise,
the while loop will not execute any statements.
The semicolon at the end of line 14 (j++;) should be removed. Otherwise, the
increment statement will not be executed in the while loop.
The semicolon at the end of line 18 (} while (j < 10)) should be replaced with a
semicolon. Otherwise, the do-while loop will not execute any statements.
The fixed code
public class Test {
public static void main(String[] args) {
int sum = 0;
int j = 0;
for (int i = 0; i < 10; i++) {
sum += i;
}
if (i < j) {
System.out.println(i);
} else {
System.out.println(j);
}
while (j < 10) {
j++;
}
do {
j++;
} while (j < 10);} }
31. After the continue statement is executed in the nested loop, the control goes back to
the beginning of the inner loop. The continue statement skips the remaining code in
the inner loop for the current iteration and moves on to the next iteration.
The output:
1
2
1
2
2
3
32. After the break statement is executed in the nested loop, the control flow will exit the
innermost loop and continue with the next iteration of the outer loop. The break
statement terminates the inner loop prematurely when the condition i * j > 2 is met.
The output:
1
2
1
2
2
3
33. yes we can always convert while loop to for loop
the converted for loop
int sum = 0;
for (int i = 1; sum < 10000; i++) {
sum = sum + i;
}
34.
Will the following program terminate? If so, give the output.
The first program will terminate, and the output will be "balance is 1".
The second program will not terminate because it contains an infinite loop.
here is a condition if (balance < 9) continue; which uses the continue statement. This
statement will skip the remaining code in the loop and start the next iteration if the
condition is true. Since the initial value of balance is 1000, which is greater than 9,
the continue statement will not be executed.
int rows = 6;
int rows = 6;
int rows = 6;
int rows = 6;
System.out.println();
}
38.
import java.util.Scanner;
public class DaysInMonth {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the month (1-12): ");
int month = input.nextInt();
String mon ="";
switch (month) {
case 1: // January
mon = "January";
case 3: // March
mon = "March";
case 5: // May
mon = "May";
case 7: // July
mon = "July";
case 8: // August
mon = "August";
case 10: // October
mon = "October";
case 12: // December
mon = "December";
days = 31;
break;
case 4: // April
mon = "April";
case 6: // June
mon = "June";
case 9: // September
mon = "September";
case 11: // November
mon = "November";
days = 30;
break;
case 2: // February
mon ="February";
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
days = 29;
} else {
days = 28;
}
break;
default:
System.out.println("Invalid month.");
System.exit(0);
}
System.out.println(mon +" " + year + " has " + days + " days."); }}
39.
public class RandomUppercaseLetter {
public static void main(String[] args) {
char randomUppercaseLetter = (char) ('A' + Math.random() * ('Z' - 'A' + 1));
System.out.println("Random Uppercase Letter: " + randomUppercaseLetter);
}
}
40.
import java.util.Scanner;
public class IntegerCounter {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
do {
input = scanner.nextInt();
if (input > 0) {
positiveCount++; // Increment positiveCount if input is positive
} else if (input < 0) {
negativeCount++; // Increment negativeCount if input is negative
}
total += input; // Add input to the total sum
} while (input != 0);
// Prompt the user to enter the year and first day of the year
System.out.print("Enter the year: ");
int year = input.nextInt();
System.out.print("Enter the first day of the year (0 for Sunday, 1 for Monday,
etc.): ");
int firstDay = input.nextInt();
// Prompt the user to enter the year and first day of the year
System.out.print("Enter the year: ");
int year = input.nextInt();
System.out.print("Enter the first day of the year (0 for Sunday, 1 for Monday,
etc.): ");
int firstDay = input.nextInt();
// Print the leading spaces for the first day of the month
for (int j = 0; j < firstDay; j++) {
System.out.print(" ");
}
System.out.println();
}
}
}
Array Exercise
43. a) One-dimensional array P contains four elements. The names of those elements are
____P[0]___, __P[1]____, ___P[2]___ and ___P[3]______.
b) Naming an array, stating its type and specifying the number of dimensions in the
array is called ___declaring______ array.
c) In a two-dimensional array, the first index identifies ___row_____ of an element and
the second index identifies the ___column_____ of an element.
d) An m-by-n array contains __m___ rows, ____n_____ columns and ___m*n____
elements.
e) The name of the element in row 3 and column 5 of array d is ____d[2][4]________.
44. a) False. To refer to a particular location or element within an array, we specify the
name of the array and the index of the particular element, not the value.
b) True.
c) False. To indicate that 100 locations should be reserved for an integer array p, you
write the declaration as int p[100];. The square brackets should be placed before the
array name to indicate the size of the array.
d) False. An application can initialize the elements of a 15-element array to zero
without using a for statement by utilizing array initialization syntax. For example, in
Java, you can declare and initialize an array with 15 elements all set to zero as follows:
e) True
45. a) To display the value of element 6 of array f,
=> System.out.println(f[5]); // Arrays are 0-indexed in Java, so the 6th element is at
index 5
b) To initialize each of the five elements of one-dimensional integer array g to 8
=> for (int i = 0; i < g.length; i++) {
g[i] = 8;
}
c) To total the 100 elements of floating-point array c:
=> double total = 0.0;
for (int i = 0; i < c.length; i++) {
total += c[i];
}
System.out.println("Total: " + total);
d) To copy 11-element array a into the first portion of array b, which contains 34
elements:
=> int[] a = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
int[] b = new int[34];
g) Write a single statement that sets the element of t in row 0 and column 1 to zero:
=> t[0][1] = 0;
t[0][0] = 0;
t[0][1] = 0;
t[0][2] = 0;
t[1][0] = 0;
t[1][1] = 0;
t[1][2] = 0;
t[i][j] = 0;
}
j) Write a nested for statement that inputs the values for the elements of t from the user:
t[i][j] = scanner.nextInt();
k) Write a series of statements that determines and displays the smallest value in t:
smallest = t[i][j];
m) Write a statement that totals the elements of the third column of t. Do not use repetition:
n) Write a series of statements that displays the contents of t in tabular format. List the column
indices as headings across the top, and list the row indices at the left of each row:
System.out.println(" 0 1 2");
System.out.println();
}
47.
import java.util.Scanner;
public class SalesCommissions {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] counters = new int[9]; // Array of counters for each salary range
System.out.print("Enter the number of salespeople: ");
int numSalespeople = scanner.nextInt();