Topics Index

Break example output

If you need explanation Read this topic

If you need Answer Take test on this topic

Break example output
What will be the output of the following program?
class BreakExample
    public static void main(String s[])
        int sum = 0;

        for(int i = 2; i <= 10; i+=2 )
            if( i == 8 ) break;

            sum += i;

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

A. sum = 18
B. sum = 36
C. Compilation error
D. sum = 12
Topic: Using Break In for Loop To Exit

If you need explanation Read this topic

If you need Answer Take test on this topic

User comments below. All of them might not be correct.

Answer is D..

Here we have the concept of Break which is used tk exit from a loop. By using break, you can force immediate termination of a loop even though there are iterations to be completed. break can also be used inside while loop. break can also be used inside nested loops (loop inside loop).

Coming to program, Here we have initialized sum to 0. In the next step we used for loop in which i value is 2 and condition i<=10 which satisfies. i value is is incremented by 2. And in if condition i==8 executes every iteration until it becomes true. Then we got break statement which helps to terminate from loop. sum += i the i value is 8 and 4 will be added in during iteration. Result will be stored in sum and control goes to print method and prints the output as sum = 12.

Posted by Sai Ram    2014-12-22 09:53:50


"Break" Keyword is used which do not execute statements after it and move the control out of the loop.

for Loop starts with counter i=2 and increased by 2 i+=2 it runs till i<10

break;sum=sum+i will not execute and control will go out of the loop and sum will get printed which is 12.


Posted by Mânïshå Mùlchåndânï    2014-12-22 10:32:24

This dose is now closed and the winners are Sai Ram,  for 'First Correct Comment', Sai Ram, Mânïshå Mùlchåndânï,  for 'Best Comment' and Sai Ram for the 'Popular Comment'. The 'lucky liker' is Shashanka Mogaliraju. Please login into Merit Campus using facebook, to claim your recharge. Go to to raise the recharge.

Posted by Merit Campus    2014-12-23 04:09:33

© meritcampus 2019

All Rights Reserved.

Open In App