What will be the output of the code given below?

public class Tester {
	public static void main(String[] args) {
		int sum = 0;
		for (int i = 2; i < 8; i += 2) {
			for (int j = 8; j > i; j -= 2) {
				if (i >= j / 2) {
					continue;
				} else {
					sum += i + j;

				}
			}
		}
		System.out.println("Sum = " + sum);
	}
}

Sum = 8

Sum = 18

Sum = 27

Sum = 36

Verified Answer
Correct Option - b
Anush said

The output of the code will be Sum = 27. Here's the explanation:
1. The outer loop runs with i values of 2, 4, and 6 (i.e., increments of 2 from 2 to less than 8).
2. The inner loop runs with j starting at 8 and decrements by 2 each time until j > i.
3. The if (i >= j / 2) condition checks whether i is greater than or equal to half of j. If true, the loop continues without adding values to sum.
4. If the condition is false, the sum of i and j is added to sum.
Here’s how the sum accumulates:

  • When i = 2 and j = 8, i + j = 10, sum becomes 10.
  • When i = 2 and j = 6, the condition i >= j / 2 is true, so it skips.
  • When i = 4 and j = 8, i + j = 12, sum becomes 22.
  • When i = 6 and j = 8, i + j = 14, sum becomes 36.
So, the final sum is 27.

To get all Self Assessment - Programming using Java Exam questions Join Telegram Group https://rebrand.ly/lex-telegram-236dee

Telegram

We're passionate about offering best placement materials and courses!! A one stop place for Placement Materials. We daily post Offcampus updates and Placement Materials.

Qtr No. 213, New Town Yehlanka Indore 454775

admin@prepflix.in

Updated on Mon, 8 Dec 2025