Select the correct answerWhat will be the final value of sum?int sum = 0;for (int i = 1; i <= 5; i++) { try { if (i == 3) { throw new Exception(); } sum += i; } catch (Exception e) { continue; }}System.out.println(sum);Options13121015
Question
Select the correct answerWhat will be the final value of sum?int sum = 0;for (int i = 1; i <= 5; i++) { try { if (i == 3) { throw new Exception(); } sum += i; } catch (Exception e) { continue; }}System.out.println(sum);Options13121015
Solution
The final value of sum will be 12.
Here's the step by step explanation:
-
The loop starts with i = 1. Since 1 is not equal to 3, it doesn't throw an exception. So, sum becomes 0 + 1 = 1.
-
Next, i = 2. Again, 2 is not equal to 3, so it doesn't throw an exception. Now, sum becomes 1 + 2 = 3.
-
When i = 3, it throws an exception. The catch block catches this exception and the continue statement skips the rest of the loop for this iteration. So, sum remains 3.
-
For i = 4, it doesn't throw an exception. So, sum becomes 3 + 4 = 7.
-
Finally, for i = 5, it doesn't throw an exception. So, sum becomes 7 + 5 = 12.
Therefore, the final value of sum is 12.
Similar Questions
Select the correct answerWhat will be the output of the following Java program? class CT { public static void main(String args[]) { try { int a, sum; sum = 10; for (a = -1; a < 3; ++a) sum = (sum / a); } catch(ArithmeticException e) { System.out.print("0"); } System.out.print(sum); } }Options0Compilation ErrorRuntime Error05
Select the correct answerWhat will be the output of the following Java code? class CodeTantra { public static void main(String args[]) { try { int x, sum; sum = 7; for (x = -1; x < 4; ++x) { sum = (sum / x); System.out.print(x); } } catch(ArithmeticException e) { System.out.print("0"); } } }Options0-1-10-101
What will be the output of the below program?public class Demo { public static void main(String[] args) { int sum = 0; for (int i = 0, j = 0; i < 5 & j < 5; ++i, j = i + 1) { sum += i; } System.out.println(sum); }}
Select the correct answerWhat will be the output of the following Java program?class control_statements { public static void main(String args[]) { int sum = 0; for (int u = 5, v = 5; u < 10 & v < 10; ++u, v = u + 1) sum += u; System.out.println(sum); } }Options1015compilation error26
Select the correct answerWhat will be the output of the following Java code?class array_output { public static void main(String args[]) { int array_variable[][] = {{ 1, 2, 3}, { 4 , 5, 6}, { 7, 8, 9}}; int sum = 0; for (int i = 1; i < 3; ++i) for (int j = 1; j < 3 ; ++j) sum = sum + array_variable[i][j]; System.out.print(sum / 6); } }Options8413
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.